Remove set-hooks.h from generic includes
[glibc.git] / string / memrchr.c
blob3de5ec691c89880ec6eeb8ad2517f04532534408
1 /* memrchr -- find the last occurrence of a byte in a memory block
2 Copyright (C) 1991-2023 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 <string-fzb.h>
20 #include <string-fzc.h>
21 #include <string-fzi.h>
22 #include <string-shift.h>
23 #include <string.h>
24 #include <libc-pointer-arith.h>
26 #undef __memrchr
27 #undef memrchr
29 #ifdef MEMRCHR
30 # define __memrchr MEMRCHR
31 #endif
33 void *
34 __memrchr (const void *s, int c_in, size_t n)
36 if (__glibc_unlikely (n == 0))
37 return NULL;
39 const op_t *word_ptr = (const op_t *) PTR_ALIGN_UP (s + n, sizeof (op_t));
40 uintptr_t s_int = (uintptr_t) s + n;
42 op_t word = *--word_ptr;
43 op_t repeated_c = repeat_bytes (c_in);
45 /* Compute the address of the word containing the initial byte. */
46 const op_t *sword = (const op_t *) PTR_ALIGN_DOWN (s, sizeof (op_t));
48 /* If the end of buffer is not op_t aligned, mask off the undesirable bits
49 before find the last byte position. */
50 find_t mask = shift_find_last (find_eq_all (word, repeated_c), s_int);
51 if (mask != 0)
53 char *ret = (char *) word_ptr + index_last (mask);
54 return ret >= (char *) s ? ret : NULL;
56 if (word_ptr == sword)
57 return NULL;
58 word = *--word_ptr;
60 while (word_ptr != sword)
62 if (has_eq (word, repeated_c))
63 return (char *) word_ptr + index_last_eq (word, repeated_c);
64 word = *--word_ptr;
67 if (has_eq (word, repeated_c))
69 /* We found a match, but it might be in a byte past the end of the
70 array. */
71 char *ret = (char *) word_ptr + index_last_eq (word, repeated_c);
72 if (ret >= (char *) s)
73 return ret;
75 return NULL;
77 #ifndef MEMRCHR
78 libc_hidden_def (__memrchr)
79 weak_alias (__memrchr, memrchr)
80 #endif