1 //===-- Implementation of lsearch -------------------------------*- 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/lsearch.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 #include "src/string/memory_utils/inline_memcpy.h" 15 16 namespace LIBC_NAMESPACE_DECL { 17 LLVM_LIBC_FUNCTION(void *, lsearch, 18 (const void *key, void *base, size_t *nmemb, size_t size, 19 int (*compar)(const void *, const void *))) { 20 if (key == nullptr || base == nullptr || nmemb == nullptr || 21 compar == nullptr) 22 return nullptr; 23 24 size_t byte_len = 0; 25 if (internal::mul_overflow(*nmemb, size, &byte_len)) 26 return nullptr; 27 28 const cpp::byte *next = reinterpret_cast<const cpp::byte *>(base); 29 const cpp::byte *end = next + byte_len; 30 for (; next < end; next += size) 31 if (compar(key, next) == 0) 32 return const_cast<cpp::byte *>(next); 33 34 *nmemb += 1; 35 inline_memcpy(const_cast<cpp::byte *>(end), key, size); 36 return const_cast<cpp::byte *>(end); 37 } 38 39 } // namespace LIBC_NAMESPACE_DECL 40