Adding reinterpret to ArrayView to allow data manipulation.
Reinterpret will only allow conversions when the underlying types are
fundamental and have the same size.
Bug: None
Change-Id: Id6a4e9784998fe65fb26ab3fd398710c892c4a67
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/128228
Commit-Queue: Amit Hilbuch <amithi@webrtc.org>
Reviewed-by: Karl Wiberg <kwiberg@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#27249}
diff --git a/api/array_view.h b/api/array_view.h
index bf91484..f7130dc 100644
--- a/api/array_view.h
+++ b/api/array_view.h
@@ -285,6 +285,23 @@
return ArrayView<T>(data, size);
}
+// Only for primitive types that have the same size and aligment.
+// Allow reinterpret cast of the array view to another primitive type of the
+// same size.
+// Template arguments order is (U, T, Size) to allow deduction of the template
+// arguments in client calls: reinterpret_array_view<target_type>(array_view).
+template <typename U, typename T, std::ptrdiff_t Size>
+inline ArrayView<U, Size> reinterpret_array_view(ArrayView<T, Size> view) {
+ static_assert(sizeof(U) == sizeof(T) && alignof(U) == alignof(T),
+ "ArrayView reinterpret_cast is only supported for casting "
+ "between views that represent the same chunk of memory.");
+ static_assert(
+ std::is_fundamental<T>::value && std::is_fundamental<U>::value,
+ "ArrayView reinterpret_cast is only supported for casting between "
+ "fundamental types.");
+ return ArrayView<U, Size>(reinterpret_cast<U*>(view.data()), view.size());
+}
+
} // namespace rtc
#endif // API_ARRAY_VIEW_H_
diff --git a/api/array_view_unittest.cc b/api/array_view_unittest.cc
index 62b51c0..18d0e6c 100644
--- a/api/array_view_unittest.cc
+++ b/api/array_view_unittest.cc
@@ -450,4 +450,23 @@
EXPECT_THAT(av.subview(1, 3), ElementsAre(2, 3));
}
+TEST(ArrayViewTest, TestReinterpretCastFixedSize) {
+ uint8_t bytes[] = {1, 2, 3};
+ ArrayView<uint8_t, 3> uint8_av(bytes);
+ ArrayView<int8_t, 3> int8_av = reinterpret_array_view<int8_t>(uint8_av);
+ EXPECT_EQ(int8_av.size(), uint8_av.size());
+ EXPECT_EQ(int8_av[0], 1);
+ EXPECT_EQ(int8_av[1], 2);
+ EXPECT_EQ(int8_av[2], 3);
+}
+
+TEST(ArrayViewTest, TestReinterpretCastVariableSize) {
+ std::vector<int8_t> v = {1, 2, 3};
+ ArrayView<int8_t> int8_av(v);
+ ArrayView<uint8_t> uint8_av = reinterpret_array_view<uint8_t>(int8_av);
+ EXPECT_EQ(int8_av.size(), uint8_av.size());
+ EXPECT_EQ(uint8_av[0], 1);
+ EXPECT_EQ(uint8_av[1], 2);
+ EXPECT_EQ(uint8_av[2], 3);
+}
} // namespace rtc