Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
memchr.c
Go to the documentation of this file.
1 // Imported from musl Libc
2 
3 #include <limits.h>
4 #include <stdint.h>
5 #include <string.h>
6 
7 #define SS (sizeof(size_t))
8 #define ALIGN (sizeof(size_t) - 1)
9 #define ONES ((size_t)-1 / UCHAR_MAX)
10 #define HIGHS (ONES * (UCHAR_MAX / 2 + 1))
11 #define HASZERO(x) ((x)-ONES & ~(x)&HIGHS)
12 
13 void* memchr(const void* src, int c, size_t n)
14 {
15  const unsigned char* s = src;
16  c = (unsigned char)c;
17 
18 #ifdef __GNUC__
19  for(; ((uintptr_t)s & ALIGN) && n && *s != c; s++, n--)
20  {
21  }
22 
23  if(n && *s != c)
24  {
25  typedef size_t __attribute__((__may_alias__)) word;
26  const word* w;
27  size_t k = ONES * (size_t)c;
28 
29  for(w = (const void*)s; n >= SS && !HASZERO(*w ^ k); w++, n -= SS)
30  {
31  }
32 
33  s = (const void*)w;
34  }
35 #endif
36 
37  for(; n && *s != c; s++, n--)
38  {
39  }
40 
41  return n ? (void*)(uintptr_t)s : 0;
42 }
#define HASZERO(x)
Definition: memchr.c:11
#define SS
Definition: memchr.c:7
__attribute__((noreturn, weak)) void __assert_fail(const char *expr
void * memchr(const void *src, int c, size_t n)
Finds the first occurrence of c in the initial n characters of the object pointed to by s.
Definition: memchr.c:13
#define ALIGN
Definition: memchr.c:8
#define ONES
Definition: memchr.c:9
int word
Definition: memcpy.c:39