Browse Source

stack object to wrapper any class

Kajetan Johannes Hammerle 3 years ago
parent
commit
3b6c3c6bc4
3 changed files with 50 additions and 0 deletions
  1. 2 0
      Main.cpp
  2. 39 0
      memory/StackAllocator.h
  3. 9 0
      tests/StackAllocatorTests.cpp

+ 2 - 0
Main.cpp

@@ -25,6 +25,8 @@
 #include "wrapper/Framebuffer.h"
 #include "rendering/FileTexture.h"
 
+#include "memory/StackAllocator.h"
+
 int main(int argAmount, char** args) {
     if(argAmount < 2) {
         std::cout << "missing path to images\n";

+ 39 - 0
memory/StackAllocator.h

@@ -2,6 +2,7 @@
 #define STACKALLOCATOR_H
 
 #include <new>
+#include <type_traits>
 
 namespace StackAllocator {
 
@@ -65,6 +66,44 @@ namespace StackAllocator {
             return static_cast<T*> (StackAllocator::get(dataPointer));
         }
     };
+
+    template<typename T>
+    class Object final {
+        int length;
+        Pointer dataPointer;
+
+    public:
+
+        Object() : length(1), dataPointer(StackAllocator::allocate(sizeof (T), length)) {
+            if(!hasError()) {
+                new (StackAllocator::get(dataPointer)) T;
+            }
+        }
+
+        ~Object() {
+            if(!hasError()) {
+                (*this)->~T();
+            }
+            StackAllocator::free(dataPointer);
+        }
+
+        Object(const Object&) = delete;
+        Object& operator=(const Object&) = delete;
+        Object(Object&&) = delete;
+        Object& operator=(Object&&) = delete;
+
+        bool hasError() {
+            return length != 1;
+        }
+
+        T* operator ->() {
+            return static_cast<T*> (StackAllocator::get(dataPointer));
+        }
+        
+        operator T&() {
+            return *static_cast<T*> (StackAllocator::get(dataPointer));
+        }
+    };
 }
 
 #endif

+ 9 - 0
tests/StackAllocatorTests.cpp

@@ -1,5 +1,6 @@
 #include "tests/StackAllocatorTests.h"
 #include "tests/Test.h"
+#include "utils/Array.h"
 #include "memory/StackAllocator.h"
 
 static void testBasicAllocation(Test& test) {
@@ -130,6 +131,13 @@ static void testArrayNotGrow(Test& test) {
     test.checkEqual(4, a.grow(4), "last element on stack can grow 3");
 }
 
+static void testObject(Test& test) {
+    StackAllocator::Object<Array<int, 1024 * 1024 * 4 >> a;
+    test.checkEqual(false, a.hasError(), "object fits in stack");
+    StackAllocator::Object<Array<int, 1024 * 1024 * 100 >> b;
+    test.checkEqual(true, b.hasError(), "object does not fit in stack");
+}
+
 void StackAllocatorTests::test() {
     Test test("StackAllocator");
     testBasicAllocation(test);
@@ -141,5 +149,6 @@ void StackAllocatorTests::test() {
     testArray(test);
     testArrayGrow(test);
     testArrayNotGrow(test);
+    testObject(test);
     test.finalize();
 }