[PATCH 3/8] hex-escape: add function to decode escaped string in-place

Jani Nikula jani at nikula.org
Sat Mar 31 15:17:23 PDT 2012


Add function hex_decode_inplace() to decode the input string onto
itself.

Signed-off-by: Jani Nikula <jani at nikula.org>

---

This could be folded to "hex-escape: (en|de)code strings to/from
restricted character set".
---
 util/hex-escape.c |   62 ++++++++++++++++++++++++++++++----------------------
 util/hex-escape.h |    6 +++++
 2 files changed, 42 insertions(+), 26 deletions(-)

diff --git a/util/hex-escape.c b/util/hex-escape.c
index 9de79df..e794f98 100644
--- a/util/hex-escape.c
+++ b/util/hex-escape.c
@@ -98,38 +98,15 @@ hex_encode (void *ctx, const char *in, char **out, size_t *out_size)
     return HEX_SUCCESS;
 }
 
-hex_status_t
-hex_decode (void *ctx, const char *in, char **out, size_t * out_size)
+/* Note: This must succeed for p == q to support hex_decode_inplace(). */
+static hex_status_t
+hex_decode_internal (const char *p, unsigned char *q)
 {
-
     char buf[3];
-
-    const char *p;
-    unsigned char *q;
-
-    size_t escape_count = 0;
-    size_t needed = 0;
-
-    assert (ctx); assert (in); assert (out); assert (out_size);
-
-    size_t len = strlen (in);
-
-    for (p = in; *p; p++)
-	escape_count += (*p == escape_char);
-
-    needed = len - escape_count * 2 + 1;
-
-    if (!maybe_realloc (ctx, needed, out, out_size))
-	return HEX_OUT_OF_MEMORY;
-
-    p = in;
-    q = (unsigned char *) *out;
     buf[2] = 0;
 
     while (*p) {
-
 	if (*p == escape_char) {
-
 	    char *endp;
 
 	    if (!isxdigit ((unsigned char) p[1]) ||
@@ -155,3 +132,36 @@ hex_decode (void *ctx, const char *in, char **out, size_t * out_size)
 
     return HEX_SUCCESS;
 }
+
+hex_status_t
+hex_decode_inplace (char *p)
+{
+    return hex_decode_internal (p, (unsigned char *) p);
+}
+
+hex_status_t
+hex_decode (void *ctx, const char *in, char **out, size_t * out_size)
+{
+    const char *p;
+    unsigned char *q;
+
+    size_t escape_count = 0;
+    size_t needed = 0;
+
+    assert (ctx); assert (in); assert (out); assert (out_size);
+
+    size_t len = strlen (in);
+
+    for (p = in; *p; p++)
+	escape_count += (*p == escape_char);
+
+    needed = len - escape_count * 2 + 1;
+
+    if (!maybe_realloc (ctx, needed, out, out_size))
+	return HEX_OUT_OF_MEMORY;
+
+    p = in;
+    q = (unsigned char *) *out;
+
+    return hex_decode_internal (p, q);
+}
diff --git a/util/hex-escape.h b/util/hex-escape.h
index e409626..be70ad2 100644
--- a/util/hex-escape.h
+++ b/util/hex-escape.h
@@ -29,4 +29,10 @@ hex_encode (void *talloc_ctx, const char *in, char **out,
 hex_status_t
 hex_decode (void *talloc_ctx, const char *in, char **out,
             size_t *out_size);
+
+/*
+ * Decode 'in' onto itself.
+ */
+hex_status_t
+hex_decode_inplace (char *in);
 #endif
-- 
1.7.5.4



More information about the notmuch mailing list