diff options
author | ncteisen <ncteisen@gmail.com> | 2018-07-13 10:35:46 -0700 |
---|---|---|
committer | ncteisen <ncteisen@gmail.com> | 2018-07-13 10:43:35 -0700 |
commit | 2d2854a1ce398c2a5c4693c68fe689055dda0cdd (patch) | |
tree | 25363b48159cab2843cbac32faae7216dc9d4a94 /src | |
parent | 82e9cb66ffb3fa3b7dc151efa056ded997186a59 (diff) |
Add copy and move ctor to InlinedVector
Diffstat (limited to 'src')
-rw-r--r-- | src/core/lib/gprpp/inlined_vector.h | 73 |
1 files changed, 70 insertions, 3 deletions
diff --git a/src/core/lib/gprpp/inlined_vector.h b/src/core/lib/gprpp/inlined_vector.h index 0d2586e507..276d5a078d 100644 --- a/src/core/lib/gprpp/inlined_vector.h +++ b/src/core/lib/gprpp/inlined_vector.h @@ -50,9 +50,76 @@ class InlinedVector { InlinedVector() { init_data(); } ~InlinedVector() { destroy_elements(); } - // For now, we do not support copying. - InlinedVector(const InlinedVector&) = delete; - InlinedVector& operator=(const InlinedVector&) = delete; + // copy constructors + InlinedVector(const InlinedVector& v) { + init_data(); + // if v is allocated, then we copy it's buffer + if (v.dynamic_ != nullptr) { + reserve(v.capacity_); + memcpy(dynamic_, v.dynamic_, v.capacity_ * sizeof(T)); + } else { + memcpy(inline_, v.inline_, v.capacity_ * sizeof(T)); + dynamic_ = nullptr; + } + // copy over metadata + size_ = v.size_; + capacity_ = v.capacity_; + } + InlinedVector& operator=(const InlinedVector& v) { + if (this != &v) { + clear(); + // if v is allocated, then we copy it's buffer + if (v.dynamic_ != nullptr) { + reserve(v.capacity_); + memcpy(dynamic_, v.dynamic_, v.capacity_ * sizeof(T)); + } else { + memcpy(inline_, v.inline_, v.capacity_ * sizeof(T)); + dynamic_ = nullptr; + } + // copy over metadata + size_ = v.size_; + capacity_ = v.capacity_; + } + return *this; + } + + // move constructors + InlinedVector(InlinedVector&& v) { + // if v is allocated, then we steal it's buffer + if (v.dynamic_ != nullptr) { + dynamic_ = v.dynamic_; + } else { + memcpy(inline_, v.inline_, v.capacity_ * sizeof(T)); + dynamic_ = nullptr; + } + // copy over metadata + size_ = v.size_; + capacity_ = v.capacity_; + // null out the original + v.dynamic_ = nullptr; + v.size_ = 0; + v.capacity_ = 0; + } + InlinedVector& operator=(InlinedVector&& v) { + if (this != &v) { + clear(); + // if v is allocated, then we steal it's buffer + if (v.dynamic_ != nullptr) { + dynamic_ = v.dynamic_; + } else { + memcpy(inline_, v.inline_, v.capacity_ * sizeof(T)); + dynamic_ = nullptr; + } + // copy over metadata + size_ = v.size_; + capacity_ = v.capacity_; + // null out the original + v.dynamic_ = nullptr; + v.size_ = 0; + v.capacity_ = 0; + } + return *this; + } T* data() { return dynamic_ != nullptr ? dynamic_ : reinterpret_cast<T*>(inline_); |