OLD | NEW |
1 #include <string.h> | 1 #include <string.h> |
2 #include <stdint.h> | 2 #include <stdint.h> |
3 #include <limits.h> | 3 #include <limits.h> |
4 | 4 |
5 #define ALIGN (sizeof(size_t)-1) | 5 #define ALIGN (sizeof(size_t) - 1) |
6 #define ONES ((size_t)-1/UCHAR_MAX) | 6 #define ONES ((size_t)-1 / UCHAR_MAX) |
7 #define HIGHS (ONES * (UCHAR_MAX/2+1)) | 7 #define HIGHS (ONES * (UCHAR_MAX / 2 + 1)) |
8 #define HASZERO(x) ((x)-ONES & ~(x) & HIGHS) | 8 #define HASZERO(x) ((x)-ONES & ~(x)&HIGHS) |
9 | 9 |
10 void *memccpy(void *restrict dest, const void *restrict src, int c, size_t n) | 10 void* memccpy(void* restrict dest, const void* restrict src, int c, size_t n) { |
11 { | 11 unsigned char* d = dest; |
12 » unsigned char *d = dest; | 12 const unsigned char* s = src; |
13 » const unsigned char *s = src; | 13 size_t *wd, k; |
14 » size_t *wd, k; | 14 const size_t* ws; |
15 » const size_t *ws; | |
16 | 15 |
17 » c = (unsigned char)c; | 16 c = (unsigned char)c; |
18 » if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) { | 17 if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) { |
19 » » for (; ((uintptr_t)s & ALIGN) && n && (*d=*s)!=c; n--, s++, d++)
; | 18 for (; ((uintptr_t)s & ALIGN) && n && (*d = *s) != c; n--, s++, d++) |
20 » » if ((uintptr_t)s & ALIGN) goto tail; | 19 ; |
21 » » k = ONES * c; | 20 if ((uintptr_t)s & ALIGN) |
22 » » wd=(void *)d; ws=(const void *)s; | 21 goto tail; |
23 » » for (; n>=sizeof(size_t) && !HASZERO(*ws^k); | 22 k = ONES * c; |
24 » » n-=sizeof(size_t), ws++, wd++) *wd = *ws; | 23 wd = (void*)d; |
25 » » d=(void *)wd; s=(const void *)ws; | 24 ws = (const void*)s; |
26 » } | 25 for (; n >= sizeof(size_t) && !HASZERO(*ws ^ k); |
27 » for (; n && (*d=*s)!=c; n--, s++, d++); | 26 n -= sizeof(size_t), ws++, wd++) |
| 27 *wd = *ws; |
| 28 d = (void*)wd; |
| 29 s = (const void*)ws; |
| 30 } |
| 31 for (; n && (*d = *s) != c; n--, s++, d++) |
| 32 ; |
28 tail: | 33 tail: |
29 » if (*s==c) return d+1; | 34 if (*s == c) |
30 » return 0; | 35 return d + 1; |
| 36 return 0; |
31 } | 37 } |
OLD | NEW |