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//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_MEMMEM_H
10#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_MEMMEM_H
11
12#include "src/__support/macros/attributes.h"
13
14#include <stddef.h>
15
16namespace LIBC_NAMESPACE {
17
18template <typename Comp>
19LIBC_INLINE constexpr static void *
20inline_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);
26
27 if (needle_len > haystack_len)
28 return nullptr;
29
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)
35 ;
36 if (j == needle_len)
37 return const_cast<unsigned char *>(h + i);
38 }
39 return nullptr;
40}
41
42} // namespace LIBC_NAMESPACE
43
44#endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_MEMMEM_H
45

source code of libc/src/string/memory_utils/inline_memmem.h