Skip to content

Commit

Permalink
pw_vector: Add constexpr max_size() for fixed-sized vector
Browse files Browse the repository at this point in the history
This change introduces the max_size() function for the
fixed-sized vector implementation. By declaring it as
static constexpr we can use the max_size of a
fixed-size vector to size another vector at compile time.
If only the generic vector gets passed to a function, the
generic max_size function gets called, that won't return
the constexpr max size value.

Tested: Added ConstexprMaxSize test case

Change-Id: I45ea288d756641e108103c4e0ce958759876e32a
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/122891
Reviewed-by: Wyatt Hepler <[email protected]>
Commit-Queue: Christoph Klee <[email protected]>
  • Loading branch information
Christoph Klee authored and CQ Bot Account committed Dec 12, 2022
1 parent dd46333 commit 6ecba3c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
2 changes: 2 additions & 0 deletions pw_containers/public/pw_containers/vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ class Vector : public Vector<T, vector_impl::kGeneric> {
Vector(std::initializer_list<T> list)
: Vector<T, vector_impl::kGeneric>(kMaxSize, list) {}

static constexpr size_t max_size() { return kMaxSize; }

// Construct from std::string_view when T is char.
template <typename U = T,
typename = std::enable_if_t<std::is_same_v<U, char>>>
Expand Down
13 changes: 13 additions & 0 deletions pw_containers/vector_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,19 @@ TEST(Vector, Generic) {
}
}

TEST(Vector, ConstexprMaxSize) {
Vector<int, 10> vector;
Vector<int, vector.max_size()> vector2;

EXPECT_EQ(vector.max_size(), vector2.max_size());

// The following code would fail with the following compiler error:
// "non-type template argument is not a constant expression"
// Reason: the generic_vector doesn't return a constexpr max_size value.
// Vector<int>& generic_vector(vector);
// Vector<int, generic_vector.max_size()> vector3;
}

// Test that Vector<T> is trivially destructible when its type is.
static_assert(std::is_trivially_destructible_v<Vector<int>>);
static_assert(std::is_trivially_destructible_v<Vector<int, 4>>);
Expand Down

0 comments on commit 6ecba3c

Please sign in to comment.