Free Electron
PoolAllocator.h
Go to the documentation of this file.
1 /* Copyright (C) 2003-2021 Free Electron Organization
2  Any use of this software requires a license. If a valid license
3  was not distributed with this file, visit freeelectron.org. */
4 
5 /** @file */
6 
7 #ifndef __core_PoolAllocator_h__
8 #define __core_PoolAllocator_h__
9 
10 namespace fe
11 {
12 
13 struct FE_PA_FREE
14 {
15  void *m_next;
16 };
17 
18 struct FE_PA_USED
19 {
20  size_t m_s;
21 };
22 
23 #define HDR_TO_BLK(x) ((void *)((char *)x + sizeof(size_t)))
24 #define BLK_TO_HDR(x) ((void *)((char *)x - sizeof(size_t)))
25 
26 class FE_DL_EXPORT PoolAllocator : public Allocator
27 {
28  public:
29  PoolAllocator(void);
30  PoolAllocator(FE_UWORD stride, FE_UWORD slots);
31 virtual ~PoolAllocator(void);
32 virtual void *allocate(FE_UWORD byteCount);
33 virtual void deallocate(void* pMemory);
34  private:
35  FE_UWORD m_max;
36  void **m_nfList;
37  FE_UWORD m_stride;
38 };
39 
40 inline void *PoolAllocator::allocate(FE_UWORD byteCount)
41 {
42  if(byteCount == 0) { return NULL; }
43  size_t s = (byteCount-1)/m_stride;
44  if(s < m_max && m_nfList[s])
45  {
46  void *pBase = m_nfList[s];
47  m_nfList[s] = ((FE_PA_FREE *)(pBase))->m_next;
48  ((FE_PA_USED *)(pBase))->m_s = s;
49  return (void *)(HDR_TO_BLK(pBase));
50  }
51  else
52  {
53  void *pBase = fe::allocate(((s+1)*m_stride)+sizeof(FE_UWORD));
54  ((FE_PA_USED *)(pBase))->m_s = s;
55  return (void *)(HDR_TO_BLK(pBase));
56  }
57 }
58 
59 inline void PoolAllocator::deallocate(void* pMemory)
60 {
61  FE_UWORD s = ((FE_PA_USED *)BLK_TO_HDR(pMemory))->m_s;
62  if(s < m_max)
63  {
64  void *pBase = BLK_TO_HDR(pMemory);
65  ((FE_PA_FREE *)(pBase))->m_next = m_nfList[s];
66  m_nfList[s] = pBase;
67  }
68  else
69  {
70  fe::deallocate(BLK_TO_HDR(pMemory));
71  }
72 }
73 
74 
75 } /* namespace */
76 
77 #endif /* __core_PoolAllocator_h__ */
78 
kernel
Definition: namespace.dox:3