From: Karel Zak Date: Thu, 12 Oct 2023 20:12:58 +0000 (+0200) Subject: lib/mbsalign: calculate size of decoded string X-Git-Tag: v2.40-rc1~195 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=6b7247411d9ddfcfeb0933b3ab44bf295c071f7b;p=thirdparty%2Futil-linux.git lib/mbsalign: calculate size of decoded string The "safe" encoding replaces each unsafe byte with \x, the new function mbs_safe_decoded_size() calculates the original size of the string. Signed-off-by: Karel Zak --- diff --git a/include/mbsalign.h b/include/mbsalign.h index 6e56755829..c1426105c1 100644 --- a/include/mbsalign.h +++ b/include/mbsalign.h @@ -55,6 +55,7 @@ extern size_t mbs_width(const char *s); extern char *mbs_safe_encode(const char *s, size_t *width); extern char *mbs_safe_encode_to_buffer(const char *s, size_t *width, char *buf, const char *safechars); extern size_t mbs_safe_encode_size(size_t bytes); +extern size_t mbs_safe_decode_size(const char *s); extern char *mbs_invalid_encode(const char *s, size_t *width); extern char *mbs_invalid_encode_to_buffer(const char *s, size_t *width, char *buf); diff --git a/lib/mbsalign.c b/lib/mbsalign.c index 7b8f5a665d..b4ab7becdd 100644 --- a/lib/mbsalign.c +++ b/lib/mbsalign.c @@ -310,11 +310,32 @@ char *mbs_invalid_encode_to_buffer(const char *s, size_t *width, char *buf) return buf; } +/* + * Guess size + */ size_t mbs_safe_encode_size(size_t bytes) { return (bytes * 4) + 1; } +/* + * Count size of the original string in bytes (count \x?? as one byte) + */ +size_t mbs_safe_decode_size(const char *p) +{ + size_t bytes = 0; + + while (p && *p) { + if (*p == '\\' && *(p + 1) == 'x' && + isxdigit(*(p + 2)) && isxdigit(*(p + 3))) + p += 4; + else + p++; + bytes++; + } + return bytes; +} + /* * Returns allocated string where all control and non-printable chars are * replaced with \x?? hex sequence.