diff options
author | Mattias Andrée <maandree@kth.se> | 2018-10-22 19:57:13 +0200 |
---|---|---|
committer | Mattias Andrée <maandree@kth.se> | 2018-10-22 19:57:13 +0200 |
commit | b6f3b8d1e7161441303e518febabcb5a7958f1f3 (patch) | |
tree | 703f9b353518ab7bffb344d38251106ddd477534 /strnstarts.c | |
parent | Add strn{,case}chr{,nul}, strnend, and strrn{,case}chr (diff) | |
download | libsimple-b6f3b8d1e7161441303e518febabcb5a7958f1f3.tar.gz libsimple-b6f3b8d1e7161441303e518febabcb5a7958f1f3.tar.bz2 libsimple-b6f3b8d1e7161441303e518febabcb5a7958f1f3.tar.xz |
Add strn{case}{starts,ends}
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to '')
-rw-r--r-- | strnstarts.c | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/strnstarts.c b/strnstarts.c new file mode 100644 index 0000000..727cf3e --- /dev/null +++ b/strnstarts.c @@ -0,0 +1,49 @@ +/* See LICENSE file for copyright and license details. */ +#include "libsimple.h" +#ifndef TEST + + +int +libsimple_strnstarts(const char *s_, const char *t, size_t n) +{ + char *s = *(char **)(void *)&s_; + size_t len = strlen(t); + n = strnlen(s, n); + if (n < len) + return 0; + return !strncmp(s, t, len); +} + + +#else +#include "test.h" + +int +main(void) +{ + size_t n, i, j; + char buf[10]; + for (n = 0; n <= 8; n++) { + assert(libsimple_strnstarts("abcABC", "", n) == 1); + assert(libsimple_strnstarts("ABCabc", "", n) == 1); + assert(libsimple_strnstarts("123456", "", n) == 1); + for (i = 0; i < 7; i++) { + for (j = 1; j < 8 - i; j++) { + strcpy(buf, &"abcABCx"[i])[j] = '\0'; + assert(libsimple_strnstarts("abcABC", buf, n) == (i == 0 && j < 7 && n >= j)); + assert(libsimple_strnstarts("ABCabc", buf, n) == (i == 3 && j < 4 && n >= j)); + strcpy(buf, &"ABCabcx"[i])[j] = '\0'; + assert(libsimple_strnstarts("abcABC", buf, n) == (i == 3 && j < 4 && n >= j)); + assert(libsimple_strnstarts("ABCabc", buf, n) == (i == 0 && j < 7 && n >= j)); + strcpy(buf, &"1234567"[i])[j] = '\0'; + assert(libsimple_strnstarts("123456", buf, n) == (i == 0 && j < 7 && n >= j)); + assert(libsimple_strnstarts("zzzzzz", buf, n) == 0); + strcpy(buf, &"aaaaaaa"[i])[j] = '\0'; + assert(libsimple_strnstarts("zzzzzz", buf, n) == 0); + } + } + } + return 0; +} + +#endif |