From d84b69ace982bd0366ca026e26422986825d1f5e Mon Sep 17 00:00:00 2001 From: Nico Weber Date: Thu, 8 Feb 2024 18:52:45 -0500 Subject: [PATCH] AK: Add to_array() This is useful if you want an array with an explicit type but still want its size to be inferred. --- AK/Array.h | 15 +++++++++++++++ Tests/AK/TestArray.cpp | 9 +++++++++ 2 files changed, 24 insertions(+) diff --git a/AK/Array.h b/AK/Array.h index a8c5629f2af..0b43544f9ce 100644 --- a/AK/Array.h +++ b/AK/Array.h @@ -162,9 +162,24 @@ constexpr auto iota_array(T const offset = {}) return Detail::integer_sequence_generate_array(offset, MakeIntegerSequence()); } +namespace Detail { +template +constexpr auto to_array_impl(T (&&a)[N], IndexSequence) -> Array +{ + return { { a[Is]... } }; +} +} + +template +constexpr auto to_array(T (&&a)[N]) +{ + return Detail::to_array_impl(move(a), MakeIndexSequence()); +} + } #if USING_AK_GLOBALLY using AK::Array; using AK::iota_array; +using AK::to_array; #endif diff --git a/Tests/AK/TestArray.cpp b/Tests/AK/TestArray.cpp index 24c687fc278..12f8ce35753 100644 --- a/Tests/AK/TestArray.cpp +++ b/Tests/AK/TestArray.cpp @@ -46,3 +46,12 @@ TEST_CASE(first_index_of) EXPECT(array.first_index_of(7) == 7u); EXPECT(!array.first_index_of(42).has_value()); } + +TEST_CASE(to_array) +{ + constexpr auto array = to_array({ 0, 2, 1 }); + static_assert(array.size() == 3); + static_assert(array[0] == 0); + static_assert(array[1] == 2); + static_assert(array[2] == 1); +}