Skip to content

Commit 6f7520d

Browse files
committed
Add portable memmem fallback for systems without it
1 parent c59d0c4 commit 6f7520d

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

c_src/py_reactor_buffer.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,30 @@
2929
#include <errno.h>
3030
#include <string.h>
3131

32+
/* Portable memmem fallback for systems that don't have it.
33+
* memmem is available on: Linux (glibc), macOS, FreeBSD >= 13
34+
* Not available on: older BSDs, some embedded systems */
35+
#if !defined(__GLIBC__) && !defined(__APPLE__) && !defined(__FreeBSD__)
36+
static void *portable_memmem(const void *haystack, size_t haystacklen,
37+
const void *needle, size_t needlelen) {
38+
if (needlelen == 0) return (void *)haystack;
39+
if (needlelen > haystacklen) return NULL;
40+
41+
const unsigned char *h = haystack;
42+
const unsigned char *n = needle;
43+
const unsigned char *end = h + haystacklen - needlelen + 1;
44+
45+
while (h < end) {
46+
h = memchr(h, n[0], end - h);
47+
if (h == NULL) return NULL;
48+
if (memcmp(h, n, needlelen) == 0) return (void *)h;
49+
h++;
50+
}
51+
return NULL;
52+
}
53+
#define memmem portable_memmem
54+
#endif
55+
3256
/* Resource type - initialized in py_nif.c */
3357
ErlNifResourceType *REACTOR_BUFFER_RESOURCE_TYPE = NULL;
3458

0 commit comments

Comments
 (0)