Debian Codegraph @

cextern/healpix/src/cxx/cxxsupport/alloc_utils.h

raw
1 /*
2 * This file is part of libcxxsupport.
3 *
4 * libcxxsupport is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * libcxxsupport is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with libcxxsupport; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19 /*
20 * libcxxsupport is being developed at the Max-Planck-Institut fuer Astrophysik
21 * and financially supported by the Deutsches Zentrum fuer Luft- und Raumfahrt
22 * (DLR).
23 */
24
25 /*! \file alloc_utils.h
26 * Classes providing raw memory allocation and deallocation support.
27 *
28 * Copyright (C) 2011-2015 Max-Planck-Society
29 * \author Martin Reinecke
30 */
31
32 #ifndef PLANCK_ALLOC_UTILS_H
33 #define PLANCK_ALLOC_UTILS_H
34
35 #include <cstdlib>
36 #include <cstddef>
37 #include "datatypes.h"
38
39 template <typename T> class normalAlloc__
40 {
41 public:
42 static T *alloc(tsize sz) { return (sz>0) ? new T[sz] : 0; }
43 static void dealloc (T *ptr) { delete[] ptr; }
44 };
45
46 template <typename T, int align> class alignAlloc__
47 {
48 private:
49 //#if (__cplusplus>=201103L)
50 // enum { max_nat_align = alignof(std::max_align_t) };
51 //#else
52 enum { max_nat_align = sizeof(void *) };
53 //#endif
54
55 public:
56 static T *alloc(tsize sz)
57 {
58 using namespace std;
59 if (sz==0) return 0;
60 planck_assert((align&(align-1))==0,"alignment must be power of 2");
61 void *res;
62 if (align<=max_nat_align)
63 {
64 res=malloc(sz*sizeof(T));
65 planck_assert(res!=0,"error in malloc()");
66 }
67 else
68 {
69 tsize overhead=align-1+sizeof(void*);
70 void *ptr=malloc(sz*sizeof(T)+overhead);
71 planck_assert(ptr!=0,"error in malloc()");
72 tsize sptr=reinterpret_cast<tsize>(ptr);
73 sptr = (sptr+overhead) & ~(align-1);
74 void **ptr2 = reinterpret_cast<void **>(sptr);
75 ptr2[-1]=ptr;
76 res=ptr2;
77 }
78 return static_cast<T *>(res);
79 }
80 static void dealloc(T *ptr)
81 {
82 using namespace std;
83 if (align<=max_nat_align)
84 free(ptr);
85 else
86 {
87 if (ptr==0) return;
88 void **ptr2 = reinterpret_cast<void **>(ptr);
89 free (ptr2[-1]);
90 }
91 }
92 };
93
94 #endif