memrchr.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* memrchr -- find the last occurrence of a byte in a memory block
  2. Copyright (C) 1991-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #include <string-fzb.h>
  16. #include <string-fzc.h>
  17. #include <string-fzi.h>
  18. #include <string-shift.h>
  19. #include <string.h>
  20. #include <libc-pointer-arith.h>
  21. #undef __memrchr
  22. #undef memrchr
  23. #ifdef MEMRCHR
  24. # define __memrchr MEMRCHR
  25. #endif
  26. void *
  27. __memrchr (const void *s, int c_in, size_t n)
  28. {
  29. if (__glibc_unlikely (n == 0))
  30. return NULL;
  31. const op_t *word_ptr = (const op_t *) PTR_ALIGN_UP (s + n, sizeof (op_t));
  32. uintptr_t s_int = (uintptr_t) s + n;
  33. op_t word = *--word_ptr;
  34. op_t repeated_c = repeat_bytes (c_in);
  35. /* Compute the address of the word containing the initial byte. */
  36. const op_t *sword = (const op_t *) PTR_ALIGN_DOWN (s, sizeof (op_t));
  37. /* If the end of buffer is not op_t aligned, mask off the undesirable bits
  38. before find the last byte position. */
  39. find_t mask = shift_find_last (find_eq_all (word, repeated_c), s_int);
  40. if (mask != 0)
  41. {
  42. char *ret = (char *) word_ptr + index_last (mask);
  43. return ret >= (char *) s ? ret : NULL;
  44. }
  45. if (word_ptr == sword)
  46. return NULL;
  47. word = *--word_ptr;
  48. while (word_ptr != sword)
  49. {
  50. if (has_eq (word, repeated_c))
  51. return (char *) word_ptr + index_last_eq (word, repeated_c);
  52. word = *--word_ptr;
  53. }
  54. if (has_eq (word, repeated_c))
  55. {
  56. /* We found a match, but it might be in a byte past the end of the
  57. array. */
  58. char *ret = (char *) word_ptr + index_last_eq (word, repeated_c);
  59. if (ret >= (char *) s)
  60. return ret;
  61. }
  62. return NULL;
  63. }
  64. #ifndef MEMRCHR
  65. libc_hidden_def (__memrchr)
  66. weak_alias (__memrchr, memrchr)
  67. #endif