Add begin/end iterators to rust::Vec
diff --git a/gen/write.rs b/gen/write.rs
index d963bb9..f67057b 100644
--- a/gen/write.rs
+++ b/gen/write.rs
@@ -147,6 +147,7 @@
}
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 f40614b..e16d9e0 100644
--- a/include/cxx.h
+++ b/include/cxx.h
@@ -205,12 +205,50 @@
template <typename T>
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<T>::type;
+ using reference = typename std::add_lvalue_reference<
+ typename std::add_const<T>::type>::type;
+
+ const T &operator*() const { return *static_cast<const T *>(this->pos); }
+ const_iterator &operator++() {
+ this->pos = static_cast<const uint8_t *>(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<const uint8_t *>(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 46f04be..502be05 100644
--- a/tests/ffi/tests.cc
+++ b/tests/ffi/tests.cc
@@ -163,17 +163,15 @@
}
void c_take_vec_u8(const rust::Vec<uint8_t> &v) {
- auto cv = static_cast<std::vector<uint8_t>>(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<Shared> &v) {
- auto cv = static_cast<std::vector<Shared>>(v);
uint32_t sum = 0;
- for (auto i : cv) {
+ for (auto i : v) {
sum += i.z;
}
if (sum == 2021) {