1 //===-- memmem implementation -----------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_MEMMEM_IMPLEMENTATIONS_H
10 #define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_MEMMEM_IMPLEMENTATIONS_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.
23 return const_cast<void *>(haystack
);
25 if (needle_len
> haystack_len
)
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
) {
32 for (; j
< needle_len
&& !comp(h
[i
+ j
], n
[j
]); ++j
)
35 return const_cast<unsigned char *>(h
+ i
);
40 } // namespace __llvm_libc
42 #endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_MEMMEM_IMPLEMENTATIONS_H