alloc_func.hpp

Go to the documentation of this file.
00001 /* $Id: alloc_func.hpp 12115 2008-02-11 20:23:38Z smatz $ */
00002 
00005 #ifndef ALLOC_FUNC_HPP
00006 #define ALLOC_FUNC_HPP
00007 
00014 void MallocError(size_t size);
00015 void ReallocError(size_t size);
00016 
00027 template <typename T> FORCEINLINE T* MallocT(size_t num_elements)
00028 {
00029   /*
00030    * MorphOS cannot handle 0 elements allocations, or rather that always
00031    * returns NULL. So we do that for *all* allocations, thus causing it
00032    * to behave the same on all OSes.
00033    */
00034   if (num_elements == 0) return NULL;
00035 
00036   T *t_ptr = (T*)malloc(num_elements * sizeof(T));
00037   if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
00038   return t_ptr;
00039 }
00040 
00051 template <typename T> FORCEINLINE T* CallocT(size_t num_elements)
00052 {
00053   /*
00054    * MorphOS cannot handle 0 elements allocations, or rather that always
00055    * returns NULL. So we do that for *all* allocations, thus causing it
00056    * to behave the same on all OSes.
00057    */
00058   if (num_elements == 0) return NULL;
00059 
00060   T *t_ptr = (T*)calloc(num_elements, sizeof(T));
00061   if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
00062   return t_ptr;
00063 }
00064 
00076 template <typename T> FORCEINLINE T* ReallocT(T *t_ptr, size_t num_elements)
00077 {
00078   /*
00079    * MorphOS cannot handle 0 elements allocations, or rather that always
00080    * returns NULL. So we do that for *all* allocations, thus causing it
00081    * to behave the same on all OSes.
00082    */
00083   if (num_elements == 0) {
00084     free(t_ptr);
00085     return NULL;
00086   }
00087 
00088   t_ptr = (T*)realloc(t_ptr, num_elements * sizeof(T));
00089   if (t_ptr == NULL) ReallocError(num_elements * sizeof(T));
00090   return t_ptr;
00091 }
00092 
00102 template <typename T, size_t length>
00103 struct SmallStackSafeStackAlloc {
00104 #if !defined(__NDS__)
00105 
00106   T data[length];
00107 #else
00108 
00109   T *data;
00110 
00112   SmallStackSafeStackAlloc() : data(MallocT<T>(length)) {}
00114   ~SmallStackSafeStackAlloc() { free(data); }
00115 #endif
00116 
00121   operator T* () { return data; }
00122 };
00123 
00124 #endif /* ALLOC_FUNC_HPP */

Generated on Mon Sep 22 20:34:15 2008 for openttd by  doxygen 1.5.6