xref: /aosp_15_r20/external/pigweed/pw_containers/public/pw_containers/to_array.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2021 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include <array>
17 #include <cstddef>
18 #include <type_traits>
19 #include <utility>
20 
21 namespace pw {
22 namespace containers {
23 
24 // If std::to_array is available, use it as pw::containers::to_array.
25 #ifdef __cpp_lib_to_array
26 
27 using std::to_array;
28 
29 #else
30 
31 namespace impl {
32 
33 template <typename T, size_t kSize, size_t... kIndices>
34 constexpr std::array<std::remove_cv_t<T>, kSize> CopyArray(
35     const T (&values)[kSize], std::index_sequence<kIndices...>) {
36   return {{values[kIndices]...}};
37 }
38 
39 template <typename T, size_t kSize, size_t... kIndices>
40 constexpr std::array<std::remove_cv_t<T>, kSize> MoveArray(
41     T (&&values)[kSize], std::index_sequence<kIndices...>) {
42   return {{std::move(values[kIndices])...}};
43 }
44 
45 }  // namespace impl
46 
47 // If C++20's std::to_array is not available, implement pw::containers::to_array
48 // in a C++14-compatible way.
49 template <typename T, size_t kSize>
50 constexpr std::array<std::remove_cv_t<T>, kSize> to_array(T (&values)[kSize]) {
51   return impl::CopyArray(values, std::make_index_sequence<kSize>{});
52 }
53 
54 template <typename T, size_t kSize>
55 constexpr std::array<std::remove_cv_t<T>, kSize> to_array(T (&&values)[kSize]) {
56   return impl::MoveArray(std::move(values), std::make_index_sequence<kSize>{});
57 }
58 
59 #endif  // __cpp_lib_to_array
60 
61 }  // namespace containers
62 }  // namespace pw
63