Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libc / src / string / memory_utils / inline_memmem.h
blobeaddee57aef54f64ceb4d895dd7f298cb7960b35
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_INLINE_MEMMEM_H
10 #define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_MEMMEM_H
12 #include "src/__support/macros/attributes.h"
14 #include <stddef.h>
16 namespace LIBC_NAMESPACE {
18 template <typename Comp>
19 LIBC_INLINE constexpr static void *
20 inline_memmem(const void *haystack, size_t haystack_len, const void *needle,
21 size_t needle_len, Comp &&comp) {
22 // TODO: simple brute force implementation. This can be
23 // improved upon using well known string matching algorithms.
24 if (!needle_len)
25 return const_cast<void *>(haystack);
27 if (needle_len > haystack_len)
28 return nullptr;
30 const unsigned char *h = static_cast<const unsigned char *>(haystack);
31 const unsigned char *n = static_cast<const unsigned char *>(needle);
32 for (size_t i = 0; i <= (haystack_len - needle_len); ++i) {
33 size_t j = 0;
34 for (; j < needle_len && !comp(h[i + j], n[j]); ++j)
36 if (j == needle_len)
37 return const_cast<unsigned char *>(h + i);
39 return nullptr;
42 } // namespace LIBC_NAMESPACE
44 #endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_MEMMEM_H