Add a LICENSE file for folly
[folly.git] / folly / Arena-inl.h
1 /*
2  * Copyright 2012 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef FOLLY_ARENA_H_
18 #error This file may only be included from Arena.h
19 #endif
20
21 // Implementation of Arena.h functions
22
23 namespace folly {
24
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;
29   if (allowSlack) {
30     allocSize = ArenaAllocatorTraits<Alloc>::goodSize(alloc, allocSize);
31   }
32
33   void* mem = alloc.allocate(allocSize);
34   assert(isAligned(mem));
35   return std::make_pair(new (mem) Block(), allocSize - sizeof(Block));
36 }
37
38 template <class Alloc>
39 void Arena<Alloc>::Block::deallocate(Alloc& alloc) {
40   this->~Block();
41   alloc.deallocate(this);
42 }
43
44 template <class Alloc>
45 void* Arena<Alloc>::allocateSlow(size_t size) {
46   std::pair<Block*, size_t> p;
47   char* start;
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
52     // null)
53     p = Block::allocate(alloc(), size, false);
54     start = p.first->start();
55     blocks_.push_back(*p.first);
56   } else {
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);
61     ptr_ = start + size;
62     end_ = start + p.second;
63   }
64
65   assert(p.second >= size);
66   return start;
67 }
68
69 template <class Alloc>
70 void Arena<Alloc>::merge(Arena<Alloc>&& other) {
71   blocks_.splice_after(blocks_.before_begin(), other.blocks_);
72   other.blocks_.clear();
73   other.ptr_ = other.end_ = nullptr;
74 }
75
76 template <class Alloc>
77 Arena<Alloc>::~Arena() {
78   auto disposer = [this] (Block* b) { b->deallocate(this->alloc()); };
79   while (!blocks_.empty()) {
80     blocks_.pop_front_and_dispose(disposer);
81   }
82 }
83
84 }  // namespace folly