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