Introduce ArrayView::subview function
to return portion of the original view
BUG=None
Review-Url: https://codereview.webrtc.org/2502383004
Cr-Commit-Position: refs/heads/master@{#15149}
diff --git a/webrtc/base/array_view.h b/webrtc/base/array_view.h
index 5c1ffe2..aa73ef7 100644
--- a/webrtc/base/array_view.h
+++ b/webrtc/base/array_view.h
@@ -120,6 +120,13 @@
const T* cbegin() const { return data_; }
const T* cend() const { return data_ + size_; }
+ ArrayView subview(size_t offset, size_t size) const {
+ if (offset >= size_)
+ return ArrayView();
+ return ArrayView(data_ + offset, std::min(size, size_ - offset));
+ }
+ ArrayView subview(size_t offset) const { return subview(offset, size_); }
+
// Comparing two ArrayViews compares their (pointer,size) pairs; it does
// *not* dereference the pointers.
friend bool operator==(const ArrayView& a, const ArrayView& b) {
diff --git a/webrtc/base/array_view_unittest.cc b/webrtc/base/array_view_unittest.cc
index 91facb0..f7fe9fa 100644
--- a/webrtc/base/array_view_unittest.cc
+++ b/webrtc/base/array_view_unittest.cc
@@ -16,11 +16,15 @@
#include "webrtc/base/buffer.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/gunit.h"
+#include "webrtc/test/gmock.h"
namespace rtc {
namespace {
+using ::testing::ElementsAre;
+using ::testing::IsEmpty;
+
template <typename T>
void Call(ArrayView<T>) {}
@@ -232,4 +236,21 @@
EXPECT_NE(ArrayView<int>(a), ArrayView<int>(a, 2));
}
+TEST(ArrayViewTest, TestSubView) {
+ int a[] = {1, 2, 3};
+ ArrayView<int> av(a);
+
+ EXPECT_EQ(av.subview(0), av);
+
+ EXPECT_THAT(av.subview(1), ElementsAre(2, 3));
+ EXPECT_THAT(av.subview(2), ElementsAre(3));
+ EXPECT_THAT(av.subview(3), IsEmpty());
+ EXPECT_THAT(av.subview(4), IsEmpty());
+
+ EXPECT_THAT(av.subview(1, 0), IsEmpty());
+ EXPECT_THAT(av.subview(1, 1), ElementsAre(2));
+ EXPECT_THAT(av.subview(1, 2), ElementsAre(2, 3));
+ EXPECT_THAT(av.subview(1, 3), ElementsAre(2, 3));
+}
+
} // namespace rtc