Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
memchr.c File Reference
#include <limits.h>
#include <stdint.h>
#include <string.h>
Include dependency graph for memchr.c:

Go to the source code of this file.

Macros

#define SS   (sizeof(size_t))
 
#define ALIGN   (sizeof(size_t) - 1)
 
#define ONES   ((size_t)-1 / UCHAR_MAX)
 
#define HIGHS   (ONES * (UCHAR_MAX / 2 + 1))
 
#define HASZERO(x)   ((x)-ONES & ~(x)&HIGHS)
 

Functions

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. More...
 

Macro Definition Documentation

◆ ALIGN

#define ALIGN   (sizeof(size_t) - 1)

Definition at line 8 of file memchr.c.

◆ HASZERO

#define HASZERO (   x)    ((x)-ONES & ~(x)&HIGHS)

Definition at line 11 of file memchr.c.

◆ HIGHS

#define HIGHS   (ONES * (UCHAR_MAX / 2 + 1))

Definition at line 10 of file memchr.c.

◆ ONES

#define ONES   ((size_t)-1 / UCHAR_MAX)

Definition at line 9 of file memchr.c.

◆ SS

#define SS   (sizeof(size_t))

Definition at line 7 of file memchr.c.

Function Documentation

◆ memchr()

void* memchr ( const void *  s,
int  c,
size_t  n 
)

Finds the first occurrence of c in the initial n characters of the object pointed to by s.

Finds the first occurrence of c (after conversion to unsigned char as if by (unsigned char)c ) in the initial n characters (each interpreted as unsigned char) of the object pointed to by s.

The behavior is undefined if access occurs beyond the end of the array (s) searched. The behavior is undefined if s is a null pointer.

Parameters
spointer to the object to be examined
ccharacter to search for
nmax number of characters to examine
Returns
a copy of dest

Definition at line 13 of file memchr.c.

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
#define ALIGN
Definition: memchr.c:8
#define ONES
Definition: memchr.c:9
int word
Definition: memcpy.c:39

References __attribute__(), ALIGN, HASZERO, ONES, and SS.

Referenced by memmem().

Here is the caller graph for this function: