Hash :
58c1fe7a
Author :
Thomas de Grivel
Date :
2024-09-25T17:43:53
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
/* kc3
* Copyright 2022,2023,2024 kmx.io <contact@kmx.io>
*
* Permission is hereby granted to use this software granted the above
* copyright notice and this permission paragraph are included in all
* copies and substantial portions of this software.
*
* THIS SOFTWARE IS PROVIDED "AS-IS" WITHOUT ANY GUARANTEE OF
* PURPOSE AND PERFORMANCE. IN NO EVENT WHATSOEVER SHALL THE
* AUTHOR BE CONSIDERED LIABLE FOR THE USE AND PERFORMANCE OF
* THIS SOFTWARE.
*/
#include "assert.h"
#include "buf.h"
#include "ident.h"
#include "io.h"
#include "sh.h"
#include "str.h"
#include "tag.h"
s_str * sh_escape (const s_str *src, s_str *dest)
{
bool allowed;
s_buf buf = {0};
bool escape;
s_ident ident;
s_str s;
character s_c;
s_str t;
character t_c;
s_tag tag = {0};
s_str tmp = {0};
assert(src);
assert(dest);
if (! src->size)
return str_init_1(dest, NULL, "\"\"");
ident_init(&ident, sym_1("Sh"), sym_1("allowed"));
if (! ident_get(&ident, &tag)) {
err_puts("sh_escape: Sh.allowed is not defined");
assert(! "sh_escape: Sh.allowed is not defined");
return NULL;
}
if (tag.type != TAG_STR) {
err_puts("sh_escape: Sh.allowed is not a Str");
assert(! "sh_escape: Sh.allowed is not a Str");
goto ko;
}
escape = false;
s = *src;
while (str_read_character_utf8(&s, &s_c) > 0) {
allowed = false;
t = tag.data.str;
while (str_read_character_utf8(&t, &t_c) > 0) {
if (s_c == t_c) {
allowed = true;
break;
}
}
if (! allowed)
escape = true;
}
tag_clean(&tag);
if (! escape)
return str_init_copy(dest, src);
ident_init(&ident, sym_1("Sh"), sym_1("reserved"));
if (! ident_get(&ident, &tag)) {
err_puts("sh_escape: Sh.reserved is not defined");
assert(! "sh_escape: Sh.reserved is not defined");
return NULL;
}
if (tag.type != TAG_STR) {
err_puts("sh_escape: Sh.reserved is not a Str");
assert(! "sh_escape: Sh.reserved is not a Str");
goto ko;
}
if (! buf_init_alloc(&buf, (src->size + 1) * 2))
goto ko;
if (buf_write_1(&buf, "\"") <= 0)
goto ko;
s = *src;
while (str_read_character_utf8(&s, &s_c) > 0) {
t = tag.data.str;
while (str_read_character_utf8(&t, &t_c) > 0) {
if (s_c == t_c) {
if (buf_write_1(&buf, "\\") <= 0)
goto ko;
break;
}
}
if (buf_write_character_utf8(&buf, s_c) <= 0)
goto ko;
}
tag_clean(&tag);
if (buf_write_1(&buf, "\"") <= 0)
goto ko_buf;
if (! buf_read_to_str(&buf, &tmp))
goto ko_buf;
buf_clean(&buf);
*dest = tmp;
return dest;
ko:
tag_clean(&tag);
ko_buf:
buf_clean(&buf);
return NULL;
}