Skip to content

Commit ad97ee2

Browse files
[libc][support][FixedVector] add reverse iterator (#86732)
Critically, we don't want to return an iterator to the end of the underlying cpp::array "store." Add a test to catch this issue. This will be used by __cxa_finalize to iterate backwards through a FixedVector. Link: #85651
1 parent 4238324 commit ad97ee2

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

libc/src/__support/fixedvector.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
#include "src/__support/CPP/array.h"
1313

14+
#include "src/__support/CPP/iterator.h"
15+
1416
namespace LIBC_NAMESPACE {
1517

1618
// A fixed size data store backed by an underlying cpp::array data structure. It
@@ -55,6 +57,12 @@ template <typename T, size_t CAPACITY> class FixedVector {
5557
// matches the `destroy` API of those other data structures so that users
5658
// can easily swap one data structure for the other.
5759
static void destroy(FixedVector<T, CAPACITY> *store) { store->reset(); }
60+
61+
using reverse_iterator = typename cpp::array<T, CAPACITY>::reverse_iterator;
62+
LIBC_INLINE constexpr reverse_iterator rbegin() {
63+
return reverse_iterator{&store[item_count]};
64+
}
65+
LIBC_INLINE constexpr reverse_iterator rend() { return store.rend(); }
5866
};
5967

6068
} // namespace LIBC_NAMESPACE

libc/test/src/__support/fixedvector_test.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,19 @@ TEST(LlvmLibcFixedVectorTest, Destroy) {
4343
LIBC_NAMESPACE::FixedVector<int, 20>::destroy(&fixed_vector);
4444
ASSERT_TRUE(fixed_vector.empty());
4545
}
46+
47+
TEST(LlvmLibcFixedVectorTest, Iteration) {
48+
LIBC_NAMESPACE::FixedVector<int, 20> v;
49+
for (int i = 0; i < 3; i++)
50+
v.push_back(i);
51+
auto it = v.rbegin();
52+
ASSERT_EQ(*it, 2);
53+
ASSERT_EQ(*++it, 1);
54+
ASSERT_EQ(*++it, 0);
55+
// TODO: need an overload of Test::test for iterators?
56+
// ASSERT_EQ(++it, v.rend());
57+
// ASSERT_EQ(v.rbegin(), v.rbegin());
58+
ASSERT_TRUE(++it == v.rend());
59+
for (auto it = v.rbegin(), e = v.rend(); it != e; ++it)
60+
ASSERT_GT(*it, -1);
61+
}

utils/bazel/llvm-project-overlay/libc/BUILD.bazel

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,7 @@ libc_support_library(
444444
hdrs = ["src/__support/fixedvector.h"],
445445
deps = [
446446
":__support_cpp_array",
447+
":__support_cpp_iterator",
447448
],
448449
)
449450

0 commit comments

Comments
 (0)