Skip to content

Commit

Permalink
add xstrnstr
Browse files Browse the repository at this point in the history
  • Loading branch information
yamt committed Jul 29, 2023
1 parent 5f89e93 commit 41af8e5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/util.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#define _DARWIN_C_SOURCE /* strnstr */
#define _GNU_SOURCE /* strnlen */

#include <assert.h>
#include <errno.h>
#include <stdlib.h>
Expand Down Expand Up @@ -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
}
2 changes: 2 additions & 0 deletions lib/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

0 comments on commit 41af8e5

Please sign in to comment.