PS2SDK
PS2 Homebrew Libraries
Loading...
Searching...
No Matches
memchr.c
1#define SYSCLIB_DISABLE_BUILTINS
2#include <sysclib.h>
3#include <stdint.h>
4#include <limits.h>
5
6#define SS (sizeof(size_t))
7#define ALIGN (sizeof(size_t)-1)
8#define ONES ((size_t)-1/UCHAR_MAX)
9#define HIGHS (ONES * (UCHAR_MAX/2+1))
10#define HASZERO(x) (((x)-ONES) & ~(x) & HIGHS)
11
12void *memchr(const void *src, int c, size_t n)
13{
14 const unsigned char *s = src;
15 c = (unsigned char)c;
16#ifdef __GNUC__
17 for (; ((uintptr_t)s & ALIGN) && n && *s != c; s++, n--);
18 if (n && *s != c) {
19 typedef size_t __attribute__((__may_alias__)) word;
20 const word *w;
21 size_t k = ONES * c;
22 for (w = (const void *)s; n>=SS && !HASZERO(*w^k); w++, n-=SS);
23 s = (const void *)w;
24 }
25#endif
26 for (; n && *s != c; s++, n--);
27 return n ? (void *)s : 0;
28}