spot  1.2.4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
fixpool.hh
1 // Copyright (C) 2011 Laboratoire de Recherche et Developpement de
2 // l'Epita (LRDE)
3 //
4 // This file is part of Spot, a model checking library.
5 //
6 // Spot is free software; you can redistribute it and/or modify it
7 // under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // Spot is distributed in the hope that it will be useful, but WITHOUT
12 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 // License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program. If not, see <http://www.gnu.org/licenses/>.
18 
19 #ifndef SPOT_MISC_FIXPOOL_HH
20 # define SPOT_MISC_FIXPOOL_HH
21 
22 #include <new>
23 #include <cstddef>
24 #include <cstdlib>
25 #include <cassert>
26 
27 namespace spot
28 {
29 
32  {
33  public:
35  fixed_size_pool(size_t size)
36  : freelist_(0), free_start_(0), free_end_(0), chunklist_(0)
37  {
38  const size_t alignement = 2 * sizeof(size_t);
39  size_ = ((size >= sizeof(block_) ? size : sizeof(block_))
40  + alignement - 1) & ~(alignement - 1);
41  }
42 
45  {
46  while (chunklist_)
47  {
48  chunk_* prev = chunklist_->prev;
49  free(chunklist_);
50  chunklist_ = prev;
51  }
52  }
53 
55  void*
57  {
58  block_* f = freelist_;
59  // If we have free blocks available, return the first one.
60  if (f)
61  {
62  freelist_ = f->next;
63  return f;
64  }
65 
66  // Else, create a block out of the last chunk of allocated
67  // memory.
68 
69  // If all the last chunk has been used, allocate one more.
70  if (free_start_ + size_ > free_end_)
71  {
72  const size_t requested = (size_ > 128 ? size_ : 128) * 8192 - 64;
73  chunk_* c = reinterpret_cast<chunk_*>(malloc(requested));
74  if (!c)
75  throw std::bad_alloc();
76  c->prev = chunklist_;
77  chunklist_ = c;
78 
79  free_start_ = c->data_ + size_;
80  free_end_ = c->data_ + requested;
81  }
82 
83  void* res = free_start_;
84  free_start_ += size_;
85  return res;
86  }
87 
94  void
95  deallocate (const void* ptr)
96  {
97  assert(ptr);
98  block_* b = reinterpret_cast<block_*>(const_cast<void*>(ptr));
99  b->next = freelist_;
100  freelist_ = b;
101  }
102 
103  private:
104  size_t size_;
105  struct block_ { block_* next; }* freelist_;
106  char* free_start_;
107  char* free_end_;
108  // chunk = several agglomerated blocks
109  union chunk_ { chunk_* prev; char data_[1]; }* chunklist_;
110  };
111 
112 }
113 
114 #endif // SPOT_MISC_FIXPOOL_HH

Please direct any question, comment, or bug report to the Spot mailing list at spot@lrde.epita.fr.
Generated on Thu May 15 2014 11:04:11 for spot by doxygen 1.8.4