aboutsummaryrefslogtreecommitdiffstats
path: root/strtoh.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 /strtoh.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 'strtoh.c')
-rw-r--r--strtoh.c45
1 files changed, 42 insertions, 3 deletions
diff --git a/strtoh.c b/strtoh.c
index 990673a..1c0181a 100644
--- a/strtoh.c
+++ b/strtoh.c
@@ -4,13 +4,13 @@
signed short int
-libsimple_strtoh(const char *restrict nptr, char **restrict end, int base) /* TODO test, man */
+libsimple_strtoh(const char *restrict nptr, char **restrict end, int base)
{
signed long int r = strtol(nptr, end, base);
- if(r < SHRT_MIN) {
+ if (r < SHRT_MIN) {
r = SHRT_MIN;
errno = ERANGE;
- } else if(r > SHRT_MAX) {
+ } else if (r > SHRT_MAX) {
r = SHRT_MAX;
errno = ERANGE;
}
@@ -21,9 +21,48 @@ libsimple_strtoh(const char *restrict nptr, char **restrict end, int base) /* TO
#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)SHRT_MAX);
+ errno = 0;
+ assert(strtoh(str, NULL, 0) == SHRT_MAX && !errno);
+ assert(strtoh(str, NULL, 16) == SHRT_MAX && !errno);
+ assert(strtoh(&str[2], NULL, 16) == SHRT_MAX && !errno);
+ assert(strtoh(str, NULL, 10) == 0 && !errno);
+ assert(strtoh(str, &e, 0) == SHRT_MAX && !*e && !errno);
+ assert(strtoh(str, &e, 10) == 0 && *e == 'x' && !errno);
+ sprintf(str, "0x%x ", (unsigned int)SHRT_MAX);
+ assert(strtoh(str, &e, 16) == SHRT_MAX && *e == ' ' && !errno);
+ sprintf(str, "-%i", SHRT_MAX);
+ assert(strtoh(&str[1], &e, 10) == SHRT_MAX && !*e && !errno);
+ assert(strtoh(str, &e, 10) == -SHRT_MAX && !*e && !errno);
+ sprintf(str, "%i", SHRT_MIN);
+ assert(strtoh(str, &e, 10) == SHRT_MIN && !*e && !errno);
+ assert(strtoh("1234", &e, 10) == 1234 && !*e && !errno);
+ assert(strtoh("1234", &e, 8) == 01234 && !*e && !errno);
+ assert(strtoh("01234", &e, 0) == 01234 && !*e && !errno);
+ sprintf(str, "%i", SHRT_MAX);
+ add_one(str);
+ assert(strtoh(str, &e, 10) == SHRT_MAX && !*e && errno == ERANGE);
+ errno = 0;
+ sprintf(str, "%i", SHRT_MIN);
+ add_one(str);
+ assert(strtoh(str, &e, 10) == SHRT_MIN && !*e && errno == ERANGE);
+ errno = 0;
+ assert(!strtoh("1", &e, -10000) && errno == EINVAL);
+ errno = 0;
return 0;
}