]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
lib/mbsalign: calculate size of decoded string
authorKarel Zak <kzak@redhat.com>
Thu, 12 Oct 2023 20:12:58 +0000 (22:12 +0200)
committerKarel Zak <kzak@redhat.com>
Mon, 23 Oct 2023 19:54:00 +0000 (21:54 +0200)
The "safe" encoding replaces each unsafe byte with \x<hex>, the new
function mbs_safe_decoded_size() calculates the original size of the
string.

Signed-off-by: Karel Zak <kzak@redhat.com>
include/mbsalign.h
lib/mbsalign.c

index 6e56755829dc1c700da3413ba25c7d4861cf9eb6..c1426105c1f080599698f11e47f0f35ec45217a5 100644 (file)
@@ -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);
index 7b8f5a665d9f77af0562a2012f52a0fb54382458..b4ab7becdda0cfaea8a665423975b9f367c2f575 100644 (file)
@@ -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.