1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| | #include <string.h>
#include <stdint.h>
#define aliases __attribute__((__may_alias__))
#define byte_repeat(x) ((size_t)~0 / 0xff * (x))
#define word_has_zero(x) (((x) - byte_repeat(0x01)) & ~(x) & byte_repeat(0x80))
void *memccpy(void *restrict _d, const void *restrict _s, int i, size_t n)
{
i = (unsigned char)i;
unsigned char *d = _d;
const unsigned char *s = _s;
size_t aliases *wd;
const size_t aliases *ws, wi = byte_repeat(i);
if (n < sizeof(size_t) * 3 || ((uintptr_t)d | (uintptr_t)s)
& sizeof(size_t) - 1) goto bytewise;
for (; (uintptr_t)s & sizeof(size_t) - 1 && *s != i
; d++, s++, n--) *d = *s;
if ((uintptr_t)s & sizeof(size_t) - 1) return d + 1;
wd = (void *)d;
ws = (const void *)s;
for (; n >= sizeof(size_t) && !word_has_zero(*ws ^ wi)
; *wd++ = *ws++, n -= sizeof(size_t));
d = (void *)wd;
s = (const void *)ws;
bytewise:
for (; n && *d != i; *d++ = *s++, n--);
return n ? d + 1 : 0;
}
|