Chris@50: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@50: // Licensed under the MIT License: Chris@50: // Chris@50: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@50: // of this software and associated documentation files (the "Software"), to deal Chris@50: // in the Software without restriction, including without limitation the rights Chris@50: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@50: // copies of the Software, and to permit persons to whom the Software is Chris@50: // furnished to do so, subject to the following conditions: Chris@50: // Chris@50: // The above copyright notice and this permission notice shall be included in Chris@50: // all copies or substantial portions of the Software. Chris@50: // Chris@50: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@50: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@50: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@50: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@50: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@50: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@50: // THE SOFTWARE. Chris@50: Chris@50: #ifndef KJ_ARENA_H_ Chris@50: #define KJ_ARENA_H_ Chris@50: Chris@50: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@50: #pragma GCC system_header Chris@50: #endif Chris@50: Chris@50: #include "memory.h" Chris@50: #include "array.h" Chris@50: #include "string.h" Chris@50: Chris@50: namespace kj { Chris@50: Chris@50: class Arena { Chris@50: // A class which allows several objects to be allocated in contiguous chunks of memory, then Chris@50: // frees them all at once. Chris@50: // Chris@50: // Allocating from the same Arena in multiple threads concurrently is NOT safe, because making Chris@50: // it safe would require atomic operations that would slow down allocation even when Chris@50: // single-threaded. If you need to use arena allocation in a multithreaded context, consider Chris@50: // allocating thread-local arenas. Chris@50: Chris@50: public: Chris@50: explicit Arena(size_t chunkSizeHint = 1024); Chris@50: // Create an Arena. `chunkSizeHint` hints at where to start when allocating chunks, but is only Chris@50: // a hint -- the Arena will, for example, allocate progressively larger chunks as time goes on, Chris@50: // in order to reduce overall allocation overhead. Chris@50: Chris@50: explicit Arena(ArrayPtr scratch); Chris@50: // Allocates from the given scratch space first, only resorting to the heap when it runs out. Chris@50: Chris@50: KJ_DISALLOW_COPY(Arena); Chris@50: ~Arena() noexcept(false); Chris@50: Chris@50: template Chris@50: T& allocate(Params&&... params); Chris@50: template Chris@50: ArrayPtr allocateArray(size_t size); Chris@50: // Allocate an object or array of type T. If T has a non-trivial destructor, that destructor Chris@50: // will be run during the Arena's destructor. Such destructors are run in opposite order of Chris@50: // allocation. Note that these methods must maintain a list of destructors to call, which has Chris@50: // overhead, but this overhead only applies if T has a non-trivial destructor. Chris@50: Chris@50: template Chris@50: Own allocateOwn(Params&&... params); Chris@50: template Chris@50: Array allocateOwnArray(size_t size); Chris@50: template Chris@50: ArrayBuilder allocateOwnArrayBuilder(size_t capacity); Chris@50: // Allocate an object or array of type T. Destructors are executed when the returned Own Chris@50: // or Array goes out-of-scope, which must happen before the Arena is destroyed. This variant Chris@50: // is useful when you need to control when the destructor is called. This variant also avoids Chris@50: // the need for the Arena itself to keep track of destructors to call later, which may make it Chris@50: // slightly more efficient. Chris@50: Chris@50: template Chris@50: inline T& copy(T&& value) { return allocate>(kj::fwd(value)); } Chris@50: // Allocate a copy of the given value in the arena. This is just a shortcut for calling the Chris@50: // type's copy (or move) constructor. Chris@50: Chris@50: StringPtr copyString(StringPtr content); Chris@50: // Make a copy of the given string inside the arena, and return a pointer to the copy. Chris@50: Chris@50: private: Chris@50: struct ChunkHeader { Chris@50: ChunkHeader* next; Chris@50: byte* pos; // first unallocated byte in this chunk Chris@50: byte* end; // end of this chunk Chris@50: }; Chris@50: struct ObjectHeader { Chris@50: void (*destructor)(void*); Chris@50: ObjectHeader* next; Chris@50: }; Chris@50: Chris@50: size_t nextChunkSize; Chris@50: ChunkHeader* chunkList = nullptr; Chris@50: ObjectHeader* objectList = nullptr; Chris@50: Chris@50: ChunkHeader* currentChunk = nullptr; Chris@50: Chris@50: void cleanup(); Chris@50: // Run all destructors, leaving the above pointers null. If a destructor throws, the State is Chris@50: // left in a consistent state, such that if cleanup() is called again, it will pick up where Chris@50: // it left off. Chris@50: Chris@50: void* allocateBytes(size_t amount, uint alignment, bool hasDisposer); Chris@50: // Allocate the given number of bytes. `hasDisposer` must be true if `setDisposer()` may be Chris@50: // called on this pointer later. Chris@50: Chris@50: void* allocateBytesInternal(size_t amount, uint alignment); Chris@50: // Try to allocate the given number of bytes without taking a lock. Fails if and only if there Chris@50: // is no space left in the current chunk. Chris@50: Chris@50: void setDestructor(void* ptr, void (*destructor)(void*)); Chris@50: // Schedule the given destructor to be executed when the Arena is destroyed. `ptr` must be a Chris@50: // pointer previously returned by an `allocateBytes()` call for which `hasDisposer` was true. Chris@50: Chris@50: template Chris@50: static void destroyArray(void* pointer) { Chris@50: size_t elementCount = *reinterpret_cast(pointer); Chris@50: constexpr size_t prefixSize = kj::max(alignof(T), sizeof(size_t)); Chris@50: DestructorOnlyArrayDisposer::instance.disposeImpl( Chris@50: reinterpret_cast(pointer) + prefixSize, Chris@50: sizeof(T), elementCount, elementCount, &destroyObject); Chris@50: } Chris@50: Chris@50: template Chris@50: static void destroyObject(void* pointer) { Chris@50: dtor(*reinterpret_cast(pointer)); Chris@50: } Chris@50: }; Chris@50: Chris@50: // ======================================================================================= Chris@50: // Inline implementation details Chris@50: Chris@50: template Chris@50: T& Arena::allocate(Params&&... params) { Chris@50: T& result = *reinterpret_cast(allocateBytes( Chris@50: sizeof(T), alignof(T), !__has_trivial_destructor(T))); Chris@50: if (!__has_trivial_constructor(T) || sizeof...(Params) > 0) { Chris@50: ctor(result, kj::fwd(params)...); Chris@50: } Chris@50: if (!__has_trivial_destructor(T)) { Chris@50: setDestructor(&result, &destroyObject); Chris@50: } Chris@50: return result; Chris@50: } Chris@50: Chris@50: template Chris@50: ArrayPtr Arena::allocateArray(size_t size) { Chris@50: if (__has_trivial_destructor(T)) { Chris@50: ArrayPtr result = Chris@50: arrayPtr(reinterpret_cast(allocateBytes( Chris@50: sizeof(T) * size, alignof(T), false)), size); Chris@50: if (!__has_trivial_constructor(T)) { Chris@50: for (size_t i = 0; i < size; i++) { Chris@50: ctor(result[i]); Chris@50: } Chris@50: } Chris@50: return result; Chris@50: } else { Chris@50: // Allocate with a 64-bit prefix in which we store the array size. Chris@50: constexpr size_t prefixSize = kj::max(alignof(T), sizeof(size_t)); Chris@50: void* base = allocateBytes(sizeof(T) * size + prefixSize, alignof(T), true); Chris@50: size_t& tag = *reinterpret_cast(base); Chris@50: ArrayPtr result = Chris@50: arrayPtr(reinterpret_cast(reinterpret_cast(base) + prefixSize), size); Chris@50: setDestructor(base, &destroyArray); Chris@50: Chris@50: if (__has_trivial_constructor(T)) { Chris@50: tag = size; Chris@50: } else { Chris@50: // In case of constructor exceptions, we need the tag to end up storing the number of objects Chris@50: // that were successfully constructed, so that they'll be properly destroyed. Chris@50: tag = 0; Chris@50: for (size_t i = 0; i < size; i++) { Chris@50: ctor(result[i]); Chris@50: tag = i + 1; Chris@50: } Chris@50: } Chris@50: return result; Chris@50: } Chris@50: } Chris@50: Chris@50: template Chris@50: Own Arena::allocateOwn(Params&&... params) { Chris@50: T& result = *reinterpret_cast(allocateBytes(sizeof(T), alignof(T), false)); Chris@50: if (!__has_trivial_constructor(T) || sizeof...(Params) > 0) { Chris@50: ctor(result, kj::fwd(params)...); Chris@50: } Chris@50: return Own(&result, DestructorOnlyDisposer::instance); Chris@50: } Chris@50: Chris@50: template Chris@50: Array Arena::allocateOwnArray(size_t size) { Chris@50: ArrayBuilder result = allocateOwnArrayBuilder(size); Chris@50: for (size_t i = 0; i < size; i++) { Chris@50: result.add(); Chris@50: } Chris@50: return result.finish(); Chris@50: } Chris@50: Chris@50: template Chris@50: ArrayBuilder Arena::allocateOwnArrayBuilder(size_t capacity) { Chris@50: return ArrayBuilder( Chris@50: reinterpret_cast(allocateBytes(sizeof(T) * capacity, alignof(T), false)), Chris@50: capacity, DestructorOnlyArrayDisposer::instance); Chris@50: } Chris@50: Chris@50: } // namespace kj Chris@50: Chris@50: #endif // KJ_ARENA_H_