[NFC][Py Reformat] Added more commits to .git-blame-ignore-revs
[llvm-project.git] / libc / src / string / memory_utils / memmem_implementations.h
blobda0be0f16c104489db8d3c0ec6741e34f4eca657
1 //===-- memmem implementation -----------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_MEMMEM_IMPLEMENTATIONS_H
10 #define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_MEMMEM_IMPLEMENTATIONS_H
12 #include <stddef.h>
14 namespace __llvm_libc {
16 template <typename Comp>
17 constexpr static void *
18 memmem_implementation(const void *haystack, size_t haystack_len,
19 const void *needle, size_t needle_len, Comp &&comp) {
20 // TODO: simple brute force implementation. This can be
21 // improved upon using well known string matching algorithms.
22 if (!needle_len)
23 return const_cast<void *>(haystack);
25 if (needle_len > haystack_len)
26 return nullptr;
28 const unsigned char *h = static_cast<const unsigned char *>(haystack);
29 const unsigned char *n = static_cast<const unsigned char *>(needle);
30 for (size_t i = 0; i <= (haystack_len - needle_len); ++i) {
31 size_t j = 0;
32 for (; j < needle_len && !comp(h[i + j], n[j]); ++j)
34 if (j == needle_len)
35 return const_cast<unsigned char *>(h + i);
37 return nullptr;
40 } // namespace __llvm_libc
42 #endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_MEMMEM_IMPLEMENTATIONS_H