aboutsummaryrefslogtreecommitdiffstats
path: root/strtoi16.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 /strtoi16.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--strtoi16.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/strtoi16.c b/strtoi16.c
new file mode 100644
index 0000000..e247e19
--- /dev/null
+++ b/strtoi16.c
@@ -0,0 +1,54 @@
+/* See LICENSE file for copyright and license details. */
+#include "common.h"
+#ifndef TEST
+
+#define RET_MAX 32767LL
+#define RET_MIN (-RET_MAX - 1LL)
+
+
+int_least16_t
+libsimple_strtoi16(const char *restrict nptr, char **restrict end, int base)
+{
+ intmax_t r = strtoimax(nptr, end, base);
+ if (r < RET_MIN) {
+ r = RET_MIN;
+ errno = ERANGE;
+ } else if (r > RET_MAX) {
+ r = RET_MAX;
+ errno = ERANGE;
+ }
+ return (int_least16_t)r;
+}
+
+
+#else
+#include "test.h"
+
+int
+main(void)
+{
+ char *e;
+ errno = 0;
+ assert(strtoi16("0x7FFF", NULL, 0) == INT16_C(0x7FFF) && !errno);
+ assert(strtoi16("0x7FFF", NULL, 16) == INT16_C(0x7FFF) && !errno);
+ assert(strtoi16("7FFF", NULL, 16) == INT16_C(0x7FFF) && !errno);
+ assert(strtoi16("0x7FFF", NULL, 10) == 0 && !errno);
+ assert(strtoi16("0x7FFF", &e, 0) == INT16_C(0x7FFF) && !*e && !errno);
+ assert(strtoi16("0x7FFF ", &e, 16) == INT16_C(0x7FFF) && *e == ' ' && !errno);
+ assert(strtoi16("0x7FFF", &e, 10) == 0 && *e == 'x' && !errno);
+ assert(strtoi16("32767", &e, 10) == INT16_C(0x7FFF) && !*e && !errno);
+ assert(strtoi16("-32767", &e, 10) == INT16_C(-32767) && !*e && !errno);
+ assert(strtoi16("-32768", &e, 10) == INT16_C(-32768) && !*e && !errno);
+ assert(strtoi16("1234", &e, 10) == 1234 && !*e && !errno);
+ assert(strtoi16("1234", &e, 8) == 01234 && !*e && !errno);
+ assert(strtoi16("01234", &e, 0) == 01234 && !*e && !errno);
+ assert(strtoi16("32768", &e, 10) == INT16_C(32767) && !*e && errno == ERANGE);
+ errno = 0;
+ assert(strtoi16("-32769", &e, 10) == INT16_C(-32768) && !*e && errno == ERANGE);
+ errno = 0;
+ assert(!strtoi16("1", &e, -10000) && errno == EINVAL);
+ errno = 0;
+ return 0;
+}
+
+#endif