Stan  1.0
probability, sampling & optimization
chunk_alloc.hpp
Go to the documentation of this file.
1 #ifndef __STAN__MEMORY__CHUNK_ALLOC_HPP__
2 #define __STAN__MEMORY__CHUNK_ALLOC_HPP__
3 
4 #include <cstdlib>
5 #include <cstddef>
6 #include <sstream>
7 #include <stdexcept>
8 #include <stdint.h> // FIXME: replace with cstddef?
9 #include <vector>
10 
11 #define DEFAULT_INITIAL_NCHUNKS (1 << 8)
12 
13 namespace stan {
14  namespace memory {
17  template<typename T, size_t Tnchunks_per_block = DEFAULT_INITIAL_NCHUNKS>
18  class chunk_alloc {
19  private:
20  std::vector<char*> blocks_; // storage for blocks, may be bigger than cur_block_
21  size_t cur_block_; // index into blocks_ for next alloc
22  size_t used_; // index into blocks_[cur_block_] for next alloc
23  public:
24 
25 
34  blocks_(1, eight_byte_aligned_malloc(sizeof(T)*Tnchunks_per_block)),
35  used_(0)
36  {
37  if (!blocks_[0])
38  throw std::bad_alloc(); // no msg allowed in bad_alloc ctor
39  }
40 
48  // free ALL blocks
49  for (size_t i = 0; i < blocks_.size(); ++i)
50  if (blocks_[i])
51  free(blocks_[i]);
52  }
53 
60  inline void* alloc() {
61  char *result;
62  if (unlikely(used_ >= Tnchunks_per_block)) {
63  used_ = 0;
64  cur_block_++;
65  }
66  if (unlikely(cur_block_ >= blocks_.size())) {
67  result = eight_byte_aligned_malloc(Tnchunks_per_block*sizeof(T));
68  if (!result)
69  throw std::bad_alloc(); // no msg allowed in bad_alloc ctor
70  blocks_.push_back(result);
71  }
72  result = blocks_[cur_block_] + sizeof(T)*used_;
73  ++used_;
74 
75  return (void*)result;
76  }
77 
84  inline void recover_all() {
85  cur_block_ = 0;
86  used_ = 0;
87  }
88 
94  inline void free_all() {
95  // frees all BUT the first (index 0) block
96  for (size_t i = 1; i < blocks_.size(); ++i)
97  if (blocks_[i])
98  free(blocks_[i]);
99  blocks_.resize(1);
100  recover_all();
101  }
102  };
103  }
104 }
105 #endif
void * alloc()
Return a newly allocated chunk of memory of the appropriate size managed by the stack allocator.
Definition: chunk_alloc.hpp:60
void recover_all()
Recover all the memory used by the stack allocator.
Definition: chunk_alloc.hpp:84
chunk_alloc()
Construct a resizable chunk allocator initially holding the specified number of bytes.
Definition: chunk_alloc.hpp:33
void free_all()
Free all memory used by the stack allocator other than the initial block allocation back to the syste...
Definition: chunk_alloc.hpp:94
~chunk_alloc()
Destroy this memory allocator.
Definition: chunk_alloc.hpp:47
Probability, optimization and sampling library.
Definition: agrad.cpp:6
#define unlikely(x)
Definition: stack_alloc.hpp:16

     [ Stan Home Page ] © 2011–2012, Stan Development Team.