From 7cfdd2f541fc601193d641c1d8c70853aaa047d2 Mon Sep 17 00:00:00 2001 From: Jorge Gorbe Date: Fri, 11 Apr 2014 14:08:05 +0200 Subject: [PATCH] wip. everything is broken right now. added fixed capacity vector class for persistent vector nodes. --- fixed_capacity_vector.h | 71 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 fixed_capacity_vector.h diff --git a/fixed_capacity_vector.h b/fixed_capacity_vector.h new file mode 100644 index 0000000..57812e1 --- /dev/null +++ b/fixed_capacity_vector.h @@ -0,0 +1,71 @@ +#ifndef FIXED_CAPACITY_VECTOR_H +#define FIXED_CAPACITY_VECTOR_H + + +namespace persistent { namespace internal { + + // A vector-like which only allows inserting up to Capacity elements. + // As the capacity is fixed, the storage space is located right + // inside the object, avoiding extra indirections + template + class fixed_capacity_vector final { + public: + fixed_capacity_vector(): size(0) {} + + ~fixed_capacity_vector() { + // destroy valid elements + T* p = reinterpret_cast(storage); + for (size_t i=0; i < size; ++i) { + p->~T(); + ++p; + } + } + + size_t size() { return size; } + + void push_back(const T& value) { + T* v = reinterpret_cast(storage); + new (&v[size]) T(value); + ++size; + } + + void push_back(T&& value) { + T* v = reinterpret_cast(storage); + new (&v[size]) T(value); + ++size; + } + + template + void emplace_back(Args&&... args) { + T* v = reinterpret_cast(storage); + new (&v[size]) T(args...); + ++size; + } + + T& operator[](size_t pos) { + T* v = reinterpret_cast(storage); + return v[pos]; + } + + const T& operator[](size_t pos) const { + const T* v = reinterpret_cast(storage); + return v[pos]; + } + + private: + // Declare the storage space as a char array, because if it was an + // array of Ts, it would have to construct the whole array of T + // objects on creation. + char storage[Capacity * sizeof(T)]; + + // number of elements that actually contain objects of type T + size_t size; + } + +}} + + + + +#endif + -- 2.34.1