diff --git a/gen/write.rs b/gen/write.rs index d963bb9c..f67057bc 100644 --- a/gen/write.rs +++ b/gen/write.rs @@ -147,6 +147,7 @@ fn write_include_cxxbridge(out: &mut OutFile, apis: &[Api], types: &Types) { } Type::RustVec(_) => { out.include.array = true; + out.include.type_traits = true; needs_rust_vec = true; } Type::Str(_) => { diff --git a/include/cxx.h b/include/cxx.h index f40614b2..e16d9e0b 100644 --- a/include/cxx.h +++ b/include/cxx.h @@ -205,12 +205,50 @@ private: template class Vec final { public: + using value_type = T; + ~Vec() noexcept { this->drop(); } size_t size() const noexcept; bool empty() const noexcept { return size() == 0; } const T *data() const noexcept; + class const_iterator { + public: + using value_type = typename std::add_const::type; + using reference = typename std::add_lvalue_reference< + typename std::add_const::type>::type; + + const T &operator*() const { return *static_cast(this->pos); } + const_iterator &operator++() { + this->pos = static_cast(this->pos) + this->stride; + return *this; + } + bool operator==(const const_iterator &other) const { + return this->pos == other.pos; + } + bool operator!=(const const_iterator &other) const { + return this->pos != other.pos; + } + + private: + friend class Vec; + const void *pos; + size_t stride; + }; + + const_iterator begin() const noexcept { + const_iterator it; + it.pos = this->data(); + it.stride = this->stride(); + return it; + } + const_iterator end() const noexcept { + const_iterator it = this->begin(); + it.pos = static_cast(it.pos) + it.stride * this->size(); + return it; + } + private: static size_t stride() noexcept; void drop() noexcept; diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc index 46f04bea..502be05c 100644 --- a/tests/ffi/tests.cc +++ b/tests/ffi/tests.cc @@ -163,17 +163,15 @@ void c_take_unique_ptr_vector_shared(std::unique_ptr> v) { } void c_take_vec_u8(const rust::Vec &v) { - auto cv = static_cast>(v); - uint8_t sum = std::accumulate(cv.begin(), cv.end(), 0); + uint8_t sum = std::accumulate(v.begin(), v.end(), 0); if (sum == 200) { cxx_test_suite_set_correct(); } } void c_take_vec_shared(const rust::Vec &v) { - auto cv = static_cast>(v); uint32_t sum = 0; - for (auto i : cv) { + for (auto i : v) { sum += i.z; } if (sum == 2021) {