memmem.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Copyright (C) 1991,92,93,94,96,97,98,2000,2004,2007,2011 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. }