# alloc_func.hpp

Go to the documentation of this file.

    00001 /* $Id$ */
    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
    00021 void NORETURN MallocError(size_t size);
    00022 void NORETURN ReallocError(size_t size);
    00023
    00034 template <typename T>
    00035 static FORCEINLINE T *MallocT(size_t num_elements)
    00036 {
    00037   /*
    00038    * MorphOS cannot handle 0 elements allocations, or rather that always
    00039    * returns NULL. So we do that for *all* allocations, thus causing it
    00040    * to behave the same on all OSes.
    00041    */
    00042   if (num_elements == 0) return NULL;
    00043
    00044   T *t_ptr = (T*)malloc(num_elements * sizeof(T));
    00045   if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
    00046   return t_ptr;
    00047 }
    00048
    00059 template <typename T>
    00060 static FORCEINLINE T *CallocT(size_t num_elements)
    00061 {
    00062   /*
    00063    * MorphOS cannot handle 0 elements allocations, or rather that always
    00064    * returns NULL. So we do that for *all* allocations, thus causing it
    00065    * to behave the same on all OSes.
    00066    */
    00067   if (num_elements == 0) return NULL;
    00068
    00069   T *t_ptr = (T*)calloc(num_elements, sizeof(T));
    00070   if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
    00071   return t_ptr;
    00072 }
    00073
    00085 template <typename T>
    00086 static FORCEINLINE T *ReallocT(T *t_ptr, size_t num_elements)
    00087 {
    00088   /*
    00089    * MorphOS cannot handle 0 elements allocations, or rather that always
    00090    * returns NULL. So we do that for *all* allocations, thus causing it
    00091    * to behave the same on all OSes.
    00092    */
    00093   if (num_elements == 0) {
    00094     free(t_ptr);
    00095     return NULL;
    00096   }
    00097
    00098   t_ptr = (T*)realloc(t_ptr, num_elements * sizeof(T));
    00099   if (t_ptr == NULL) ReallocError(num_elements * sizeof(T));
    00100   return t_ptr;
    00101 }
    00102
    00104 #define AllocaM(T, num_elements) ((T*)alloca((num_elements) * sizeof(T)))
    00105
    00106 #endif /* ALLOC_FUNC_HPP */