2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #ifndef FOLLY_ARENA_H_
18 #error This file may only be included from Arena.h
21 // Implementation of Arena.h functions
25 template <class Alloc>
26 std::pair<typename Arena<Alloc>::Block*, size_t>
27 Arena<Alloc>::Block::allocate(Alloc& alloc, size_t size, bool allowSlack) {
28 size_t allocSize = sizeof(Block) + size;
30 allocSize = ArenaAllocatorTraits<Alloc>::goodSize(alloc, allocSize);
33 void* mem = alloc.allocate(allocSize);
34 return std::make_pair(new (mem) Block(), allocSize - sizeof(Block));
37 template <class Alloc>
38 void Arena<Alloc>::Block::deallocate(Alloc& alloc) {
40 alloc.deallocate(this);
43 template <class Alloc>
44 void* Arena<Alloc>::allocateSlow(size_t size) {
45 std::pair<Block*, size_t> p;
48 size_t allocSize = std::max(size, minBlockSize()) + sizeof(Block);
49 if (sizeLimit_ != kNoSizeLimit &&
50 allocSize > sizeLimit_ - totalAllocatedSize_) {
51 throw std::bad_alloc();
54 if (size > minBlockSize()) {
55 // Allocate a large block for this chunk only, put it at the back of the
56 // list so it doesn't get used for small allocations; don't change ptr_
57 // and end_, let them point into a normal block (or none, if they're
59 p = Block::allocate(alloc(), size, false);
60 start = p.first->start();
61 blocks_.push_back(*p.first);
63 // Allocate a normal sized block and carve out size bytes from it
64 p = Block::allocate(alloc(), minBlockSize(), true);
65 start = p.first->start();
66 blocks_.push_front(*p.first);
68 end_ = start + p.second;
71 assert(p.second >= size);
72 totalAllocatedSize_ += p.second + sizeof(Block);
76 template <class Alloc>
77 void Arena<Alloc>::merge(Arena<Alloc>&& other) {
78 blocks_.splice_after(blocks_.before_begin(), other.blocks_);
79 other.blocks_.clear();
80 other.ptr_ = other.end_ = nullptr;
81 totalAllocatedSize_ += other.totalAllocatedSize_;
82 other.totalAllocatedSize_ = 0;
85 template <class Alloc>
86 Arena<Alloc>::~Arena() {
87 auto disposer = [this] (Block* b) { b->deallocate(this->alloc()); };
88 while (!blocks_.empty()) {
89 blocks_.pop_front_and_dispose(disposer);