memmem.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Copyright (C) 1991-2022 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License along
  12. with this program; if not, write to the Free Software Foundation,
  13. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  14. /*
  15. @deftypefn Supplemental void* memmem (const void *@var{haystack}, @
  16. size_t @var{haystack_len} const void *@var{needle}, size_t @var{needle_len})
  17. Returns a pointer to the first occurrence of @var{needle} (length
  18. @var{needle_len}) in @var{haystack} (length @var{haystack_len}).
  19. Returns @code{NULL} if not found.
  20. @end deftypefn
  21. */
  22. #ifndef _LIBC
  23. # include <config.h>
  24. #endif
  25. #include <stddef.h>
  26. #include <string.h>
  27. #ifndef _LIBC
  28. # define __builtin_expect(expr, val) (expr)
  29. #endif
  30. #undef memmem
  31. /* Return the first occurrence of NEEDLE in HAYSTACK. */
  32. void *
  33. memmem (const void *haystack, size_t haystack_len, const void *needle,
  34. size_t needle_len)
  35. {
  36. const char *begin;
  37. const char *const last_possible
  38. = (const char *) haystack + haystack_len - needle_len;
  39. if (needle_len == 0)
  40. /* The first occurrence of the empty string is deemed to occur at
  41. the beginning of the string. */
  42. return (void *) haystack;
  43. /* Sanity check, otherwise the loop might search through the whole
  44. memory. */
  45. if (__builtin_expect (haystack_len < needle_len, 0))
  46. return NULL;
  47. for (begin = (const char *) haystack; begin <= last_possible; ++begin)
  48. if (begin[0] == ((const char *) needle)[0] &&
  49. !memcmp ((const void *) &begin[1],
  50. (const void *) ((const char *) needle + 1),
  51. needle_len - 1))
  52. return (void *) begin;
  53. return NULL;
  54. }