1 #ifndef __STAN__MEMORY__STACK_ALLOC_HPP__
2 #define __STAN__MEMORY__STACK_ALLOC_HPP__
12 #define likely(x) (__builtin_expect((x),1))
13 #define unlikely(x) (__builtin_expect((x),0))
16 #define unlikely(x) (x)
36 return (
reinterpret_cast<uintptr_t
>(ptr) % bytes_aligned) == 0U;
41 const size_t DEFAULT_INITIAL_NBYTES = 1 << 16;
46 inline char* eight_byte_aligned_malloc(
size_t size) {
47 char* ptr =
static_cast<char*
>(malloc(size));
51 s <<
"invalid alignment to 8 bytes, ptr="
52 <<
reinterpret_cast<uintptr_t
>(ptr)
54 throw std::runtime_error(s.str());
81 std::vector<char*> blocks_;
82 std::vector<size_t> sizes_;
95 char* move_to_next_block(
size_t len) {
99 while ((cur_block_ < blocks_.size()) && (sizes_[cur_block_] < len))
102 if (
unlikely(cur_block_ >= blocks_.size())) {
104 size_t newsize = sizes_.back() * 2;
107 blocks_.push_back(eight_byte_aligned_malloc(newsize));
109 throw std::bad_alloc();
110 sizes_.push_back(newsize);
112 result = blocks_[cur_block_];
114 next_loc_ = result + len;
115 cur_block_end_ = result + sizes_[cur_block_];
131 blocks_(1, eight_byte_aligned_malloc(initial_nbytes)),
132 sizes_(1,initial_nbytes),
134 cur_block_end_(blocks_[0] + initial_nbytes),
135 next_loc_(blocks_[0]) {
138 throw std::bad_alloc();
149 for (
size_t i = 0; i < blocks_.size(); ++i)
168 char* result = next_loc_;
171 if (
unlikely(next_loc_ >= cur_block_end_))
172 result = move_to_next_block(len);
173 return (
void*)result;
184 next_loc_ = blocks_[0];
185 cur_block_end_ = next_loc_ + sizes_[0];
195 for (
size_t i = 1; i < blocks_.size(); ++i)
An instance of this class provides a memory pool through which blocks of raw memory may be allocated ...
void free_all()
Free all memory used by the stack allocator other than the initial block allocation back to the syste...
stack_alloc(size_t initial_nbytes=DEFAULT_INITIAL_NBYTES)
Construct a resizable stack allocator initially holding the specified number of bytes.
void recover_all()
Recover all the memory used by the stack allocator.
~stack_alloc()
Destroy this memory allocator.
void * alloc(size_t len)
Return a newly allocated block of memory of the appropriate size managed by the stack allocator.
bool is_aligned(T *ptr, unsigned int bytes_aligned)
Return true if the specified pointer is aligned on the number of bytes.
Probability, optimization and sampling library.