github.com/afumu/libc@v0.0.6/musl/src/string/strlcpy.c (about) 1 #define _BSD_SOURCE 2 #include <string.h> 3 #include <stdint.h> 4 #include <limits.h> 5 6 #define ALIGN (sizeof(size_t)-1) 7 #define ONES ((size_t)-1/UCHAR_MAX) 8 #define HIGHS (ONES * (UCHAR_MAX/2+1)) 9 #define HASZERO(x) ((x)-ONES & ~(x) & HIGHS) 10 11 size_t strlcpy(char *d, const char *s, size_t n) 12 { 13 char *d0 = d; 14 size_t *wd; 15 16 if (!n--) goto finish; 17 #ifdef __GNUC__ 18 typedef size_t __attribute__((__may_alias__)) word; 19 const word *ws; 20 if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) { 21 for (; ((uintptr_t)s & ALIGN) && n && (*d=*s); n--, s++, d++); 22 if (n && *s) { 23 wd=(void *)d; ws=(const void *)s; 24 for (; n>=sizeof(size_t) && !HASZERO(*ws); 25 n-=sizeof(size_t), ws++, wd++) *wd = *ws; 26 d=(void *)wd; s=(const void *)ws; 27 } 28 } 29 #endif 30 for (; n && (*d=*s); n--, s++, d++); 31 *d = 0; 32 finish: 33 return d-d0 + strlen(s); 34 }