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}
This commit is contained in:
Amit Hilbuch
2019-03-22 10:16:07 -07:00
committed by Commit Bot
parent fe0b499634
commit e155dd0fdb
2 changed files with 36 additions and 0 deletions

View File

@ -285,6 +285,23 @@ inline ArrayView<T> MakeArrayView(T* data, size_t size) {
return ArrayView<T>(data, size); 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 } // namespace rtc
#endif // API_ARRAY_VIEW_H_ #endif // API_ARRAY_VIEW_H_

View File

@ -450,4 +450,23 @@ TEST(ArrayViewTest, TestSubViewFixed) {
EXPECT_THAT(av.subview(1, 3), ElementsAre(2, 3)); 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 } // namespace rtc