[libc-commits] [libc] [llvm] [libc] Implement a Vector container (PR #243109)
Pavel Labath via libc-commits
libc-commits at lists.llvm.org
Mon Nov 16 07:58:49 PST 2026
https://github.com/labath created https://github.com/llvm/llvm-project/pull/243109
This adds Vector, a heap-allocated std::vector-like container, whose allocating operations (reserve, resize, push_back, append, assign) return a Checked object. Checked is a new [[nodiscard]] bool wrapper, which (like CheckedPtr) asserts in !NDEBUG builds that the result was checked before it is destroyed. To share the tracking logic, I've moved CheckedState out of checked_ptr.h and into the new checked.h header. Checked is implicitly constructible from bool (so functions can just `return true`), but not from other types, as I don't want `return 0` (i.e., the errno-style success) to silently turn into a failure.
For background, see <https://discourse.llvm.org/t/rfc-error-checking-apis-for-memory-allocation-and-management/92511>.
To keep the patch small, this implements only a subset of the std::vector interface. Things like emplace_back, shrink_to_fit and the remaining append/assign overloads will come in a separate patch. The other differences from std::vector are:
- the copy constructor and assignment are deleted, as copying needs to allocate. assign(const Vector &) does the same thing in a way that lets the caller check the result.
- however, operations which do not allocate (operator[], front, back, pop_back) do *NOT* report errors. It's up to the caller to make sure the index is valid, the vector is not empty, etc. (LIBC_ASSERT checks these in debug builds), just like with a regular std::vector.
- it has `append`, as an alternative to insert(end()). It takes an iterator range, which must not point into the vector (just like `vector::insert`).
A failed operation leaves the vector unchanged.
The implementation uses with realloc for trivially copyable types, as that sometimes avoids the copy. Other types get moved one by one. Over-aligned types are not supported (yet).
To make `v.push_back(v[0])` work when the storage needs to grow, I'm using the same pattern as `llvm::SmallVector`: if the argument points into the vector, push_back remembers its index and finds the element again after growing the storage.
The constructors of the element type that Vector uses (default, copy, move, and the converting one in append) must not fail, which in practice means they must not allocate memory.
The plan is to use this to replace various hand-rolled growable arrays (e.g. ScannedEntries in dir_scan_impl.h), which I'll do in separate patches.
Assisted-by: Gemini
>From 8d3f6e9511ce6cbb34850c9cfd3e1841f4c28df4 Mon Sep 17 00:00:00 2001
From: Pavel Labath <pavel at labath.sk>
Date: Mon, 16 Nov 2026 14:01:50 +0000
Subject: [PATCH] [libc] Implement a Vector container
This adds Vector, a heap-allocated std::vector-like container, whose
allocating operations (reserve, resize, push_back, append, assign)
return a Checked object. Checked is a new [[nodiscard]] bool wrapper,
which (like CheckedPtr) asserts in !NDEBUG builds that the result was
checked before it is destroyed. To share the tracking logic, I've moved
CheckedState out of checked_ptr.h and into the new checked.h header.
Checked is implicitly constructible from bool (so functions can just
`return true`), but not from other types, as I don't want `return 0`
(i.e., the errno-style success) to silently turn into a failure.
To keep the patch small, this implements only a subset of the
std::vector interface. Things like emplace_back, shrink_to_fit and
the remaining append/assign overloads will come in a separate patch. The
other differences from std::vector are:
- the copy constructor and assignment are deleted, as copying needs to
allocate. assign(const Vector &) does the same thing in a way that
lets the caller check the result.
- operations which do not allocate (operator[], front, back, pop_back)
do not report errors. It's up to the caller to make sure the index is
valid, the vector is not empty, etc. (LIBC_ASSERT checks these in
debug builds).
- append, as an alternative to insert(end()). It takes an iterator
range, which must not point into the vector.
A failed operation leaves the vector (and the argument of push_back)
unchanged.
The storage comes from malloc rather than make_unique_for_overwrite, so
that trivially copyable types can be moved around with realloc (which
can sometimes avoid the copy). Other types get moved one by one.
Over-aligned types are not supported (yet).
To make `v.push_back(v[0])` work when the storage needs to grow,
libc++ constructs the new element before moving the old ones. That
doesn't work with realloc, so I'm doing what llvm::SmallVector does
instead: if the argument points into the vector, push_back remembers
its index and finds the element again after growing the storage.
The constructors of the element type that Vector uses (default, copy,
move, and the converting one in append) must not fail, which in
practice means they must not allocate memory.
The plan is to use this to replace various hand-rolled growable arrays
(e.g. ScannedEntries in dir_scan_impl.h), which I'll do in separate
patches.
Assisted-by: Gemini
---
libc/src/__support/CMakeLists.txt | 33 +-
libc/src/__support/checked.h | 106 +++++
libc/src/__support/checked_ptr.h | 46 +--
libc/src/__support/vector.h | 284 +++++++++++++
libc/test/src/__support/CMakeLists.txt | 27 ++
libc/test/src/__support/checked_test.cpp | 92 +++++
libc/test/src/__support/vector_test.cpp | 389 ++++++++++++++++++
.../libc/src/__support/BUILD.bazel | 12 +-
8 files changed, 942 insertions(+), 47 deletions(-)
create mode 100644 libc/src/__support/checked.h
create mode 100644 libc/src/__support/vector.h
create mode 100644 libc/test/src/__support/checked_test.cpp
create mode 100644 libc/test/src/__support/vector_test.cpp
diff --git a/libc/src/__support/CMakeLists.txt b/libc/src/__support/CMakeLists.txt
index 9b1089fa48c8c3..427939c131ec1e 100644
--- a/libc/src/__support/CMakeLists.txt
+++ b/libc/src/__support/CMakeLists.txt
@@ -178,13 +178,23 @@ add_header_library(
libc.src.__support.macros.properties.os
)
+add_header_library(
+ checked
+ HDRS
+ checked.h
+ DEPENDS
+ .libc_assert
+ libc.src.__support.macros.attributes
+ libc.src.__support.macros.config
+)
+
add_header_library(
checked_ptr
HDRS
checked_ptr.h
DEPENDS
.alloc_checker
- .libc_assert
+ .checked
libc.hdr.types.size_t
libc.src.__support.CPP.nullptr_t
libc.src.__support.CPP.type_traits
@@ -390,6 +400,27 @@ add_header_library(
libc.src.__support.common
)
+add_header_library(
+ vector
+ HDRS
+ vector.h
+ DEPENDS
+ .checked
+ .libc_assert
+ libc.hdr.func.free
+ libc.hdr.func.malloc
+ libc.hdr.func.realloc
+ libc.hdr.stdint_proxy
+ libc.hdr.types.size_t
+ libc.src.__support.CPP.algorithm
+ libc.src.__support.CPP.limits
+ libc.src.__support.CPP.new
+ libc.src.__support.CPP.type_traits
+ libc.src.__support.CPP.utility
+ libc.src.__support.macros.attributes
+ libc.src.__support.macros.config
+)
+
add_header_library(
number_pair
HDRS
diff --git a/libc/src/__support/checked.h b/libc/src/__support/checked.h
new file mode 100644
index 00000000000000..a026b86c53e8da
--- /dev/null
+++ b/libc/src/__support/checked.h
@@ -0,0 +1,106 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Utilities for enforcing that results of fallible operations get checked.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_CHECKED_H
+#define LLVM_LIBC_SRC___SUPPORT_CHECKED_H
+
+#include "src/__support/libc_assert.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+namespace detail {
+
+class LIBC_TRIVIAL_ABI CheckedState {
+#ifndef NDEBUG
+ bool checked = false;
+
+public:
+ LIBC_INLINE constexpr CheckedState() = default;
+
+ // Moving disarms `other` and starts `this` unchecked so the new owner must
+ // explicitly check its value.
+ LIBC_INLINE constexpr CheckedState(CheckedState &&other) {
+ other.checked = true;
+ }
+
+ // Overwriting an existing CheckedState requires it to have been checked,
+ // disarms `other`, and resets `this` to unchecked.
+ LIBC_INLINE constexpr CheckedState &operator=(CheckedState &&other) {
+ assert_checked();
+ // Self-move-assignment leaves the (checked) state unchanged.
+ if (this == &other)
+ return *this;
+ other.checked = true;
+ checked = false;
+ return *this;
+ }
+
+ LIBC_INLINE ~CheckedState() { assert_checked(); }
+
+ LIBC_INLINE constexpr void mark_checked() { checked = true; }
+ LIBC_INLINE constexpr void assert_checked() const { LIBC_ASSERT(checked); }
+#else
+public:
+ LIBC_INLINE constexpr CheckedState() = default;
+ LIBC_INLINE constexpr CheckedState(CheckedState &&) = default;
+ LIBC_INLINE constexpr CheckedState &operator=(CheckedState &&) = default;
+
+ LIBC_INLINE constexpr void mark_checked() {}
+ LIBC_INLINE constexpr void assert_checked() const {}
+#endif
+};
+
+} // namespace detail
+
+/// The result of an operation that can fail (typically, because it needs to
+/// allocate memory). In !NDEBUG builds, it asserts that the result has been
+/// checked (by converting it to bool) before it is destroyed or overwritten by
+/// a move assignment.
+///
+/// Moving from a Checked object disarms the source and leaves the destination
+/// unchecked, forcing the new owner to check it.
+///
+/// In NDEBUG builds, nothing is tracked and Checked is just a wrapper for bool.
+class [[nodiscard]] LIBC_TRIVIAL_ABI Checked {
+ LIBC_NO_UNIQUE_ADDRESS detail::CheckedState state;
+ bool success;
+
+public:
+ LIBC_INLINE constexpr Checked(bool success) : success(success) {}
+
+ // Disallow (implicit) conversions from other types, such as integers or
+ // pointers, as their truthiness need not correspond to success.
+ template <typename U> Checked(U) = delete;
+
+ LIBC_INLINE Checked(Checked &&other) = default;
+ LIBC_INLINE Checked &operator=(Checked &&other) = default;
+
+ Checked(const Checked &) = delete;
+ Checked &operator=(const Checked &) = delete;
+
+ /// Returns true if the operation succeeded, and marks the result as checked.
+ ///
+ /// This is intentionally non-const: recording the check in a const member
+ /// function would require a mutable flag, and concurrent checks through const
+ /// references would then race on it.
+ LIBC_INLINE constexpr explicit operator bool() {
+ state.mark_checked();
+ return success;
+ }
+};
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC___SUPPORT_CHECKED_H
diff --git a/libc/src/__support/checked_ptr.h b/libc/src/__support/checked_ptr.h
index ea06669cc259e0..cdea243067168f 100644
--- a/libc/src/__support/checked_ptr.h
+++ b/libc/src/__support/checked_ptr.h
@@ -20,56 +20,12 @@
#include "src/__support/CPP/unique_ptr.h"
#include "src/__support/CPP/utility.h"
#include "src/__support/alloc-checker.h"
-#include "src/__support/libc_assert.h"
+#include "src/__support/checked.h"
#include "src/__support/macros/attributes.h"
#include "src/__support/macros/config.h"
namespace LIBC_NAMESPACE_DECL {
-namespace detail {
-
-class LIBC_TRIVIAL_ABI CheckedState {
-#ifndef NDEBUG
- bool checked = false;
-
-public:
- LIBC_INLINE constexpr CheckedState() = default;
-
- // Moving disarms `other` and starts `this` unchecked so the new owner must
- // explicitly check its value.
- LIBC_INLINE constexpr CheckedState(CheckedState &&other) {
- other.checked = true;
- }
-
- // Overwriting an existing CheckedState requires it to have been checked,
- // disarms `other`, and resets `this` to unchecked.
- LIBC_INLINE constexpr CheckedState &operator=(CheckedState &&other) {
- assert_checked();
- // Self-move-assignment leaves the (checked) state unchanged.
- if (this == &other)
- return *this;
- other.checked = true;
- checked = false;
- return *this;
- }
-
- LIBC_INLINE ~CheckedState() { assert_checked(); }
-
- LIBC_INLINE constexpr void mark_checked() { checked = true; }
- LIBC_INLINE constexpr void assert_checked() const { LIBC_ASSERT(checked); }
-#else
-public:
- LIBC_INLINE constexpr CheckedState() = default;
- LIBC_INLINE constexpr CheckedState(CheckedState &&) = default;
- LIBC_INLINE constexpr CheckedState &operator=(CheckedState &&) = default;
-
- LIBC_INLINE constexpr void mark_checked() {}
- LIBC_INLINE constexpr void assert_checked() const {}
-#endif
-};
-
-} // namespace detail
-
/// A smart pointer wrapper around cpp::unique_ptr that enforces (in !NDEBUG
/// builds) that callers check pointer nullness before accessing or destroying
/// the pointer.
diff --git a/libc/src/__support/vector.h b/libc/src/__support/vector.h
new file mode 100644
index 00000000000000..7ae89787f47a39
--- /dev/null
+++ b/libc/src/__support/vector.h
@@ -0,0 +1,284 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// A growable array, which reports allocation failures to the caller.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_VECTOR_H
+#define LLVM_LIBC_SRC___SUPPORT_VECTOR_H
+
+#include "hdr/func/free.h"
+#include "hdr/func/malloc.h"
+#include "hdr/func/realloc.h"
+#include "hdr/stdint_proxy.h"
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/algorithm.h"
+#include "src/__support/CPP/iterator.h"
+#include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/type_traits.h"
+#include "src/__support/CPP/utility.h"
+#include "src/__support/checked.h"
+#include "src/__support/libc_assert.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+
+#include <stddef.h> // max_align_t, ptrdiff_t
+
+namespace LIBC_NAMESPACE_DECL {
+
+/// A heap-allocated array which grows as needed, similar to std::vector.
+///
+/// Operations which may need to allocate memory return a Checked object, which
+/// the caller must check. If such an operation fails, the vector is left
+/// unchanged. The other operations cannot fail, but they have the same
+/// preconditions as in std::vector (e.g., pop_back() requires a non-empty
+/// vector). Where practical, these are checked with LIBC_ASSERT.
+///
+/// Copying a vector requires an allocation, so Vector is not copy-constructible
+/// or copy-assignable. Use assign() instead.
+///
+/// The constructors of T that Vector uses (the default constructor in resize(),
+/// the copy and move constructors, and the converting constructor in append())
+/// must not fail (e.g., by allocating memory). Over-aligned types (whose
+/// alignment exceeds alignof(max_align_t)) are not supported. Like with
+/// std::vector, T may be incomplete at the point where Vector<T> is
+/// instantiated, as long as it is completed before the vector is used.
+template <typename T> class Vector {
+ T *items = nullptr;
+ size_t count = 0;
+ size_t cap = 0;
+
+ // Limiting the storage size to PTRDIFF_MAX bytes guarantees that differences
+ // between pointers into it are representable. It also means that doubling
+ // the capacity cannot overflow.
+ LIBC_INLINE static constexpr size_t max_size() {
+ return static_cast<size_t>(cpp::numeric_limits<ptrdiff_t>::max()) /
+ sizeof(T);
+ }
+
+ LIBC_INLINE static void destroy(T *first, T *last) {
+ for (; first != last; ++first)
+ first->~T();
+ }
+
+ LIBC_INLINE static void value_initialize(T *first, T *last) {
+ for (; first != last; ++first)
+ new (first) T();
+ }
+
+ // Moves the elements in [first, last) to the uninitialized storage starting
+ // at `dest`, and destroys the originals.
+ LIBC_INLINE static void relocate(T *first, T *last, T *dest) {
+ for (; first != last; ++first, ++dest) {
+ new (dest) T(cpp::move(*first));
+ first->~T();
+ }
+ }
+
+ LIBC_INLINE void truncate(size_t n) {
+ LIBC_ASSERT(n <= count);
+ destroy(items + n, items + count);
+ count = n;
+ }
+
+ // Moves the elements to new storage with room for `new_cap` elements.
+ LIBC_INLINE bool reallocate(size_t new_cap) {
+ static_assert(alignof(T) <= alignof(max_align_t),
+ "over-aligned types are not supported");
+ // Besides being needed for moving the elements, this guarantees that
+ // trivially copyable types are implicit-lifetime types, whose objects
+ // realloc implicitly creates in the new block.
+ static_assert(cpp::is_move_constructible_v<T>,
+ "T must be move-constructible");
+ LIBC_ASSERT(count <= new_cap && new_cap <= max_size());
+ // realloc(p, 0) may free p and return nullptr.
+ LIBC_ASSERT(new_cap > 0);
+ T *new_items;
+ if constexpr (cpp::is_trivially_copyable_v<T>) {
+ // realloc can avoid the copy if it manages to resize the block in place.
+ new_items = static_cast<T *>(::realloc(items, new_cap * sizeof(T)));
+ if (new_items == nullptr)
+ return false;
+ } else {
+ new_items = static_cast<T *>(::malloc(new_cap * sizeof(T)));
+ if (new_items == nullptr)
+ return false;
+ relocate(items, items + count, new_items);
+ ::free(items);
+ }
+ items = new_items;
+ cap = new_cap;
+ return true;
+ }
+
+ // Makes room for `n` more elements.
+ LIBC_INLINE bool grow_by(size_t n) {
+ if (n <= cap - count)
+ return true;
+ if (n > max_size() - count)
+ return false;
+ // Grow geometrically, so that appends take amortized constant time.
+ return reallocate(cpp::max(count + n, cpp::min(2 * cap, max_size())));
+ }
+
+ // Returns the index of the element `ptr` points to, or `count` if it does not
+ // point to an element of this vector.
+ LIBC_INLINE size_t index_of(const T *ptr) const {
+ // Compare the addresses as integers, as comparing pointers to unrelated
+ // objects gives unspecified results.
+ uintptr_t offset =
+ reinterpret_cast<uintptr_t>(ptr) - reinterpret_cast<uintptr_t>(items);
+ return offset < count * sizeof(T) ? offset / sizeof(T) : count;
+ }
+
+ // Appends an element constructed from `value`, which may be an element of
+ // this vector. Growing the storage moves it, so in that case we find it again
+ // by its index. Nothing happens to `value` if growing fails.
+ template <typename U> LIBC_INLINE bool push_back_impl(U &&value) {
+ auto *ptr = &value;
+ if (count == cap) {
+ size_t index = index_of(ptr);
+ if (!grow_by(1))
+ return false;
+ if (index < count)
+ ptr = items + index;
+ }
+ new (items + count) T(cpp::forward<U>(*ptr));
+ ++count;
+ return true;
+ }
+
+public:
+ using iterator = T *;
+ using const_iterator = const T *;
+
+ LIBC_INLINE constexpr Vector() = default;
+ LIBC_INLINE Vector(Vector &&other) { swap(other); }
+ Vector(const Vector &) = delete;
+
+ LIBC_INLINE Vector &operator=(Vector &&other) {
+ Vector tmp(cpp::move(other));
+ swap(tmp);
+ return *this;
+ }
+ Vector &operator=(const Vector &) = delete;
+
+ LIBC_INLINE ~Vector() {
+ destroy(items, items + count);
+ ::free(items);
+ }
+
+ LIBC_INLINE void swap(Vector &other) {
+ cpp::swap(items, other.items);
+ cpp::swap(count, other.count);
+ cpp::swap(cap, other.cap);
+ }
+
+ LIBC_INLINE bool empty() const { return count == 0; }
+ LIBC_INLINE size_t size() const { return count; }
+ LIBC_INLINE size_t capacity() const { return cap; }
+
+ LIBC_INLINE T *data() { return items; }
+ LIBC_INLINE const T *data() const { return items; }
+
+ LIBC_INLINE T &operator[](size_t i) {
+ LIBC_ASSERT(i < count);
+ return items[i];
+ }
+ LIBC_INLINE const T &operator[](size_t i) const {
+ LIBC_ASSERT(i < count);
+ return items[i];
+ }
+
+ LIBC_INLINE T &front() { return (*this)[0]; }
+ LIBC_INLINE const T &front() const { return (*this)[0]; }
+ LIBC_INLINE T &back() { return (*this)[count - 1]; }
+ LIBC_INLINE const T &back() const { return (*this)[count - 1]; }
+
+ LIBC_INLINE iterator begin() { return items; }
+ LIBC_INLINE const_iterator begin() const { return items; }
+ LIBC_INLINE iterator end() { return items + count; }
+ LIBC_INLINE const_iterator end() const { return items + count; }
+
+ LIBC_INLINE Checked reserve(size_t n) {
+ if (n <= cap)
+ return true;
+ if (n > max_size())
+ return false;
+ return reallocate(n);
+ }
+
+ /// New elements are value-initialized.
+ LIBC_INLINE Checked resize(size_t n) {
+ if (n <= count) {
+ truncate(n);
+ return true;
+ }
+ if (!grow_by(n - count))
+ return false;
+ value_initialize(items + count, items + n);
+ count = n;
+ return true;
+ }
+
+ LIBC_INLINE void clear() { truncate(0); }
+
+ /// Appends a copy of `value`, which may be an element of this vector.
+ LIBC_INLINE Checked push_back(const T &value) {
+ return push_back_impl(value);
+ }
+
+ /// Appends `value` by moving from it. `value` may be an element of this
+ /// vector. If the operation fails, `value` is left untouched.
+ LIBC_INLINE Checked push_back(T &&value) {
+ return push_back_impl(cpp::move(value));
+ }
+
+ LIBC_INLINE void pop_back() {
+ LIBC_ASSERT(count > 0);
+ truncate(count - 1);
+ }
+
+ /// Appends copies of the elements in [first, last), which must not point into
+ /// this vector.
+ template <typename It> LIBC_INLINE Checked append(It first, It last) {
+ size_t n = cpp::distance(first, last);
+ if (!grow_by(n))
+ return false;
+ for (T *dest = items + count; first != last; ++first, ++dest)
+ new (dest) T(*first);
+ count += n;
+ return true;
+ }
+
+ /// Replaces the contents with copies of the elements of `other`, which must
+ /// not be stored within an element of this vector.
+ LIBC_INLINE Checked assign(const Vector &other) {
+ if (this == &other)
+ return true;
+ if (other.count > cap) {
+ // Build the new contents in separate storage, so that a failure leaves
+ // this vector unchanged, and the old elements are not moved just to be
+ // destroyed.
+ Vector tmp;
+ if (!tmp.reserve(other.count) || !tmp.append(other.begin(), other.end()))
+ return false;
+ swap(tmp);
+ return true;
+ }
+ clear();
+ return append(other.begin(), other.end());
+ }
+};
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC___SUPPORT_VECTOR_H
diff --git a/libc/test/src/__support/CMakeLists.txt b/libc/test/src/__support/CMakeLists.txt
index 525388dc2f71c8..b36466651abc5e 100644
--- a/libc/test/src/__support/CMakeLists.txt
+++ b/libc/test/src/__support/CMakeLists.txt
@@ -122,6 +122,18 @@ add_libc_test(
libc.src.__support.blockstore
)
+add_libc_test(
+ checked_test
+ SUITE
+ libc-support-tests
+ SRCS
+ checked_test.cpp
+ DEPENDS
+ libc.src.__support.checked
+ libc.src.__support.CPP.type_traits
+ libc.src.__support.CPP.utility
+)
+
add_libc_test(
checked_ptr_test
SUITE
@@ -287,6 +299,21 @@ add_libc_test(
libc.src.__support.char_vector
)
+add_libc_test(
+ vector_test
+ SUITE
+ libc-support-tests
+ SRCS
+ vector_test.cpp
+ DEPENDS
+ libc.hdr.types.size_t
+ libc.src.__support.checked
+ libc.src.__support.CPP.limits
+ libc.src.__support.CPP.type_traits
+ libc.src.__support.CPP.utility
+ libc.src.__support.vector
+)
+
add_libc_test(
hash_test
SUITE
diff --git a/libc/test/src/__support/checked_test.cpp b/libc/test/src/__support/checked_test.cpp
new file mode 100644
index 00000000000000..d7e33436dc87e0
--- /dev/null
+++ b/libc/test/src/__support/checked_test.cpp
@@ -0,0 +1,92 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Unittests for Checked.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/__support/CPP/type_traits.h"
+#include "src/__support/CPP/utility.h"
+#include "src/__support/checked.h"
+#include "test/UnitTest/Test.h"
+
+using LIBC_NAMESPACE::Checked;
+using LIBC_NAMESPACE::cpp::is_constructible_v;
+using LIBC_NAMESPACE::cpp::is_convertible_v;
+using LIBC_NAMESPACE::cpp::move;
+
+// Verify compile-time properties:
+// - Implicitly constructible from bool, but not from other types.
+// - Movable, but not copyable.
+// - Explicit conversion to bool is only allowed on non-const lvalues/rvalues.
+static_assert(!is_constructible_v<Checked>);
+static_assert(is_convertible_v<bool, Checked>);
+static_assert(!is_constructible_v<Checked, int>);
+static_assert(!is_constructible_v<Checked, int *>);
+static_assert(is_constructible_v<Checked, Checked &&>);
+static_assert(!is_constructible_v<Checked, const Checked &>);
+static_assert(!is_convertible_v<Checked, bool>);
+static_assert(is_constructible_v<bool, Checked &>);
+static_assert(is_constructible_v<bool, Checked &&>);
+static_assert(!is_constructible_v<bool, const Checked &>);
+
+static Checked succeed() { return true; }
+static Checked fail() { return false; }
+
+TEST(LlvmLibcCheckedTest, Value) {
+ EXPECT_TRUE(static_cast<bool>(succeed()));
+ EXPECT_FALSE(static_cast<bool>(fail()));
+}
+
+TEST(LlvmLibcCheckedTest, Move) {
+ Checked c1 = succeed();
+ // Moving disarms `c1`, and `c2` needs to be checked instead.
+ Checked c2(move(c1));
+ EXPECT_TRUE(static_cast<bool>(c2));
+
+ Checked c3 = fail();
+ EXPECT_FALSE(static_cast<bool>(c3));
+ c3 = move(c2);
+ EXPECT_TRUE(static_cast<bool>(c3));
+}
+
+#if !defined(NDEBUG) && LIBC_TEST_SUBPROCESS_TESTS
+
+#if defined(LIBC_FULL_BUILD) && !defined(LIBC_COPT_USE_C_ASSERT)
+#define EXPECT_ASSERT_FAILS(stmt) EXPECT_EXITS(stmt, 255)
+#else
+#define EXPECT_ASSERT_FAILS(stmt) EXPECT_DEATH(stmt, WITH_SIGNAL(-1))
+#endif
+
+TEST(LlvmLibcCheckedDeathTest, UncheckedDestructionDies) {
+ EXPECT_ASSERT_FAILS([] {
+ Checked c = succeed();
+ (void)c;
+ });
+}
+
+TEST(LlvmLibcCheckedDeathTest, MoveFromCheckedRequiresRecheckOrDies) {
+ EXPECT_ASSERT_FAILS([] {
+ Checked c1 = succeed();
+ (void)static_cast<bool>(c1);
+ Checked c2(move(c1));
+ });
+}
+
+TEST(LlvmLibcCheckedDeathTest, OverwritingUncheckedViaMoveAssignmentDies) {
+ EXPECT_ASSERT_FAILS([] {
+ Checked c1 = succeed();
+ Checked c2 = succeed();
+ (void)static_cast<bool>(c2);
+ c1 = move(c2);
+ (void)static_cast<bool>(c1);
+ });
+}
+
+#endif // !defined(NDEBUG) && LIBC_TEST_SUBPROCESS_TESTS
diff --git a/libc/test/src/__support/vector_test.cpp b/libc/test/src/__support/vector_test.cpp
new file mode 100644
index 00000000000000..9a97273fec3150
--- /dev/null
+++ b/libc/test/src/__support/vector_test.cpp
@@ -0,0 +1,389 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Unittests for Vector.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/type_traits.h"
+#include "src/__support/CPP/utility.h"
+#include "src/__support/checked.h"
+#include "src/__support/vector.h"
+#include "test/UnitTest/Test.h"
+
+using LIBC_NAMESPACE::Checked;
+using LIBC_NAMESPACE::Vector;
+using LIBC_NAMESPACE::cpp::is_copy_assignable_v;
+using LIBC_NAMESPACE::cpp::is_copy_constructible_v;
+using LIBC_NAMESPACE::cpp::is_move_assignable_v;
+using LIBC_NAMESPACE::cpp::is_move_constructible_v;
+using LIBC_NAMESPACE::cpp::is_trivially_copyable_v;
+using LIBC_NAMESPACE::cpp::move;
+using LIBC_NAMESPACE::cpp::numeric_limits;
+
+// Copying needs to allocate, so it is only possible through assign().
+static_assert(!is_copy_constructible_v<Vector<int>>);
+static_assert(!is_copy_assignable_v<Vector<int>>);
+static_assert(is_move_constructible_v<Vector<int>>);
+static_assert(is_move_assignable_v<Vector<int>>);
+
+namespace {
+
+// Counts live objects, to catch leaked or doubly-destroyed elements.
+struct Counted {
+ static inline int live = 0;
+ int value;
+
+ Counted(int value = 0) : value(value) { ++live; }
+ Counted(const Counted &other) : value(other.value) { ++live; }
+ Counted(Counted &&other) : value(other.value) {
+ other.value = -1;
+ ++live;
+ }
+ ~Counted() {
+ value = -2;
+ --live;
+ }
+};
+
+struct MoveOnly {
+ int value;
+ explicit MoveOnly(int value) : value(value) {}
+ MoveOnly(MoveOnly &&other) : value(other.value) { other.value = -1; }
+ MoveOnly(const MoveOnly &) = delete;
+};
+
+// Vector<TreeNode> is instantiated while TreeNode is still incomplete.
+struct TreeNode {
+ int value;
+ Vector<TreeNode> children;
+};
+
+} // namespace
+
+// Trivially copyable types are moved with realloc, while the others are moved
+// one by one. Make sure we test both.
+static_assert(is_trivially_copyable_v<int>);
+static_assert(!is_trivially_copyable_v<Counted>);
+static_assert(!is_trivially_copyable_v<MoveOnly>);
+
+// Checks the result of a fallible operation, and converts it to bool so it can
+// be used with ASSERT_TRUE and friends.
+static bool ok(Checked result) { return static_cast<bool>(result); }
+
+static int value_of(int x) { return x; }
+static int value_of(const Counted &x) { return x.value; }
+
+template <typename T, size_t N>
+static void expect_contents(const Vector<T> &v, const int (&expected)[N]) {
+ ASSERT_EQ(v.size(), N);
+ for (size_t i = 0; i < N; ++i)
+ EXPECT_EQ(value_of(v[i]), expected[i]);
+}
+
+TEST(LlvmLibcVectorTest, Empty) {
+ Vector<int> v;
+ EXPECT_TRUE(v.empty());
+ EXPECT_EQ(v.size(), size_t(0));
+ EXPECT_EQ(v.capacity(), size_t(0));
+ EXPECT_TRUE(v.begin() == v.end());
+}
+
+TEST(LlvmLibcVectorTest, PushAndPop) {
+ Vector<int> v;
+ for (int i = 0; i < 20; ++i)
+ ASSERT_TRUE(ok(v.push_back(i)));
+ ASSERT_EQ(v.size(), size_t(20));
+ EXPECT_GE(v.capacity(), size_t(20));
+ EXPECT_FALSE(v.empty());
+ EXPECT_EQ(v.front(), 0);
+ EXPECT_EQ(v.back(), 19);
+ for (size_t i = 0; i < v.size(); ++i)
+ EXPECT_EQ(v[i], static_cast<int>(i));
+
+ for (int i = 19; i >= 0; --i) {
+ EXPECT_EQ(v.back(), i);
+ v.pop_back();
+ }
+ EXPECT_TRUE(v.empty());
+}
+
+TEST(LlvmLibcVectorTest, Iteration) {
+ Vector<int> v;
+ for (int i = 0; i < 4; ++i)
+ ASSERT_TRUE(ok(v.push_back(i)));
+
+ int expected = 0;
+ for (int &x : v)
+ EXPECT_EQ(x, expected++);
+ EXPECT_EQ(expected, 4);
+
+ const Vector<int> &cv = v;
+ expected = 0;
+ for (const int &x : cv)
+ EXPECT_EQ(x, expected++);
+ EXPECT_EQ(expected, 4);
+}
+
+TEST(LlvmLibcVectorTest, Reserve) {
+ Vector<int> v;
+ ASSERT_TRUE(ok(v.reserve(10)));
+ EXPECT_EQ(v.capacity(), size_t(10));
+ EXPECT_TRUE(v.empty());
+
+ // Filling up the reserved space does not reallocate.
+ int *data = v.data();
+ for (int i = 0; i < 10; ++i)
+ ASSERT_TRUE(ok(v.push_back(i)));
+ EXPECT_EQ(v.data(), data);
+
+ // Reserving less than the capacity does nothing.
+ ASSERT_TRUE(ok(v.reserve(5)));
+ EXPECT_EQ(v.capacity(), size_t(10));
+ EXPECT_EQ(v.data(), data);
+
+ ASSERT_TRUE(ok(v.reserve(20)));
+ EXPECT_EQ(v.capacity(), size_t(20));
+ expect_contents(v, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
+}
+
+TEST(LlvmLibcVectorTest, Resize) {
+ Vector<int> v;
+ ASSERT_TRUE(ok(v.resize(3)));
+ expect_contents(v, {0, 0, 0});
+
+ v[1] = 1;
+ v[2] = 2;
+ ASSERT_TRUE(ok(v.resize(2)));
+ expect_contents(v, {0, 1});
+
+ // New elements are value-initialized even if there is no reallocation.
+ ASSERT_TRUE(ok(v.resize(3)));
+ expect_contents(v, {0, 1, 0});
+}
+
+TEST(LlvmLibcVectorTest, Append) {
+ Vector<int> v;
+ const int ARR[] = {1, 2, 3};
+ ASSERT_TRUE(ok(v.append(ARR, ARR + 3)));
+ ASSERT_TRUE(ok(v.append(ARR, ARR)));
+ ASSERT_TRUE(ok(v.append(ARR + 1, ARR + 3)));
+ expect_contents(v, {1, 2, 3, 2, 3});
+}
+
+TEST(LlvmLibcVectorTest, PushBackOwnElementWhileGrowing) {
+ Vector<int> v;
+ ASSERT_TRUE(ok(v.reserve(2)));
+ ASSERT_TRUE(ok(v.push_back(1)));
+ ASSERT_TRUE(ok(v.push_back(2)));
+ // Without spare capacity, the push_back needs to grow the storage, which
+ // invalidates the reference to the element being appended.
+ ASSERT_EQ(v.size(), v.capacity());
+ ASSERT_TRUE(ok(v.push_back(v[0])));
+ expect_contents(v, {1, 2, 1});
+}
+
+TEST(LlvmLibcVectorTest, PushBackCopiesOrMoves) {
+ Vector<Counted> v;
+ Counted c(1);
+ ASSERT_TRUE(ok(v.push_back(c)));
+ EXPECT_EQ(c.value, 1);
+ ASSERT_TRUE(ok(v.push_back(move(c))));
+ EXPECT_EQ(c.value, -1);
+ expect_contents(v, {1, 1});
+}
+
+TEST(LlvmLibcVectorTest, PushBackMovedOwnElementWhileGrowing) {
+ Vector<Counted> v;
+ ASSERT_TRUE(ok(v.reserve(2)));
+ ASSERT_TRUE(ok(v.push_back(Counted(1))));
+ ASSERT_TRUE(ok(v.push_back(Counted(2))));
+ // Growing the storage moves the elements, so the new element has to be moved
+ // from the new location of v[0], leaving it in the moved-from state.
+ ASSERT_EQ(v.size(), v.capacity());
+ ASSERT_TRUE(ok(v.push_back(move(v[0]))));
+ expect_contents(v, {-1, 2, 1});
+}
+
+TEST(LlvmLibcVectorTest, Assign) {
+ const int ARR[] = {1, 2, 3, 4};
+ Vector<int> v;
+ ASSERT_TRUE(ok(v.append(ARR, ARR + 4)));
+
+ Vector<int> w;
+ ASSERT_TRUE(ok(w.assign(v)));
+ EXPECT_NE(w.data(), v.data());
+ expect_contents(w, {1, 2, 3, 4});
+
+ // Assigning fewer elements keeps the storage.
+ int *data = w.data();
+ v.pop_back();
+ v.pop_back();
+ ASSERT_TRUE(ok(w.assign(v)));
+ EXPECT_EQ(w.data(), data);
+ expect_contents(w, {1, 2});
+
+ // Self-assignment does nothing.
+ ASSERT_TRUE(ok(w.assign(w)));
+ expect_contents(w, {1, 2});
+}
+
+TEST(LlvmLibcVectorTest, MoveAndSwap) {
+ Vector<int> a;
+ ASSERT_TRUE(ok(a.resize(3)));
+ int *data = a.data();
+
+ Vector<int> b(move(a));
+ EXPECT_TRUE(a.empty());
+ EXPECT_EQ(a.capacity(), size_t(0));
+ EXPECT_EQ(b.size(), size_t(3));
+ EXPECT_EQ(b.data(), data);
+
+ Vector<int> c;
+ ASSERT_TRUE(ok(c.push_back(2)));
+ c = move(b);
+ EXPECT_TRUE(b.empty());
+ EXPECT_EQ(c.size(), size_t(3));
+ EXPECT_EQ(c.data(), data);
+
+ // Self-move-assignment leaves the vector unchanged.
+ Vector<int> &alias = c;
+ c = move(alias);
+ EXPECT_EQ(c.size(), size_t(3));
+ EXPECT_EQ(c.data(), data);
+
+ ASSERT_TRUE(ok(a.push_back(4)));
+ a.swap(c);
+ EXPECT_EQ(a.size(), size_t(3));
+ EXPECT_EQ(a.data(), data);
+ expect_contents(c, {4});
+}
+
+TEST(LlvmLibcVectorTest, AllocationFailure) {
+ // None of these sizes can be allocated. They are rejected before allocating,
+ // which keeps the test friendly to simple test allocators.
+ constexpr size_t HUGE_SIZE = numeric_limits<size_t>::max();
+ // Computing the allocation size for this one in a naive way would overflow
+ // to a small number.
+ constexpr size_t OVERFLOWING_SIZE = HUGE_SIZE / sizeof(int) + 2;
+
+ Vector<int> v;
+ const int ARR[] = {1, 2, 3};
+ ASSERT_TRUE(ok(v.append(ARR, ARR + 3)));
+ int *data = v.data();
+ size_t capacity = v.capacity();
+
+ EXPECT_FALSE(ok(v.reserve(HUGE_SIZE)));
+ EXPECT_FALSE(ok(v.reserve(OVERFLOWING_SIZE)));
+ EXPECT_FALSE(ok(v.resize(HUGE_SIZE)));
+ EXPECT_FALSE(ok(v.resize(OVERFLOWING_SIZE)));
+
+ // Failed operations leave the vector unchanged.
+ EXPECT_EQ(v.data(), data);
+ EXPECT_EQ(v.capacity(), capacity);
+ expect_contents(v, {1, 2, 3});
+}
+
+TEST(LlvmLibcVectorTest, ElementLifetimes) {
+ Counted::live = 0;
+ {
+ Vector<Counted> v;
+ ASSERT_TRUE(ok(v.reserve(4)));
+ for (int i = 0; i < 4; ++i)
+ ASSERT_TRUE(ok(v.push_back(Counted(i))));
+ EXPECT_EQ(Counted::live, 4);
+
+ // The storage is full, so this needs to move the elements, which
+ // invalidates the reference to the element being appended.
+ ASSERT_EQ(v.size(), v.capacity());
+ ASSERT_TRUE(ok(v.push_back(v[2])));
+ EXPECT_EQ(Counted::live, 5);
+ expect_contents(v, {0, 1, 2, 3, 2});
+
+ v.pop_back();
+ EXPECT_EQ(Counted::live, 4);
+ ASSERT_TRUE(ok(v.resize(2)));
+ EXPECT_EQ(Counted::live, 2);
+ ASSERT_TRUE(ok(v.resize(4)));
+ EXPECT_EQ(Counted::live, 4);
+ expect_contents(v, {0, 1, 0, 0});
+
+ Vector<Counted> w;
+ ASSERT_TRUE(ok(w.assign(v)));
+ EXPECT_EQ(Counted::live, 8);
+ expect_contents(w, {0, 1, 0, 0});
+
+ ASSERT_TRUE(ok(v.append(w.begin(), w.begin() + 2)));
+ EXPECT_EQ(Counted::live, 10);
+ expect_contents(v, {0, 1, 0, 0, 0, 1});
+
+ v = move(w);
+ EXPECT_EQ(Counted::live, 4);
+ v.clear();
+ EXPECT_EQ(Counted::live, 0);
+ }
+ EXPECT_EQ(Counted::live, 0);
+}
+
+TEST(LlvmLibcVectorTest, MoveOnlyElements) {
+ Vector<MoveOnly> v;
+ for (int i = 0; i < 10; ++i)
+ ASSERT_TRUE(ok(v.push_back(MoveOnly(i))));
+
+ Vector<MoveOnly> w(move(v));
+ ASSERT_EQ(w.size(), size_t(10));
+ for (size_t i = 0; i < w.size(); ++i)
+ EXPECT_EQ(w[i].value, static_cast<int>(i));
+}
+
+TEST(LlvmLibcVectorTest, IncompleteType) {
+ TreeNode root{1, {}};
+ ASSERT_TRUE(ok(root.children.push_back(TreeNode{2, {}})));
+ ASSERT_TRUE(ok(root.children.push_back(TreeNode{3, {}})));
+ ASSERT_TRUE(ok(root.children[0].children.push_back(TreeNode{4, {}})));
+
+ ASSERT_EQ(root.children.size(), size_t(2));
+ EXPECT_EQ(root.children[0].value, 2);
+ EXPECT_EQ(root.children[1].value, 3);
+ ASSERT_EQ(root.children[0].children.size(), size_t(1));
+ EXPECT_EQ(root.children[0].children[0].value, 4);
+}
+
+#if !defined(NDEBUG) && LIBC_TEST_SUBPROCESS_TESTS
+
+#if defined(LIBC_FULL_BUILD) && !defined(LIBC_COPT_USE_C_ASSERT)
+#define EXPECT_ASSERT_FAILS(stmt) EXPECT_EXITS(stmt, 255)
+#else
+#define EXPECT_ASSERT_FAILS(stmt) EXPECT_DEATH(stmt, WITH_SIGNAL(-1))
+#endif
+
+TEST(LlvmLibcVectorDeathTest, UncheckedResultDies) {
+ EXPECT_ASSERT_FAILS([] {
+ Vector<int> v;
+ (void)v.push_back(1);
+ });
+}
+
+TEST(LlvmLibcVectorDeathTest, OutOfBoundsAccessDies) {
+ EXPECT_ASSERT_FAILS([] {
+ Vector<int> v;
+ (void)v[0];
+ });
+}
+
+TEST(LlvmLibcVectorDeathTest, PopBackOnEmptyVectorDies) {
+ EXPECT_ASSERT_FAILS([] {
+ Vector<int> v;
+ v.pop_back();
+ });
+}
+
+#endif // !defined(NDEBUG) && LIBC_TEST_SUBPROCESS_TESTS
diff --git a/utils/bazel/llvm-project-overlay/libc/src/__support/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/src/__support/BUILD.bazel
index 491b4b67113277..b9779038999093 100644
--- a/utils/bazel/llvm-project-overlay/libc/src/__support/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/src/__support/BUILD.bazel
@@ -366,12 +366,22 @@ libc_support_library(
],
)
+libc_support_library(
+ name = "checked",
+ hdrs = ["checked.h"],
+ deps = [
+ ":libc_assert",
+ "//libc/src/__support/macros:attributes",
+ "//libc/src/__support/macros:config",
+ ],
+)
+
libc_support_library(
name = "checked_ptr",
hdrs = ["checked_ptr.h"],
deps = [
":alloc_checker",
- ":libc_assert",
+ ":checked",
"//libc/hdr/types:size_t",
"//libc/src/__support/CPP:nullptr_t",
"//libc/src/__support/CPP:type_traits",
More information about the libc-commits
mailing list