commit 6618db9: [Minor] Add conversion routine for hex strings

Vsevolod Stakhov vsevolod at highsecure.ru
Fri Jan 22 16:00:29 UTC 2021


Author: Vsevolod Stakhov
Date: 2021-01-21 15:22:30 +0000
URL: https://github.com/rspamd/rspamd/commit/6618db9e85543e95fe1029dd6506204025e4c492

[Minor] Add conversion routine for hex strings

---
 src/libutil/str_util.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++
 src/libutil/str_util.h |  7 ++++++-
 2 files changed, 53 insertions(+), 1 deletion(-)

diff --git a/src/libutil/str_util.c b/src/libutil/str_util.c
index 2e1fd6a0d..5a44ed311 100644
--- a/src/libutil/str_util.c
+++ b/src/libutil/str_util.c
@@ -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
diff --git a/src/libutil/str_util.h b/src/libutil/str_util.h
index bc7b4f4b5..1a11daca9 100644
--- a/src/libutil/str_util.h
+++ b/src/libutil/str_util.h
@@ -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 a 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


More information about the Commits mailing list