From 5278f6def4248391a481382bd7b0042b04c829f2 Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Tue, 21 Apr 2026 23:16:50 +0800 Subject: feat: add string manipulation functions derived from musl libc This commit introduces a variety of string manipulation functions, including: - `memmem`: Searches for a substring in a memory area. - `memmove`: Safely copies memory areas, handling overlaps. - `mempcpy`: Copies memory and returns a pointer to the end of the destination. - `memrchr`: Finds the last occurrence of a character in a memory area. - `memset`: Fills a memory area with a specified value. - `rindex`: Returns the last occurrence of a character in a string. - `stpcpy` and `stpncpy`: Copies strings and returns a pointer to the end. - `strcat`, `strchr`, `strcspn`, `strlcat`, `strlcpy`, `strlen`, `strncat`, `strncmp`, `strncpy`, `strnlen`, `strpbrk`, `strrchr`, `strstr`, `strtok`, and `strtok_r`: Various string manipulation functions for concatenation, searching, and tokenization. Assembly implementations for `memcpy`, `memmove`, and `memset` are also included for optimized performance on x86_64 architectures. --- na/lib/string/strchrnul.c | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 na/lib/string/strchrnul.c (limited to 'na/lib/string/strchrnul.c') diff --git a/na/lib/string/strchrnul.c b/na/lib/string/strchrnul.c new file mode 100644 index 0000000..6fc86d1 --- /dev/null +++ b/na/lib/string/strchrnul.c @@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: MIT */ +/* Derived from musl libc (Copyright © 2005-2020 Rich Felker, et al.) */ + +#include +#include +#include + +#define ALIGN (sizeof(size_t)) +#define ONES ((size_t)-1/UCHAR_MAX) +#define HIGHS (ONES * (UCHAR_MAX/2+1)) +#define HASZERO(x) ((x)-ONES & ~(x) & HIGHS) + +char *__strchrnul(const char *s, int c) +{ + c = (unsigned char)c; + if (!c) return (char *)s + strlen(s); + +#ifdef __GNUC__ + typedef size_t __attribute__((__may_alias__)) word; + const word *w; + for (; (uintptr_t)s % ALIGN; s++) + if (!*s || *(unsigned char *)s == c) return (char *)s; + size_t k = ONES * c; + for (w = (void *)s; !HASZERO(*w) && !HASZERO(*w^k); w++); + s = (void *)w; +#endif + for (; *s && *(unsigned char *)s != c; s++); + return (char *)s; +} + +weak_alias(__strchrnul, strchrnul); -- cgit v1.2.3