src/core/alloc_func.hpp
changeset 10164 3ff9e65f3d49
parent 9294 5cd9e0da420f
child 10246 707c09e2e42b
equal deleted inserted replaced
10163:d18ad4693602 10164:3ff9e65f3d49
    88 	t_ptr = (T*)realloc(t_ptr, num_elements * sizeof(T));
    88 	t_ptr = (T*)realloc(t_ptr, num_elements * sizeof(T));
    89 	if (t_ptr == NULL) ReallocError(num_elements * sizeof(T));
    89 	if (t_ptr == NULL) ReallocError(num_elements * sizeof(T));
    90 	return t_ptr;
    90 	return t_ptr;
    91 }
    91 }
    92 
    92 
    93 /**
       
    94  * A small 'wrapper' for allocations that can be done on most OSes on the
       
    95  * stack, but are just too large to fit in the stack on devices with a small
       
    96  * stack such as the NDS.
       
    97  * So when it is possible a stack allocation is made, otherwise a heap
       
    98  * allocation is made and this is freed once the struct goes out of scope.
       
    99  * @param T      the type to make the allocation for
       
   100  * @param length the amount of items to allocate
       
   101  */
       
   102 template <typename T, size_t length>
       
   103 struct SmallStackSafeStackAlloc {
       
   104 #if !defined(__NDS__)
       
   105 	/** Storing the data on the stack */
       
   106 	T data[length];
       
   107 #else
       
   108 	/** Storing it on the heap */
       
   109 	T *data;
       
   110 	/** The length (in elements) of data in this allocator. */
       
   111 	size_t len;
       
   112 
       
   113 	/** Allocating the memory */
       
   114 	SmallStackSafeStackAlloc() : data(MallocT<T>(length)), len(length) {}
       
   115 	/** And freeing when it goes out of scope */
       
   116 	~SmallStackSafeStackAlloc() { free(data); }
       
   117 #endif
       
   118 
       
   119 	/**
       
   120 	 * Gets a pointer to the data stored in this wrapper.
       
   121 	 * @return the pointer.
       
   122 	 */
       
   123 	inline operator T* () { return data; }
       
   124 
       
   125 	/**
       
   126 	 * Gets a pointer to the data stored in this wrapper.
       
   127 	 * @return the pointer.
       
   128 	 */
       
   129 	inline T* operator -> () { return data; }
       
   130 
       
   131 	/**
       
   132 	 * Gets a pointer to the last data element stored in this wrapper.
       
   133 	 * @note needed because endof does not work properly for pointers.
       
   134 	 * @return the 'endof' pointer.
       
   135 	 */
       
   136 	inline T* EndOf() {
       
   137 #if !defined(__NDS__)
       
   138 		return endof(data);
       
   139 #else
       
   140 		return &data[len];
       
   141 #endif
       
   142 	}
       
   143 };
       
   144 
       
   145 #endif /* ALLOC_FUNC_HPP */
    93 #endif /* ALLOC_FUNC_HPP */