]> source.dussan.org Git - rspamd.git/commitdiff
[Minor] Add conversion routine for hex strings
authorVsevolod Stakhov <vsevolod@highsecure.ru>
Thu, 21 Jan 2021 15:22:30 +0000 (15:22 +0000)
committerVsevolod Stakhov <vsevolod@highsecure.ru>
Fri, 22 Jan 2021 15:58:05 +0000 (15:58 +0000)
src/libutil/str_util.c
src/libutil/str_util.h

index 2e1fd6a0d3b382af4ed50bce5bd97011d92424f3..5a44ed3112e7b736c3cc3a0ac7e03010b8a5c363 100644 (file)
@@ -519,6 +519,53 @@ rspamd_strtoul (const gchar *s, gsize len, gulong *value)
        return TRUE;
 }
 
+gboolean
+rspamd_xstrtoul (const gchar *s, gsize len, gulong *value)
+{
+       const gchar *p = s, *end = s + len;
+       gchar c;
+       gulong v = 0;
+       const gulong cutoff = G_MAXULONG / 10, cutlim = G_MAXULONG % 10;
+
+       /* Some preparations for range errors */
+       while (p < end) {
+               c = g_ascii_tolower (*p);
+               if (c >= '0' && c <= '9') {
+                       c -= '0';
+                       if (v > cutoff || (v == cutoff && (guint8)c > cutlim)) {
+                               /* Range error */
+                               *value = G_MAXULONG;
+                               return FALSE;
+                       }
+                       else {
+                               v *= 16;
+                               v += c;
+                       }
+               }
+               else if (c >= 'a' || c <= 'f') {
+                       c = c - 'a' + 10;
+                       if (v > cutoff || (v == cutoff && (guint8)c > cutlim)) {
+                               /* Range error */
+                               *value = G_MAXULONG;
+                               return FALSE;
+                       }
+                       else {
+                               v *= 16;
+                               v += c;
+                       }
+               }
+               else {
+                       *value = v;
+
+                       return FALSE;
+               }
+               p++;
+       }
+
+       *value = v;
+       return TRUE;
+}
+
 /**
  * Utility function to provide mem_pool copy for rspamd_hash_table_copy function
  * @param data string to copy
index bc7b4f4b5b47ee75044b1de78b77e9ea0c5a6418..1a11daca9c8b3bd39429d2d9421a414271b9d726 100644 (file)
@@ -130,10 +130,15 @@ rspamd_null_safe_copy (const gchar *src, gsize srclen,
 gboolean rspamd_strtol (const gchar *s, gsize len, glong *value);
 
 /*
- * Try to convert string of length to unsigned long
+ * Try to convert string of length to unsigned long
  */
 gboolean rspamd_strtoul (const gchar *s, gsize len, gulong *value);
 
+/*
+ * Try to convert a hex string of length to unsigned long
+ */
+gboolean rspamd_xstrtoul (const gchar *s, gsize len, gulong *value);
+
 /**
  * Utility function to provide mem_pool copy for rspamd_hash_table_copy function
  * @param data string to copy