From 02dfb8e891a759ed2152918778f6d0a928a71cac Mon Sep 17 00:00:00 2001 From: Michael Stapelberg Date: Sun, 17 Jul 2011 15:18:45 +0200 Subject: [PATCH] use memmem and strndup from FreeBSD on Darwin (Thanks Marcus) --- include/util.h | 14 +++++++++++ src/util.c | 63 +++++++++++++++++++++++++++++++++----------------- 2 files changed, 56 insertions(+), 21 deletions(-) diff --git a/include/util.h b/include/util.h index 276ea5b9..f3ab28ba 100644 --- a/include/util.h +++ b/include/util.h @@ -164,4 +164,18 @@ char *get_process_filename(const char *prefix); */ void i3_restart(bool forget_layout); +#if defined(__OpenBSD__) || defined(__APPLE__) + +/* + * Taken from FreeBSD + * Find the first occurrence of the byte string s in byte string l. + * + */ +void *memmem(const void *l, size_t l_len, const void *s, size_t s_len); + +#endif + +#if defined(__APPLE__) +#endif + #endif diff --git a/src/util.c b/src/util.c index cc93df21..1ad43d3f 100644 --- a/src/util.c +++ b/src/util.c @@ -448,9 +448,7 @@ void i3_restart(bool forget_layout) { /* not reached */ } -#if 0 - -#if defined(__OpenBSD__) +#if defined(__OpenBSD__) || defined(__APPLE__) /* * Taken from FreeBSD @@ -458,31 +456,54 @@ void i3_restart(bool forget_layout) { * */ void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) { - register char *cur, *last; - const char *cl = (const char *)l; - const char *cs = (const char *)s; + register char *cur, *last; + const char *cl = (const char *)l; + const char *cs = (const char *)s; - /* we need something to compare */ - if (l_len == 0 || s_len == 0) - return NULL; + /* we need something to compare */ + if (l_len == 0 || s_len == 0) + return NULL; - /* "s" must be smaller or equal to "l" */ - if (l_len < s_len) - return NULL; + /* "s" must be smaller or equal to "l" */ + if (l_len < s_len) + return NULL; - /* special case where s_len == 1 */ - if (s_len == 1) - return memchr(l, (int)*cs, l_len); + /* special case where s_len == 1 */ + if (s_len == 1) + return memchr(l, (int)*cs, l_len); - /* the last position where its possible to find "s" in "l" */ - last = (char *)cl + l_len - s_len; + /* the last position where its possible to find "s" in "l" */ + last = (char *)cl + l_len - s_len; - for (cur = (char *)cl; cur <= last; cur++) - if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0) - return cur; + for (cur = (char *)cl; cur <= last; cur++) + if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0) + return cur; - return NULL; + return NULL; } #endif + +#if defined(__APPLE__) + +/* + * Taken from FreeBSD + * Returns a pointer to a new string which is a duplicate of the + * string, but only copies at most n characters. + * + */ +char *strndup(const char *str, size_t n) { + size_t len; + char *copy; + + for (len = 0; len < n && str[len]; len++) + continue; + + if ((copy = malloc(len + 1)) == NULL) + return (NULL); + memcpy(copy, str, len); + copy[len] = '\0'; + return (copy); +} + #endif -- 2.39.5