CUBRID Engine  latest
sizeheap.h
Go to the documentation of this file.
1 /* -*- C++ -*- */
2 
3 /*
4 
5  Heap Layers: An Extensible Memory Allocation Infrastructure
6 
7  Copyright (C) 2000-2020 by Emery Berger
8  http://www.emeryberger.com
9  emery@cs.umass.edu
10 
11  Heap Layers is distributed under the terms of the Apache 2.0 license.
12 
13  You may obtain a copy of the License at
14  http://www.apache.org/licenses/LICENSE-2.0
15 
16 */
17 
18 #ifndef HL_SIZEHEAP_H
19 #define HL_SIZEHEAP_H
20 
26 #include <assert.h>
27 
28 #include "wrappers/mallocinfo.h"
30 #include "utility/gcd.h"
31 
32 namespace HL {
33 
39  template <class SuperHeap>
40  class SizeHeap : public SuperHeap {
41 
42  private:
43  struct freeObject {
44  size_t _sz;
45  size_t _magic;
46  // char _buf[HL::MallocInfo::Alignment];
47  };
48 
49  enum { MAGIC_NUMBER = 0xCAFEBABE };
50 
51  public:
52 
53  enum { Alignment = gcd<(int) SuperHeap::Alignment,
54  (int) sizeof(freeObject)>::value };
55 
56  virtual ~SizeHeap (void) {}
57 
58  inline void * malloc (size_t sz) {
59  freeObject * p = (freeObject *) SuperHeap::malloc (sz + sizeof(freeObject));
60  p->_sz = sz;
61  p->_magic = MAGIC_NUMBER;
62  return (void *) (p + 1);
63  }
64 
65  inline void free (void * ptr) {
66  if (getHeader(ptr)->_magic == MAGIC_NUMBER) {
67  // Probably one of our objects.
68  SuperHeap::free (getHeader(ptr));
69  }
70  }
71 
72  inline static size_t getSize (const void * ptr) {
73  if (getHeader(ptr)->_magic == MAGIC_NUMBER) {
74  size_t size = getHeader(ptr)->_sz;
75  return size;
76  } else {
77  // Probably not one of our objects.
78  return 0;
79  }
80  }
81 
82  private:
83 
84  inline static void setSize (void * ptr, size_t sz) {
86  getHeader(ptr)->_sz = sz;
87  }
88 
89  inline static freeObject * getHeader (const void * ptr) {
90  return ((freeObject *) ptr - 1);
91  }
92 
93  };
94 
95 }
96 
97 #endif
Definition: gcd.h:9
static void setSize(void *ptr, size_t sz)
Definition: sizeheap.h:84
Definition: heaplayers.h:34
#define assert(x)
virtual ~SizeHeap(void)
Definition: sizeheap.h:56
void free(void *ptr)
Definition: sizeheap.h:65
static freeObject * getHeader(const void *ptr)
Definition: sizeheap.h:89
Allocates extra room for the size of an object.
Definition: sizeheap.h:40
const char ** p
Definition: dynamic_load.c:945
void * malloc(size_t sz)
Definition: sizeheap.h:58
static size_t getSize(const void *ptr)
Definition: sizeheap.h:72