strlcpy.c 777 B

1234567891011121314151617181920212223242526272829303132
  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <limits.h>
  5. #include "libc.h"
  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. size_t strlcpy(char *d, const char *s, size_t n)
  11. {
  12. char *d0 = d;
  13. size_t *wd;
  14. const size_t *ws;
  15. if (!n--) goto finish;
  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) {
  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. }
  25. for (; n && (*d=*s); n--, s++, d++);
  26. *d = 0;
  27. finish:
  28. return d-d0 + strlen(s);
  29. }