diff options
| author | Richard Qin <richard.qin.x@gmail.com> | 2026-04-21 23:16:50 +0800 |
|---|---|---|
| committer | Richard Qin <richard.qin.x@gmail.com> | 2026-04-21 23:16:50 +0800 |
| commit | 5278f6def4248391a481382bd7b0042b04c829f2 (patch) | |
| tree | 6b41347c2675dfda2da34c3aec6cea11ad033fe0 /na/lib/string/strlcpy.c | |
| parent | e7b6e9453800ecf15bee5f8f1763fd8c4862f70c (diff) | |
| download | lume-5278f6def4248391a481382bd7b0042b04c829f2.tar.gz lume-5278f6def4248391a481382bd7b0042b04c829f2.tar.xz | |
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.
Diffstat (limited to 'na/lib/string/strlcpy.c')
| -rw-r--r-- | na/lib/string/strlcpy.c | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/na/lib/string/strlcpy.c b/na/lib/string/strlcpy.c new file mode 100644 index 0000000..c2a5142 --- /dev/null +++ b/na/lib/string/strlcpy.c @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: MIT */ +/* Derived from musl libc (Copyright © 2005-2020 Rich Felker, et al.) */ + +#define _BSD_SOURCE +#include <string.h> +#include <stdint.h> +#include <limits.h> + +#define ALIGN (sizeof(size_t)-1) +#define ONES ((size_t)-1/UCHAR_MAX) +#define HIGHS (ONES * (UCHAR_MAX/2+1)) +#define HASZERO(x) ((x)-ONES & ~(x) & HIGHS) + +size_t strlcpy(char *d, const char *s, size_t n) +{ + char *d0 = d; + size_t *wd; + + if (!n--) goto finish; +#ifdef __GNUC__ + typedef size_t __attribute__((__may_alias__)) word; + const word *ws; + if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) { + for (; ((uintptr_t)s & ALIGN) && n && (*d=*s); n--, s++, d++); + if (n && *s) { + wd=(void *)d; ws=(const void *)s; + for (; n>=sizeof(size_t) && !HASZERO(*ws); + n-=sizeof(size_t), ws++, wd++) *wd = *ws; + d=(void *)wd; s=(const void *)ws; + } + } +#endif + for (; n && (*d=*s); n--, s++, d++); + *d = 0; +finish: + return d-d0 + strlen(s); +} |
