2 * Copyright 2012 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 assert(isAligned(mem));
35 return std::make_pair(new (mem) Block(), allocSize - sizeof(Block));
38 template <class Alloc>
39 void Arena<Alloc>::Block::deallocate(Alloc& alloc) {
41 alloc.deallocate(this);
44 template <class Alloc>
45 void* Arena<Alloc>::allocateSlow(size_t size) {
46 std::pair<Block*, size_t> p;
48 if (size > minBlockSize()) {
49 // Allocate a large block for this chunk only, put it at the back of the
50 // list so it doesn't get used for small allocations; don't change ptr_
51 // and end_, let them point into a normal block (or none, if they're
53 p = Block::allocate(alloc(), size, false);
54 start = p.first->start();
55 blocks_.push_back(*p.first);
57 // Allocate a normal sized block and carve out size bytes from it
58 p = Block::allocate(alloc(), minBlockSize(), true);
59 start = p.first->start();
60 blocks_.push_front(*p.first);
62 end_ = start + p.second;
65 assert(p.second >= size);
66 totalAllocatedSize_ += p.second + sizeof(Block);
70 template <class Alloc>
71 void Arena<Alloc>::merge(Arena<Alloc>&& other) {
72 blocks_.splice_after(blocks_.before_begin(), other.blocks_);
73 other.blocks_.clear();
74 other.ptr_ = other.end_ = nullptr;
75 totalAllocatedSize_ += other.totalAllocatedSize_;
76 other.totalAllocatedSize_ = 0;
79 template <class Alloc>
80 Arena<Alloc>::~Arena() {
81 auto disposer = [this] (Block* b) { b->deallocate(this->alloc()); };
82 while (!blocks_.empty()) {
83 blocks_.pop_front_and_dispose(disposer);