1 /* Scan memory for a character. Generic version
2 Copyright (C) 1991-2024 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
19 #include <libc-pointer-arith.h>
20 #include <string-fzb.h>
21 #include <string-fzc.h>
22 #include <string-fzi.h>
23 #include <string-shift.h>
29 # define __memchr MEMCHR
32 static __always_inline
const char *
33 sadd (uintptr_t x
, uintptr_t y
)
35 return (const char *)(y
> UINTPTR_MAX
- x
? UINTPTR_MAX
: x
+ y
);
38 /* Search no more than N bytes of S for C. */
40 __memchr (void const *s
, int c_in
, size_t n
)
42 if (__glibc_unlikely (n
== 0))
45 /* Read the first word, but munge it so that bytes before the array
46 will not match goal. */
47 const op_t
*word_ptr
= PTR_ALIGN_DOWN (s
, sizeof (op_t
));
48 uintptr_t s_int
= (uintptr_t) s
;
50 op_t word
= *word_ptr
;
51 op_t repeated_c
= repeat_bytes (c_in
);
52 /* Compute the address of the last byte taking in consideration possible
54 const char *lbyte
= sadd (s_int
, n
- 1);
55 /* And also the address of the word containing the last byte. */
56 const op_t
*lword
= (const op_t
*) PTR_ALIGN_DOWN (lbyte
, sizeof (op_t
));
58 find_t mask
= shift_find (find_eq_all (word
, repeated_c
), s_int
);
61 char *ret
= (char *) s
+ index_first (mask
);
62 return (ret
<= lbyte
) ? ret
: NULL
;
64 if (word_ptr
== lword
)
68 while (word_ptr
!= lword
)
70 if (has_eq (word
, repeated_c
))
71 return (char *) word_ptr
+ index_first_eq (word
, repeated_c
);
75 if (has_eq (word
, repeated_c
))
77 /* We found a match, but it might be in a byte past the end of the
79 char *ret
= (char *) word_ptr
+ index_first_eq (word
, repeated_c
);
86 weak_alias (__memchr
, memchr
)
87 libc_hidden_builtin_def (memchr
)