alloc_func.hpp

Go to the documentation of this file.
00001 /* $Id: alloc_func.hpp 21886 2011-01-22 09:53:15Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #ifndef ALLOC_FUNC_HPP
00013 #define ALLOC_FUNC_HPP
00014 
00015 /*
00016  * Functions to exit badly with an error message.
00017  * It has to be linked so the error messages are not
00018  * duplicated in each object file making the final
00019  * binary needlessly large.
00020  */
00021 
00022 void NORETURN MallocError(size_t size);
00023 void NORETURN ReallocError(size_t size);
00024 
00035 template <typename T>
00036 static FORCEINLINE T *MallocT(size_t num_elements)
00037 {
00038   /*
00039    * MorphOS cannot handle 0 elements allocations, or rather that always
00040    * returns NULL. So we do that for *all* allocations, thus causing it
00041    * to behave the same on all OSes.
00042    */
00043   if (num_elements == 0) return NULL;
00044 
00045   T *t_ptr = (T*)malloc(num_elements * sizeof(T));
00046   if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
00047   return t_ptr;
00048 }
00049 
00060 template <typename T>
00061 static FORCEINLINE T *CallocT(size_t num_elements)
00062 {
00063   /*
00064    * MorphOS cannot handle 0 elements allocations, or rather that always
00065    * returns NULL. So we do that for *all* allocations, thus causing it
00066    * to behave the same on all OSes.
00067    */
00068   if (num_elements == 0) return NULL;
00069 
00070   T *t_ptr = (T*)calloc(num_elements, sizeof(T));
00071   if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
00072   return t_ptr;
00073 }
00074 
00086 template <typename T>
00087 static FORCEINLINE T *ReallocT(T *t_ptr, size_t num_elements)
00088 {
00089   /*
00090    * MorphOS cannot handle 0 elements allocations, or rather that always
00091    * returns NULL. So we do that for *all* allocations, thus causing it
00092    * to behave the same on all OSes.
00093    */
00094   if (num_elements == 0) {
00095     free(t_ptr);
00096     return NULL;
00097   }
00098 
00099   t_ptr = (T*)realloc(t_ptr, num_elements * sizeof(T));
00100   if (t_ptr == NULL) ReallocError(num_elements * sizeof(T));
00101   return t_ptr;
00102 }
00103 
00105 #define AllocaM(T, num_elements) ((T*)alloca((num_elements) * sizeof(T)))
00106 
00107 #endif /* ALLOC_FUNC_HPP */

Generated on Sun May 15 19:20:07 2011 for OpenTTD by  doxygen 1.6.1