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_