From bbc81527ffbbb1cb26dfd145d492bdd613cd7ae2 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sun, 9 Apr 2023 20:05:12 +0200 Subject: Add tests and man pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mattias Andrée --- strtohh.c | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) (limited to 'strtohh.c') diff --git a/strtohh.c b/strtohh.c index da68c86..3fb21b8 100644 --- a/strtohh.c +++ b/strtohh.c @@ -4,13 +4,13 @@ signed char -libsimple_strtohh(const char *restrict nptr, char **restrict end, int base) /* TODO test, man */ +libsimple_strtohh(const char *restrict nptr, char **restrict end, int base) { signed long int r = strtol(nptr, end, base); - if(r < SCHAR_MIN) { + if (r < SCHAR_MIN) { r = SCHAR_MIN; errno = ERANGE; - } else if(r > SCHAR_MAX) { + } else if (r > SCHAR_MAX) { r = SCHAR_MAX; errno = ERANGE; } @@ -21,9 +21,48 @@ libsimple_strtohh(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)SCHAR_MAX); + errno = 0; + assert(strtohh(str, NULL, 0) == SCHAR_MAX && !errno); + assert(strtohh(str, NULL, 16) == SCHAR_MAX && !errno); + assert(strtohh(&str[2], NULL, 16) == SCHAR_MAX && !errno); + assert(strtohh(str, NULL, 10) == 0 && !errno); + assert(strtohh(str, &e, 0) == SCHAR_MAX && !*e && !errno); + assert(strtohh(str, &e, 10) == 0 && *e == 'x' && !errno); + sprintf(str, "0x%x ", (unsigned int)SCHAR_MAX); + assert(strtohh(str, &e, 16) == SCHAR_MAX && *e == ' ' && !errno); + sprintf(str, "-%i", SCHAR_MAX); + assert(strtohh(&str[1], &e, 10) == SCHAR_MAX && !*e && !errno); + assert(strtohh(str, &e, 10) == -SCHAR_MAX && !*e && !errno); + sprintf(str, "%i", SCHAR_MIN); + assert(strtohh(str, &e, 10) == SCHAR_MIN && !*e && !errno); + assert(strtohh("12", &e, 10) == 12 && !*e && !errno); + assert(strtohh("12", &e, 8) == 012 && !*e && !errno); + assert(strtohh("012", &e, 0) == 012 && !*e && !errno); + sprintf(str, "%i", SCHAR_MAX); + add_one(str); + assert(strtohh(str, &e, 10) == SCHAR_MAX && !*e && errno == ERANGE); + errno = 0; + sprintf(str, "%i", SCHAR_MIN); + add_one(str); + assert(strtohh(str, &e, 10) == SCHAR_MIN && !*e && errno == ERANGE); + errno = 0; + assert(!strtohh("1", &e, -10000) && errno == EINVAL); + errno = 0; return 0; } -- cgit v1.2.3-70-g09d2