xref: /aosp_15_r20/external/llvm-libc/src/search/lfind.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Implementation of lfind   -------------------------------*- 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 #include "src/search/lfind.h"
10 #include "src/__support/CPP/cstddef.h" // cpp::byte
11 #include "src/__support/common.h"
12 #include "src/__support/macros/config.h"
13 #include "src/__support/memory_size.h"
14 
15 namespace LIBC_NAMESPACE_DECL {
16 LLVM_LIBC_FUNCTION(void *, lfind,
17                    (const void *key, const void *base, size_t *nmemb,
18                     size_t size, int (*compar)(const void *, const void *))) {
19   if (key == nullptr || base == nullptr || nmemb == nullptr ||
20       compar == nullptr)
21     return nullptr;
22 
23   size_t byte_len = 0;
24   if (internal::mul_overflow(*nmemb, size, &byte_len))
25     return nullptr;
26 
27   const cpp::byte *next = reinterpret_cast<const cpp::byte *>(base);
28   const cpp::byte *end = next + byte_len;
29   for (; next < end; next += size)
30     if (compar(key, next) == 0)
31       return const_cast<cpp::byte *>(next);
32   return nullptr;
33 }
34 
35 } // namespace LIBC_NAMESPACE_DECL
36