[libc-commits] [libc] [libc][search] implement posix `lfind` function (PR #114692)
via libc-commits
libc-commits at lists.llvm.org
Tue Nov 5 10:49:44 PST 2024
================
@@ -0,0 +1,41 @@
+//===-- Implementation of lfind -------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/search/lfind.h"
+#include "src/__support/CPP/cstddef.h" // cpp::byte
+#include "src/__support/common.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/memory_size.h"
+
+namespace LIBC_NAMESPACE_DECL {
+LLVM_LIBC_FUNCTION(void *, lfind,
+ (const void *key, const void *base, size_t *nmemb,
+ size_t size, int (*compar)(const void *, const void *))) {
+ if (key == nullptr || base == nullptr || nmemb == nullptr ||
+ compar == nullptr)
+ return nullptr;
+
+ size_t byte_len = 0;
+ if (internal::mul_overflow(*nmemb, size, &byte_len))
+ return nullptr;
+
+ const cpp::byte *next = reinterpret_cast<const cpp::byte *>(base);
+ const cpp::byte *end = next + byte_len;
+ while (next < end) {
+ if (compar(key, next) == 0) {
+ // According to IEEE Std 1003.1-2024 we are expected to accept a const
+ // reference to base, but return a non-const reference to the element it
+ // contains.
----------------
duncpro wrote:
Just to be clear, the suggested change here is…
1. Use char instead of cpp::byte
2. Discard the const-ness at the beginning of the function instead of waiting until we return the pointer.
3. Use for loop instead of while loop.
I agree that (3) is an improvement. However it’s not clear the benefit of (1) and (2).
https://github.com/llvm/llvm-project/pull/114692
More information about the libc-commits
mailing list