From 28f764b3b367a7e97481fe66b19a11cac5403b09 Mon Sep 17 00:00:00 2001 From: Vsevolod Stakhov Date: Wed, 20 Oct 2021 10:38:34 +0100 Subject: [PATCH] [Minor] Add helper to convert a string to a uint64 number --- src/libutil/str_util.c | 57 +++++++++++++++++++++++++++--------------- src/libutil/str_util.h | 1 + 2 files changed, 38 insertions(+), 20 deletions(-) diff --git a/src/libutil/str_util.c b/src/libutil/str_util.c index fc53a8711..6cee32243 100644 --- a/src/libutil/str_util.c +++ b/src/libutil/str_util.c @@ -526,6 +526,28 @@ rspamd_strtol (const gchar *s, gsize len, glong *value) /* * Try to convert string of length to long */ +#define CONV_STR_LIM_DECIMAL(max_num) do { \ + while (p < end) { \ + c = *p; \ + if (c >= '0' && c <= '9') { \ + c -= '0'; \ + if (v > cutoff || (v == cutoff && (guint8)c > cutlim)) { \ + *value = (max_num); \ + return FALSE; \ + } \ + else { \ + v *= 10; \ + v += c; \ + } \ + } \ + else { \ + *value = v; \ + return FALSE; \ + } \ + p++; \ + } \ +} while(0) + gboolean rspamd_strtoul (const gchar *s, gsize len, gulong *value) { @@ -535,27 +557,22 @@ rspamd_strtoul (const gchar *s, gsize len, gulong *value) const gulong cutoff = G_MAXULONG / 10, cutlim = G_MAXULONG % 10; /* Some preparations for range errors */ - while (p < end) { - c = *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 *= 10; - v += c; - } - } - else { - *value = v; + CONV_STR_LIM_DECIMAL(G_MAXULONG); - return FALSE; - } - p++; - } + *value = v; + return TRUE; +} + +gboolean +rspamd_strtou64 (const gchar *s, gsize len, guint64 *value) +{ + const gchar *p = s, *end = s + len; + gchar c; + guint64 v = 0; + const guint64 cutoff = G_MAXUINT64 / 10, cutlim = G_MAXUINT64 % 10; + + /* Some preparations for range errors */ + CONV_STR_LIM_DECIMAL(G_MAXUINT64); *value = v; return TRUE; diff --git a/src/libutil/str_util.h b/src/libutil/str_util.h index e5e4cfb76..b08dd56ad 100644 --- a/src/libutil/str_util.h +++ b/src/libutil/str_util.h @@ -141,6 +141,7 @@ gboolean rspamd_strtol (const gchar *s, gsize len, glong *value); * Try to convert a string of length to unsigned long */ gboolean rspamd_strtoul (const gchar *s, gsize len, gulong *value); +gboolean rspamd_strtou64 (const gchar *s, gsize len, guint64 *value); /* * Try to convert a hex string of length to unsigned long -- 2.39.5