github.com/afumu/libc@v0.0.6/musl/src/string/stpncpy.c (about)

     1  #include <string.h>
     2  #include <stdint.h>
     3  #include <limits.h>
     4  
     5  #define ALIGN (sizeof(size_t)-1)
     6  #define ONES ((size_t)-1/UCHAR_MAX)
     7  #define HIGHS (ONES * (UCHAR_MAX/2+1))
     8  #define HASZERO(x) ((x)-ONES & ~(x) & HIGHS)
     9  
    10  char *__stpncpy(char *restrict d, const char *restrict s, size_t n)
    11  {
    12  #ifdef __GNUC__
    13  	typedef size_t __attribute__((__may_alias__)) word;
    14  	word *wd;
    15  	const word *ws;
    16  	if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) {
    17  		for (; ((uintptr_t)s & ALIGN) && n && (*d=*s); n--, s++, d++);
    18  		if (!n || !*s) goto tail;
    19  		wd=(void *)d; ws=(const void *)s;
    20  		for (; n>=sizeof(size_t) && !HASZERO(*ws);
    21  		       n-=sizeof(size_t), ws++, wd++) *wd = *ws;
    22  		d=(void *)wd; s=(const void *)ws;
    23  	}
    24  #endif
    25  	for (; n && (*d=*s); n--, s++, d++);
    26  tail:
    27  	memset(d, 0, n);
    28  	return d;
    29  }
    30  
    31  weak_alias(__stpncpy, stpncpy);
    32