From 858c4d70cd8eff85b8c203696baa32be5c101c06 Mon Sep 17 00:00:00 2001 From: Alessio Bazzica Date: Mon, 14 May 2018 16:33:58 +0200 Subject: [PATCH] ArrayView, adding ctor for fixed-size views of std::array. This CL allows to reduce the code required to create fixed-size ArrayView objects for std::array instances. Instead of passing .data() and .size(), it is now sufficient to pass the std::array instance. When instancing an array view with variable size, a different ctor is called. Bug: webrtc:9076 Change-Id: I4fe133b27cd12827ed0206d40184279fc3a196f5 Reviewed-on: https://webrtc-review.googlesource.com/76160 Commit-Queue: Alessio Bazzica Reviewed-by: Karl Wiberg Cr-Commit-Position: refs/heads/master@{#23220} --- api/array_view.h | 13 ++++++++++++- api/array_view_unittest.cc | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/api/array_view.h b/api/array_view.h index d951d0f02d..a9df84d7f5 100644 --- a/api/array_view.h +++ b/api/array_view.h @@ -11,6 +11,7 @@ #ifndef API_ARRAY_VIEW_H_ #define API_ARRAY_VIEW_H_ +#include #include #include @@ -169,7 +170,7 @@ class ArrayView final : public impl::ArrayViewBase { RTC_DCHECK_EQ(0, size); } - // Construct an ArrayView from an array. + // Construct an ArrayView from a C-style array. template ArrayView(U (&array)[N]) // NOLINT : ArrayView(array, N) { @@ -177,6 +178,16 @@ class ArrayView final : public impl::ArrayViewBase { "Array size must match ArrayView size"); } + // (Only if size is fixed.) Construct an ArrayView with fixed size from an + // std::array instance. For an ArrayView with variable size, the used ctor is + // ArrayView(U& u) instead - i.e., the next one. + template (N)>::type* = nullptr> + ArrayView(std::array& u) // NOLINT + : ArrayView(u.data(), u.size()) {} + // (Only if size is fixed.) Construct an ArrayView from any type U that has a // static constexpr size() method whose return value is equal to Size, and a // data() method whose return value converts implicitly to T*. In particular, diff --git a/api/array_view_unittest.cc b/api/array_view_unittest.cc index 48dff2c266..0cea889cd5 100644 --- a/api/array_view_unittest.cc +++ b/api/array_view_unittest.cc @@ -9,6 +9,7 @@ */ #include +#include #include #include #include @@ -180,6 +181,19 @@ TEST(ArrayViewTest, TestCopyAssignmentFixed) { // v = z; // Compile error, because can't drop const. } +TEST(ArrayViewTest, TestStdArray) { + constexpr size_t size = 5; + std::array arr{}; + // Fixed size view. + rtc::ArrayView arr_view_fixed(arr); + EXPECT_EQ(arr.data(), arr_view_fixed.data()); + static_assert(size == arr_view_fixed.size(), ""); + // Variable size view. + rtc::ArrayView arr_view(arr); + EXPECT_EQ(arr.data(), arr_view.data()); + EXPECT_EQ(size, arr_view.size()); +} + TEST(ArrayViewTest, TestStdVector) { std::vector v; v.push_back(3);