|
| 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 | + cpp::byte *next = reinterpret_cast<cpp::byte *>(const_cast<void *>(base)); |
| 29 | + const cpp::byte *end = next + byte_len; |
| 30 | + |
| 31 | + for (; next < end; next += size) |
| 32 | + if (compar(key, next) == 0) |
| 33 | + break; |
| 34 | + |
| 35 | + if (next == end) { |
| 36 | + LIBC_NAMESPACE::inline_memcpy(next, key, size); |
| 37 | + *nmemb += 1; |
| 38 | + } |
| 39 | + |
| 40 | + return next; |
| 41 | +} |
| 42 | + |
| 43 | +} // namespace LIBC_NAMESPACE_DECL |
0 commit comments