/* Copyright (C) 2021 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef INCLUDED_STL_ALLOCATORS #define INCLUDED_STL_ALLOCATORS #include #include /** * Adapt a 0 A.D.-style allocator for usage in STL containers. * Use 'Backend' as an underlying allocator. */ template class STLAllocator { template friend class STLAllocator; public: using value_type = T; using pointer = T*; using is_always_equal = std::false_type; STLAllocator() : allocator(std::make_shared()) { } template STLAllocator(const STLAllocator& proxy) : allocator(proxy.allocator) { } template struct rebind { using other = STLAllocator; }; T* allocate(size_t n) { return static_cast(allocator->allocate(n * sizeof(T), nullptr, alignof(T))); } void deallocate(T* ptr, const size_t n) { return allocator->deallocate(static_cast(ptr), n * sizeof(T)); } private: std::shared_ptr allocator; }; /** * Proxies allocation to another allocator. * This allows a single allocator to serve multiple STL containers. */ template class ProxyAllocator { template friend class ProxyAllocator; public: using value_type = T; using pointer = T*; using is_always_equal = std::false_type; ProxyAllocator(Backend& alloc) : allocator(alloc) { } template ProxyAllocator(const ProxyAllocator& proxy) : allocator(proxy.allocator) { } template struct rebind { using other = ProxyAllocator; }; T* allocate(size_t n) { return static_cast(allocator.allocate(n * sizeof(T), nullptr, alignof(T))); } void deallocate(T* ptr, const size_t n) { return allocator.deallocate(static_cast(ptr), n * sizeof(T)); } private: Backend& allocator; }; #endif // INCLUDED_STL_ALLOCATORS