Cygwin: mmap: allow remapping part of an existing anonymous mapping
[newlib-cygwin.git] / newlib / libc / string / strchr.c
blob96f30be044beda6db51782932edb4da98c889d96
1 /*
2 FUNCTION
3 <<strchr>>---search for character in string
5 INDEX
6 strchr
8 SYNOPSIS
9 #include <string.h>
10 char * strchr(const char *<[string]>, int <[c]>);
12 DESCRIPTION
13 This function finds the first occurence of <[c]> (converted to
14 a char) in the string pointed to by <[string]> (including the
15 terminating null character).
17 RETURNS
18 Returns a pointer to the located character, or a null pointer
19 if <[c]> does not occur in <[string]>.
21 PORTABILITY
22 <<strchr>> is ANSI C.
24 <<strchr>> requires no supporting OS subroutines.
26 QUICKREF
27 strchr ansi pure
30 #include <string.h>
31 #include <limits.h>
33 /* Nonzero if X is not aligned on a "long" boundary. */
34 #define UNALIGNED(X) ((long)X & (sizeof (long) - 1))
36 /* How many bytes are loaded each iteration of the word copy loop. */
37 #define LBLOCKSIZE (sizeof (long))
39 #if LONG_MAX == 2147483647L
40 #define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
41 #else
42 #if LONG_MAX == 9223372036854775807L
43 /* Nonzero if X (a long int) contains a NULL byte. */
44 #define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
45 #else
46 #error long int is not a 32bit or 64bit type.
47 #endif
48 #endif
50 /* DETECTCHAR returns nonzero if (long)X contains the byte used
51 to fill (long)MASK. */
52 #define DETECTCHAR(X,MASK) (DETECTNULL(X ^ MASK))
54 char *
55 strchr (const char *s1,
56 int i)
58 const unsigned char *s = (const unsigned char *)s1;
59 unsigned char c = i;
61 #if !defined(PREFER_SIZE_OVER_SPEED) && !defined(__OPTIMIZE_SIZE__)
62 unsigned long mask,j;
63 unsigned long *aligned_addr;
65 /* Special case for finding 0. */
66 if (!c)
68 while (UNALIGNED (s))
70 if (!*s)
71 return (char *) s;
72 s++;
74 /* Operate a word at a time. */
75 aligned_addr = (unsigned long *) s;
76 while (!DETECTNULL (*aligned_addr))
77 aligned_addr++;
78 /* Found the end of string. */
79 s = (const unsigned char *) aligned_addr;
80 while (*s)
81 s++;
82 return (char *) s;
85 /* All other bytes. Align the pointer, then search a long at a time. */
86 while (UNALIGNED (s))
88 if (!*s)
89 return NULL;
90 if (*s == c)
91 return (char *) s;
92 s++;
95 mask = c;
96 for (j = 8; j < LBLOCKSIZE * 8; j <<= 1)
97 mask = (mask << j) | mask;
99 aligned_addr = (unsigned long *) s;
100 while (!DETECTNULL (*aligned_addr) && !DETECTCHAR (*aligned_addr, mask))
101 aligned_addr++;
103 /* The block of bytes currently pointed to by aligned_addr
104 contains either a null or the target char, or both. We
105 catch it using the bytewise search. */
107 s = (unsigned char *) aligned_addr;
109 #endif /* not PREFER_SIZE_OVER_SPEED */
111 while (*s && *s != c)
112 s++;
113 if (*s == c)
114 return (char *)s;
115 return NULL;