Skip to content

Commit

Permalink
[glibutil] Slightly optimized gutil_parse_int()
Browse files Browse the repository at this point in the history
Avoided unnecessary duplication of the input string and removed
unnecessary errno check.
  • Loading branch information
monich committed May 5, 2021
1 parent 4cf6a5c commit 7621553
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
37 changes: 26 additions & 11 deletions src/gutil_misc.c
Expand Up @@ -36,7 +36,6 @@

#include <ctype.h>
#include <limits.h>
#include <errno.h>

void
gutil_disconnect_handlers(
Expand Down Expand Up @@ -153,36 +152,52 @@ gutil_hexdump(
return bytes_dumped;
}

/* Since 1.0.30 */
static
const char*
gutil_strstrip(
const char* str,
char** tmp)
{
/* Caller makes sure that str isn't NULL */
const gsize len = strlen(str);

if (g_ascii_isspace(str[0]) || g_ascii_isspace(str[len - 1])) {
/* Need to modify the original string */
return (*tmp = g_strstrip(gutil_memdup(str, len + 1)));
} else {
/* The original string is fine as is */
return str;
}
}

gboolean
gutil_parse_int(
const char* str,
int base,
int* value)
int* value) /* Since 1.0.30 */
{
gboolean ok = FALSE;

if (str && str[0]) {
char* str2 = g_strstrip(g_strdup(str));
char* end = str2;
char* tmp = NULL;
char* end = NULL;
const char* stripped = gutil_strstrip(str, &tmp);
gint64 l;

errno = 0;
l = g_ascii_strtoll(str2, &end, base);
ok = !*end && errno != ERANGE && l >= INT_MIN && l <= INT_MAX;
l = g_ascii_strtoll(stripped, &end, base);
ok = !*end && l >= INT_MIN && l <= INT_MAX;
if (ok && value) {
*value = (int)l;
}
g_free(str2);
g_free(tmp);
}
return ok;
}

/* since 1.0.31 */
gboolean
gutil_data_equal(
const GUtilData* data1,
const GUtilData* data2)
const GUtilData* data2) /* Since 1.0.31 */
{
if (data1 == data2) {
return TRUE;
Expand Down
12 changes: 9 additions & 3 deletions test/test_misc/test_misc.c
Expand Up @@ -175,14 +175,20 @@ test_parse_int(
g_assert(!gutil_parse_int("0 trailing garbage", 0, NULL));
g_assert(gutil_parse_int("0", 0, NULL));
g_assert(gutil_parse_int("0", 0, &value));
g_assert(value == 0);
g_assert_cmpint(value, == ,0);
g_assert(gutil_parse_int("-1", 0, &value));
g_assert_cmpint(value, == ,-1);
g_assert(gutil_parse_int("42", 0, &value));
g_assert_cmpint(value, == ,42);
g_assert(!gutil_parse_int("0x10000000000000000", 0, &value));
g_assert(!gutil_parse_int("-2147483649", 0, &value));
g_assert(!gutil_parse_int("4294967295", 0, &value));
g_assert(gutil_parse_int(" 0x7fffffff ", 0, &value));
g_assert(value == 0x7fffffff);
g_assert_cmpint(value, == ,0x7fffffff);
g_assert(gutil_parse_int(" 7fffffff ", 16, &value));
g_assert(value == 0x7fffffff);
g_assert_cmpint(value, == ,0x7fffffff);
g_assert(gutil_parse_int("7ffffffe ", 16, &value));
g_assert_cmpint(value, == ,0x7ffffffe);
g_assert(!gutil_parse_int("0xffffffff", 0, &value));
}

Expand Down

0 comments on commit 7621553

Please sign in to comment.