aboutsummaryrefslogtreecommitdiffstats
path: root/strtouh.c
diff options
context:
space:
mode:
authorMattias Andrée <maandree@kth.se>2023-04-09 20:05:12 +0200
committerMattias Andrée <maandree@kth.se>2023-04-09 20:05:12 +0200
commitbbc81527ffbbb1cb26dfd145d492bdd613cd7ae2 (patch)
tree1bdaf0b894cf933f7d96951a516b037cde2f32c1 /strtouh.c
parentImprove makefile and fix a bug (diff)
downloadlibsimple-bbc81527ffbbb1cb26dfd145d492bdd613cd7ae2.tar.gz
libsimple-bbc81527ffbbb1cb26dfd145d492bdd613cd7ae2.tar.bz2
libsimple-bbc81527ffbbb1cb26dfd145d492bdd613cd7ae2.tar.xz
Add tests and man pages
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to 'strtouh.c')
-rw-r--r--strtouh.c36
1 files changed, 34 insertions, 2 deletions
diff --git a/strtouh.c b/strtouh.c
index 7de6434..fb2f037 100644
--- a/strtouh.c
+++ b/strtouh.c
@@ -4,10 +4,10 @@
unsigned short int
-libsimple_strtouh(const char *restrict nptr, char **restrict end, int base) /* TODO test, man */
+libsimple_strtouh(const char *restrict nptr, char **restrict end, int base)
{
unsigned long int r = strtoul(nptr, end, base);
- if(r > USHRT_MAX) {
+ if (r > USHRT_MAX) {
r = USHRT_MAX;
errno = ERANGE;
}
@@ -18,9 +18,41 @@ libsimple_strtouh(const char *restrict nptr, char **restrict end, int base) /* T
#else
#include "test.h"
+static void
+add_one(char *buf)
+{
+ char *p = strchr(buf, '\0');
+ while (*--p == '9')
+ *p = '0';
+ *p += 1;
+}
+
int
main(void)
{
+ char str[128];
+ char *e;
+ sprintf(str, "0x%x", (unsigned int)USHRT_MAX);
+ errno = 0;
+ assert(strtouh(str, NULL, 0) == USHRT_MAX && !errno);
+ assert(strtouh(str, NULL, 16) == USHRT_MAX && !errno);
+ assert(strtouh(&str[2], NULL, 16) == USHRT_MAX && !errno);
+ assert(strtouh(str, NULL, 10) == 0 && !errno);
+ assert(strtouh(str, &e, 0) == USHRT_MAX && !*e && !errno);
+ assert(strtouh(str, &e, 10) == 0 && *e == 'x' && !errno);
+ sprintf(str, "0x%x ", (unsigned int)USHRT_MAX);
+ assert(strtouh(str, &e, 16) == USHRT_MAX && *e == ' ' && !errno);
+ sprintf(str, "%u", (unsigned int)USHRT_MAX);
+ assert(strtouh(str, &e, 10) == USHRT_MAX && !*e && !errno);
+ assert(strtouh("1234", &e, 10) == 1234 && !*e && !errno);
+ assert(strtouh("1234", &e, 8) == 01234 && !*e && !errno);
+ assert(strtouh("01234", &e, 0) == 01234 && !*e && !errno);
+ sprintf(str, "%u", (unsigned int)USHRT_MAX);
+ add_one(str);
+ assert(strtouh(str, &e, 10) == USHRT_MAX && !*e && errno == ERANGE);
+ errno = 0;
+ assert(!strtouh("1", &e, -10000) && errno == EINVAL);
+ errno = 0;
return 0;
}