memccpy.c 868 B

1234567891011121314151617181920212223242526272829303132
  1. #include <string.h>
  2. #include <stdlib.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. void *memccpy(void *restrict dest, const void *restrict src, int c, size_t n)
  10. {
  11. unsigned char *d = dest;
  12. const unsigned char *s = src;
  13. size_t *wd, k;
  14. const size_t *ws;
  15. c = (unsigned char)c;
  16. if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) {
  17. for (; ((uintptr_t)s & ALIGN) && n && (*d=*s)!=c; n--, s++, d++);
  18. if ((uintptr_t)s & ALIGN) goto tail;
  19. k = ONES * c;
  20. wd=(void *)d; ws=(const void *)s;
  21. for (; n>=sizeof(size_t) && !HASZERO(*ws^k);
  22. n-=sizeof(size_t), ws++, wd++) *wd = *ws;
  23. d=(void *)wd; s=(const void *)ws;
  24. }
  25. for (; n && (*d=*s)!=c; n--, s++, d++);
  26. tail:
  27. if (*s==c) return d+1;
  28. return 0;
  29. }