diff --git a/lib/util.c b/lib/util.c index 1f0191a0..d43b8e97 100644 --- a/lib/util.c +++ b/lib/util.c @@ -1,3 +1,6 @@ +#define _DARWIN_C_SOURCE /* strnstr */ +#define _GNU_SOURCE /* strnlen */ + #include #include #include @@ -41,3 +44,25 @@ zalloc(size_t sz) return p; } #endif + +char * +xstrnstr(const char *haystack, const char *needle, size_t len) +{ +#if defined(__APPLE__) + return strnstr(haystack, needle, len); +#else + size_t haystack_len = strnlen(haystack, len); + size_t needle_len = strlen(needle); + if (needle_len > haystack_len) { + return NULL; + } + size_t max_offset = haystack_len - needle_len; + size_t i; + for (i = 0; i <= max_offset; i++) { + if (!memcmp(&haystack[i], needle, needle_len)) { + return (char *)&haystack[i]; /* discard const */ + } + } + return NULL; +#endif +} diff --git a/lib/util.h b/lib/util.h index 302c7fb3..82178d32 100644 --- a/lib/util.h +++ b/lib/util.h @@ -19,3 +19,5 @@ void *__must_check zalloc(size_t sz) __malloc_like __alloc_size(1); #define ZERO(p) memset(p, 0, sizeof(*p)) #define HOWMANY(a, b) ((a + (b - 1)) / b) + +char *xstrnstr(const char *haystack, const char *needle, size_t len);