wip. everything is broken right now. added fixed capacity vector class for persistent...
authorJorge Gorbe <jgorbe@stcsl.es>
Fri, 11 Apr 2014 12:08:05 +0000 (14:08 +0200)
committerJorge Gorbe <jgorbe@stcsl.es>
Fri, 11 Apr 2014 12:08:05 +0000 (14:08 +0200)
fixed_capacity_vector.h [new file with mode: 0644]

diff --git a/fixed_capacity_vector.h b/fixed_capacity_vector.h
new file mode 100644 (file)
index 0000000..57812e1
--- /dev/null
@@ -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<typename T, int Capacity>
+    class fixed_capacity_vector final {
+        public:
+            fixed_capacity_vector(): size(0) {}
+
+            ~fixed_capacity_vector() {
+                // destroy valid elements
+                T* p = reinterpret_cast<T*>(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<T*>(storage);
+                new (&v[size]) T(value);
+                ++size;
+            }
+
+            void push_back(T&& value) {
+                T* v = reinterpret_cast<T*>(storage);
+                new (&v[size]) T(value);
+                ++size;
+            }
+
+            template<class Args...>
+            void emplace_back(Args&&... args) {
+                T* v = reinterpret_cast<T*>(storage);
+                new (&v[size]) T(args...);
+                ++size;
+            }
+
+            T& operator[](size_t pos) {
+                T* v = reinterpret_cast<T*>(storage);
+                return v[pos];
+            }
+
+            const T& operator[](size_t pos) const {
+                const T* v = reinterpret_cast<const T*>(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
+