Add begin/end iterators to rust::Vec

This commit is contained in:
David Tolnay 2020-04-24 17:07:41 -07:00
parent 503d01902a
commit c87c215f56
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
3 changed files with 41 additions and 4 deletions

View File

@ -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(_) => {

View File

@ -205,12 +205,50 @@ private:
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;

View File

@ -163,17 +163,15 @@ void c_take_unique_ptr_vector_shared(std::unique_ptr<std::vector<Shared>> v) {
}
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) {