From 15a3f4c54021221b814eed7927bf7950ee07a1d6 Mon Sep 17 00:00:00 2001 From: Augustin Cavalier Date: Tue, 28 Nov 2023 20:36:26 -0500 Subject: [PATCH] libroot: Add stpncpy. Imported from musl. It is in POSIX.1-2017. --- headers/posix/string.h | 1 + src/system/libroot/posix/musl/string/Jamfile | 1 + .../libroot/posix/musl/string/stpncpy.c | 33 +++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 src/system/libroot/posix/musl/string/stpncpy.c diff --git a/headers/posix/string.h b/headers/posix/string.h index 235b982e45..6d0fa08fb9 100644 --- a/headers/posix/string.h +++ b/headers/posix/string.h @@ -62,6 +62,7 @@ extern char *strcasestr(const char *string, const char *searchString); extern char *strdup(const char *string); extern char *strndup(const char* string, size_t size); extern char *stpcpy(char *dest, const char *source); +extern char *stpncpy(char *dest, const char *source, size_t size); extern size_t strlcat(char *dest, const char *source, size_t length); extern size_t strlcpy(char *dest, const char *source, size_t length); diff --git a/src/system/libroot/posix/musl/string/Jamfile b/src/system/libroot/posix/musl/string/Jamfile index ea1e43bc8f..d12b8f84ce 100644 --- a/src/system/libroot/posix/musl/string/Jamfile +++ b/src/system/libroot/posix/musl/string/Jamfile @@ -10,6 +10,7 @@ for architectureObject in [ MultiArchSubDirSetup ] { MergeObject <$(architecture)>posix_musl_string.o : memrchr.c + stpncpy.c strchrnul.c strcspn.c swab.c diff --git a/src/system/libroot/posix/musl/string/stpncpy.c b/src/system/libroot/posix/musl/string/stpncpy.c new file mode 100644 index 0000000000..d106f935de --- /dev/null +++ b/src/system/libroot/posix/musl/string/stpncpy.c @@ -0,0 +1,33 @@ +#include +#include +#include +#include + +#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) + +char *__stpncpy(char *restrict d, const char *restrict s, size_t n) +{ +#if defined(__GNUC__) && __GNUC__ > 3 + typedef size_t __attribute__((__may_alias__)) word; + word *wd; + 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) goto tail; + 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++); +tail: + memset(d, 0, n); + return d; +} + +weak_alias(__stpncpy, stpncpy); +