aboutsummaryrefslogtreecommitdiffstats
path: root/strtou32.c
diff options
context:
space:
mode:
authorMattias Andrée <maandree@kth.se>2024-08-18 09:58:23 +0200
committerMattias Andrée <maandree@kth.se>2024-08-18 09:58:23 +0200
commita69f0f613687edf6c1f1ee83b462f77e8ea3c9a9 (patch)
treed976683461a0f427d2f1ef79a8732a048dd0c67b /strtou32.c
parentMerge tag '1.3' into since (diff)
parentUpdate VERSION_MINOR (diff)
downloadlibsimple-a69f0f613687edf6c1f1ee83b462f77e8ea3c9a9.tar.gz
libsimple-a69f0f613687edf6c1f1ee83b462f77e8ea3c9a9.tar.bz2
libsimple-a69f0f613687edf6c1f1ee83b462f77e8ea3c9a9.tar.xz
Merge tag '1.4' into since
Version 1.4
Diffstat (limited to '')
-rw-r--r--strtou32.c46
1 files changed, 46 insertions, 0 deletions
diff --git a/strtou32.c b/strtou32.c
new file mode 100644
index 0000000..8e20bb1
--- /dev/null
+++ b/strtou32.c
@@ -0,0 +1,46 @@
+/* See LICENSE file for copyright and license details. */
+#include "common.h"
+#ifndef TEST
+
+#define RET_MAX 4294967295ULL
+
+
+uint_least32_t
+libsimple_strtou32(const char *restrict nptr, char **restrict end, int base)
+{
+ uintmax_t r = strtoumax(nptr, end, base);
+ if (r > RET_MAX) {
+ r = RET_MAX;
+ errno = ERANGE;
+ }
+ return (uint_least32_t)r;
+}
+
+
+#else
+#include "test.h"
+
+int
+main(void)
+{
+ char *e;
+ errno = 0;
+ assert(strtou32("0xFFFFFFFF", NULL, 0) == UINT32_C(0xFFFFFFFF) && !errno);
+ assert(strtou32("0xFFFFFFFF", NULL, 16) == UINT32_C(0xFFFFFFFF) && !errno);
+ assert(strtou32("FFFFFFFF", NULL, 16) == UINT32_C(0xFFFFFFFF) && !errno);
+ assert(strtou32("0xFFFFFFFF", NULL, 10) == 0 && !errno);
+ assert(strtou32("0xFFFFFFFF", &e, 0) == UINT32_C(0xFFFFFFFF) && !*e && !errno);
+ assert(strtou32("0xFFFFFFFF ", &e, 16) == UINT32_C(0xFFFFFFFF) && *e == ' ' && !errno);
+ assert(strtou32("0xFFFFFFFF", &e, 10) == 0 && *e == 'x' && !errno);
+ assert(strtou32("4294967295", &e, 10) == UINT32_C(0xFFFFFFFF) && !*e && !errno);
+ assert(strtou32("1234", &e, 10) == 1234 && !*e && !errno);
+ assert(strtou32("1234", &e, 8) == 01234 && !*e && !errno);
+ assert(strtou32("01234", &e, 0) == 01234 && !*e && !errno);
+ assert(strtou32("4294967296", &e, 10) == UINT32_C(4294967295) && !*e && errno == ERANGE);
+ errno = 0;
+ assert(!strtou32("1", &e, -10000) && errno == EINVAL);
+ errno = 0;
+ return 0;
+}
+
+#endif