strlcpy.c 833 B

12345678910111213141516171819202122232425262728293031323334
  1. #define _BSD_SOURCE
  2. #include <string.h>
  3. #include <stdint.h>
  4. #include <limits.h>
  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. size_t strlcpy(char *d, const char *s, size_t n)
  10. {
  11. char *d0 = d;
  12. size_t *wd;
  13. if (!n--) goto finish;
  14. #ifdef __GNUC__
  15. typedef size_t __attribute__((__may_alias__)) word;
  16. const word *ws;
  17. if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) {
  18. for (; ((uintptr_t)s & ALIGN) && n && (*d=*s); n--, s++, d++);
  19. if (n && *s) {
  20. wd=(void *)d; ws=(const void *)s;
  21. for (; n>=sizeof(size_t) && !HASZERO(*ws);
  22. n-=sizeof(size_t), ws++, wd++) *wd = *ws;
  23. d=(void *)wd; s=(const void *)ws;
  24. }
  25. }
  26. #endif
  27. for (; n && (*d=*s); n--, s++, d++);
  28. *d = 0;
  29. finish:
  30. return d-d0 + strlen(s);
  31. }