memmem.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* Copyright (C) 1991-2025 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. #include <stddef.h>
  23. #include <string.h>
  24. #ifndef _LIBC
  25. #define __builtin_expect(expr, val) (expr)
  26. #endif
  27. #undef memmem
  28. /* Return the first occurrence of NEEDLE in HAYSTACK. */
  29. void* memmem(const void* haystack, size_t haystack_len, const void* needle, size_t needle_len) {
  30. const char* begin;
  31. const char* const last_possible = (const char*)haystack + haystack_len - needle_len;
  32. if(needle_len == 0)
  33. /* The first occurrence of the empty string is deemed to occur at
  34. the beginning of the string. */
  35. return (void*)haystack;
  36. /* Sanity check, otherwise the loop might search through the whole
  37. memory. */
  38. if(__builtin_expect(haystack_len < needle_len, 0)) return NULL;
  39. for(begin = (const char*)haystack; begin <= last_possible; ++begin)
  40. if(begin[0] == ((const char*)needle)[0] &&
  41. !memcmp((const void*)&begin[1], (const void*)((const char*)needle + 1), needle_len - 1))
  42. return (void*)begin;
  43. return NULL;
  44. }