memmem.c 752 B

123456789101112131415161718192021222324252627282930313233
  1. #include "../git-compat-util.h"
  2. void *gitmemmem(const void *haystack, size_t haystack_len,
  3. const void *needle, size_t needle_len)
  4. {
  5. const char *begin = haystack;
  6. const char *last_possible = begin + haystack_len - needle_len;
  7. const char *tail = needle;
  8. char point;
  9. /*
  10. * The first occurrence of the empty string is deemed to occur at
  11. * the beginning of the string.
  12. */
  13. if (needle_len == 0)
  14. return (void *)begin;
  15. /*
  16. * Sanity check, otherwise the loop might search through the whole
  17. * memory.
  18. */
  19. if (haystack_len < needle_len)
  20. return NULL;
  21. point = *tail++;
  22. for (; begin <= last_possible; begin++) {
  23. if (*begin == point && !memcmp(begin + 1, tail, needle_len - 1))
  24. return (void *)begin;
  25. }
  26. return NULL;
  27. }