[libc-commits] [libc] [llvm] [libc] Implement a Vector container (PR #243109)
Pavel Labath via libc-commits
libc-commits at lists.llvm.org
Tue Nov 17 02:37:28 PST 2026
https://github.com/labath updated https://github.com/llvm/llvm-project/pull/243109
>From 39f652c0723ff70749ea63a34e193c0614139cee 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 (currently just push_back) 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.
This patch implements only the most basic vector operations. Other
operations can be added if there's a sufficiently compelling use case.
The copy constructor and assignment are deleted, as copying needs to
allocate. And the default operations cannot return errors. 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).
A failed operation leaves the vector unchanged.
Vector only supports trivially copyable types for now. Supporting other
types is an open question. 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.
As a first user, I'm converting the array of byte sets in the regex
ExprPool. The old code made room for a new set before interning the
node which refers to it, and stored the set afterwards, so that a
failed intern wouldn't leave the set behind. Doing the same with Vector
would need something like reserve(size() + 1), which defeats the
geometric growth, so I'm appending the set first, and popping it if
interning fails. The array no longer starts with a capacity of four,
but it's still allocated lazily, so pure literal patterns don't
allocate it at all.
The plan is to use this to replace other hand-rolled growable arrays
(e.g. ScannedEntries in dir_scan_impl.h) as well, which I'll do in
separate patches.
Assisted-by: Gemini
---
libc/src/__support/CMakeLists.txt | 32 ++-
libc/src/__support/checked.h | 106 ++++++++++
libc/src/__support/checked_ptr.h | 46 +----
libc/src/__support/regex/CMakeLists.txt | 1 +
libc/src/__support/regex/regex_expr_pool.cpp | 20 +-
libc/src/__support/regex/regex_expr_pool.h | 21 +-
libc/src/__support/vector.h | 184 +++++++++++++++++
libc/test/src/__support/CMakeLists.txt | 26 +++
libc/test/src/__support/checked_test.cpp | 92 +++++++++
libc/test/src/__support/regex/expr_test.cpp | 4 +-
libc/test/src/__support/vector_test.cpp | 188 ++++++++++++++++++
.../libc/src/__support/BUILD.bazel | 12 +-
12 files changed, 651 insertions(+), 81 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..4e15b8fcb895c0 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,26 @@ 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.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/regex/CMakeLists.txt b/libc/src/__support/regex/CMakeLists.txt
index 2b9ce08e4dd214..7cd021d9aca183 100644
--- a/libc/src/__support/regex/CMakeLists.txt
+++ b/libc/src/__support/regex/CMakeLists.txt
@@ -19,6 +19,7 @@ add_object_library(
libc.src.__support.hash
libc.src.__support.libc_assert
libc.src.__support.macros.config
+ libc.src.__support.vector
)
add_header_library(
diff --git a/libc/src/__support/regex/regex_expr_pool.cpp b/libc/src/__support/regex/regex_expr_pool.cpp
index cd5d2ced4a66df..091c31a39f6d89 100644
--- a/libc/src/__support/regex/regex_expr_pool.cpp
+++ b/libc/src/__support/regex/regex_expr_pool.cpp
@@ -225,29 +225,17 @@ ErrorOr<ExprId> ExprPool::make_byte_set(const ByteSet &bs) {
return make_lit(static_cast<char>(last_bit));
uint32_t bs_id = 0;
- for (const ByteSet &existing : active_byte_sets()) {
+ for (const ByteSet &existing : byte_sets) {
if (existing == bs)
return intern(Expr::make_byte_set(bs_id));
++bs_id;
}
- if (byte_set_count == byte_set_capacity) {
- size_t new_cap = byte_set_capacity == 0 ? INITIAL_BYTE_SETS_CAPACITY
- : byte_set_capacity * GROWTH_FACTOR;
- auto new_sets = make_unique<ByteSet[]>(new_cap);
- if (!new_sets)
- return Error(REG_ESPACE);
- for (size_t i = 0; i < byte_set_count; ++i)
- new_sets[i] = byte_sets[i];
- byte_sets = new_sets.take_unique();
- byte_set_capacity = new_cap;
- }
-
+ if (!byte_sets.push_back(bs))
+ return Error(REG_ESPACE);
ErrorOr<ExprId> id = intern(Expr::make_byte_set(bs_id));
if (!id.has_value())
- return id;
- byte_sets[byte_set_count] = bs;
- ++byte_set_count;
+ byte_sets.pop_back();
return id;
}
diff --git a/libc/src/__support/regex/regex_expr_pool.h b/libc/src/__support/regex/regex_expr_pool.h
index 4bc1e1ba18f218..2f8ea57a3481ad 100644
--- a/libc/src/__support/regex/regex_expr_pool.h
+++ b/libc/src/__support/regex/regex_expr_pool.h
@@ -21,6 +21,7 @@
#include "src/__support/libc_assert.h"
#include "src/__support/macros/config.h"
#include "src/__support/regex/regex_ast.h"
+#include "src/__support/vector.h"
#include <stddef.h>
namespace LIBC_NAMESPACE_DECL {
@@ -48,9 +49,6 @@ class ExprPool {
/// Initial directory capacity for 8 blocks (64B), holding up to 256 nodes
/// before directory growth.
static constexpr size_t INITIAL_BLOCKS_CAPACITY = 8;
- /// Initial capacity for 4 unique ByteSets (4 * 32B = 128B), allocated lazily
- /// on the first multi-bit ByteSet so pure literal patterns allocate 0 bytes.
- static constexpr size_t INITIAL_BYTE_SETS_CAPACITY = 4;
/// Initial power-of-two hash table size: 64 slots (256B), holding up to 44
/// unique nodes at 70% max load factor while keeping initial pool footprint
/// at 512B + 64B + 256B = 832B (< 1 KiB).
@@ -69,18 +67,12 @@ class ExprPool {
size_t node_count = 0;
/// Lazily allocated array of deduplicated 256-bit character sets.
- cpp::unique_ptr<ByteSet[]> byte_sets;
- size_t byte_set_capacity = 0;
- size_t byte_set_count = 0;
+ Vector<ByteSet> byte_sets;
/// Open-addressing hash table storing ExprIds (0 = empty bucket).
cpp::unique_ptr<ExprId[]> hashtable;
size_t hashtable_capacity = 0;
- cpp::span<const ByteSet> active_byte_sets() const {
- return {byte_sets.get(), byte_set_count};
- }
-
cpp::span<ExprId> hashtable_slots() {
return {hashtable.get(), hashtable_capacity};
}
@@ -130,10 +122,7 @@ class ExprPool {
const Expr &get(ExprId id) const { return slot_at(id); }
/// Resolves a ByteSet index to its 256-bit character set.
- const ByteSet &get_byte_set(uint32_t id) const {
- LIBC_ASSERT(id < byte_set_count);
- return byte_sets[id];
- }
+ const ByteSet &get_byte_set(uint32_t id) const { return byte_sets[id]; }
/// O(1) unconditional nullability query for a valid ExprId.
bool is_nullable(ExprId id) const { return get(id).nullable; }
@@ -145,14 +134,14 @@ class ExprPool {
size_t size() const { return node_count; }
/// Returns the number of unique multi-bit ByteSets interned in this pool.
- size_t num_byte_sets() const { return byte_set_count; }
+ size_t num_byte_sets() const { return byte_sets.size(); }
/// Returns the current heap bytes allocated by this pool.
size_t allocated_bytes() const {
return (block_count * sizeof(Block)) +
(block_capacity * sizeof(cpp::unique_ptr<Block>)) +
(hashtable_capacity * sizeof(ExprId)) +
- (byte_set_capacity * sizeof(ByteSet));
+ (byte_sets.capacity() * sizeof(ByteSet));
}
// TODO: Use fluent interface (and_then, transform) for these factories once
diff --git a/libc/src/__support/vector.h b/libc/src/__support/vector.h
new file mode 100644
index 00000000000000..c4c437cdec265f
--- /dev/null
+++ b/libc/src/__support/vector.h
@@ -0,0 +1,184 @@
+//===----------------------------------------------------------------------===//
+//
+// 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/realloc.h"
+#include "hdr/stdint_proxy.h"
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/algorithm.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.
+///
+/// T must be trivially copyable, so that the elements can be moved with
+/// realloc. Over-aligned types (whose alignment exceeds alignof(max_align_t))
+/// are not supported either. 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);
+ }
+
+ // Moves the elements to new storage with room for `new_cap` elements.
+ LIBC_INLINE bool reallocate(size_t new_cap) {
+ // These are checked here rather than at class scope, so that T can be
+ // incomplete when Vector<T> is instantiated.
+ static_assert(cpp::is_trivially_copyable_v<T>,
+ "non-trivially-copyable types are not supported");
+ static_assert(alignof(T) <= alignof(max_align_t),
+ "over-aligned types are not supported");
+ // Together with trivial copyability, this guarantees that T is an
+ // implicit-lifetime type, 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);
+ // realloc can avoid the copy if it manages to resize the block in place.
+ T *new_items = static_cast<T *>(::realloc(items, new_cap * sizeof(T)));
+ if (new_items == nullptr)
+ return false;
+ items = new_items;
+ cap = new_cap;
+ return true;
+ }
+
+ // Makes room for at least one more element in a full vector.
+ LIBC_INLINE bool grow() {
+ LIBC_ASSERT(count == cap);
+ if (cap == max_size())
+ return false;
+ // Grow geometrically, so that appends take amortized constant time.
+ return reallocate(cpp::max(cap + 1, 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;
+ }
+
+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() { ::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 void clear() { count = 0; }
+
+ /// Appends a copy of `value`, which may be an element of this vector.
+ LIBC_INLINE Checked push_back(const T &value) {
+ const T *ptr = &value;
+ if (count == cap) {
+ // Growing the storage moves `value` if it is an element of this vector,
+ // so in that case we find it again by its index.
+ size_t index = index_of(ptr);
+ if (!grow())
+ return false;
+ if (index < count)
+ ptr = items + index;
+ }
+ new (items + count) T(*ptr);
+ ++count;
+ return true;
+ }
+
+ LIBC_INLINE void pop_back() {
+ LIBC_ASSERT(count > 0);
+ --count;
+ }
+};
+
+} // 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..71ffa049e23fe8 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,20 @@ 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.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/regex/expr_test.cpp b/libc/test/src/__support/regex/expr_test.cpp
index 990a67d0cc87c3..d2e9718ca588e7 100644
--- a/libc/test/src/__support/regex/expr_test.cpp
+++ b/libc/test/src/__support/regex/expr_test.cpp
@@ -108,7 +108,7 @@ TEST(LlvmLibcRegexExprTest, ByteSetNormalizationAndDeduplication) {
EXPECT_TRUE(pool.get_byte_set(0) == bs);
EXPECT_LE(pool.allocated_bytes(), size_t(1024));
- // Grow past INITIAL_BYTE_SETS_CAPACITY (4).
+ // Add enough byte sets to make the array grow.
for (uint8_t i = 0; i < 5; ++i) {
ByteSet multi;
multi.set(i);
@@ -254,7 +254,7 @@ TEST(LlvmLibcRegexExprTest, MemoryLimits) {
EXPECT_EQ(fail.error(), REG_ESPACE);
// A new multi-bit ByteSet at MAX_NODE_LIMIT fails without incrementing
- // byte_set_count.
+ // num_byte_sets().
ByteSet bs;
bs.flip();
auto bs_fail = pool.make_byte_set(bs);
diff --git a/libc/test/src/__support/vector_test.cpp b/libc/test/src/__support/vector_test.cpp
new file mode 100644
index 00000000000000..8bb9358d92e0ee
--- /dev/null
+++ b/libc/test/src/__support/vector_test.cpp
@@ -0,0 +1,188 @@
+//===----------------------------------------------------------------------===//
+//
+// 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/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::move;
+
+// Copying needs to allocate, and the copy operations can't report failures.
+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 {
+
+// Vector<Point> is instantiated while Point is still incomplete.
+struct Point;
+struct Polygon {
+ Vector<Point> vertices;
+};
+struct Point {
+ int x;
+ int y;
+};
+
+} // namespace
+
+// 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); }
+
+template <size_t N>
+static void expect_contents(const Vector<int> &v, const int (&expected)[N]) {
+ ASSERT_EQ(v.size(), N);
+ for (size_t i = 0; i < N; ++i)
+ EXPECT_EQ(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, PushBackOwnElementWhileGrowing) {
+ Vector<int> v;
+ 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, MoveAndSwap) {
+ Vector<int> a;
+ for (int i = 0; i < 3; ++i)
+ ASSERT_TRUE(ok(a.push_back(i)));
+ 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, IncompleteType) {
+ Polygon p;
+ ASSERT_TRUE(ok(p.vertices.push_back(Point{1, 2})));
+ ASSERT_TRUE(ok(p.vertices.push_back(Point{3, 4})));
+
+ ASSERT_EQ(p.vertices.size(), size_t(2));
+ EXPECT_EQ(p.vertices[0].x, 1);
+ EXPECT_EQ(p.vertices[0].y, 2);
+ EXPECT_EQ(p.vertices[1].x, 3);
+ EXPECT_EQ(p.vertices[1].y, 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