Add range constructor to hidl_vec.
Bug: b/36864090
Test: Unit test
Test: a device boots
Test: marlin boots and completes unit test
Change-Id: I7d37f75ec6c8ba0252c3c60afd515eff87dfc4dd
diff --git a/base/include/hidl/HidlSupport.h b/base/include/hidl/HidlSupport.h
index d7c3b83..3f45afd 100644
--- a/base/include/hidl/HidlSupport.h
+++ b/base/include/hidl/HidlSupport.h
@@ -316,6 +316,27 @@
*this = other;
}
+ template <typename InputIterator,
+ typename = typename std::enable_if<std::is_convertible<
+ typename std::iterator_traits<InputIterator>::iterator_category,
+ std::input_iterator_tag>::value>::type>
+ hidl_vec(InputIterator first, InputIterator last) : mOwnsBuffer(true) {
+ auto size = std::distance(first, last);
+ if (size > static_cast<int64_t>(UINT32_MAX)) {
+ details::logAlwaysFatal("hidl_vec can't hold more than 2^32 elements.");
+ }
+ if (size < 0) {
+ details::logAlwaysFatal("size can't be negative.");
+ }
+ mSize = static_cast<uint32_t>(size);
+ mBuffer = new T[mSize];
+
+ size_t idx = 0;
+ for (; first != last; ++first) {
+ mBuffer[idx++] = static_cast<T>(*first);
+ }
+ }
+
~hidl_vec() {
if (mOwnsBuffer) {
delete[] mBuffer;
diff --git a/test_main.cpp b/test_main.cpp
index bce9294..1f2f845 100644
--- a/test_main.cpp
+++ b/test_main.cpp
@@ -262,6 +262,30 @@
EXPECT_TRUE(hv1 != hv3);
}
+TEST_F(LibHidlTest, VecRangeCtorTest) {
+ struct ConvertibleType {
+ int val;
+
+ explicit ConvertibleType(int val) : val(val) {}
+ explicit operator int() const { return val; }
+ bool operator==(const int& other) const { return val == other; }
+ };
+
+ std::vector<ConvertibleType> input{
+ ConvertibleType(1), ConvertibleType(2), ConvertibleType(3),
+ };
+
+ android::hardware::hidl_vec<int> hv(input.begin(), input.end());
+
+ EXPECT_EQ(input.size(), hv.size());
+ int sum = 0;
+ for (unsigned i = 0; i < input.size(); i++) {
+ EXPECT_EQ(input[i], hv[i]);
+ sum += hv[i];
+ }
+ EXPECT_EQ(sum, 1 + 2 + 3);
+}
+
TEST_F(LibHidlTest, ArrayTest) {
using android::hardware::hidl_array;
int32_t array[] = {5, 6, 7};