libcruft-util/alloc/arena.hpp
Danny Robson f6056153e3 rename root namespace from util to cruft
This places, at long last, the core library code into the same namespace
as the extended library code.
2018-08-05 14:42:02 +10:00

85 lines
2.2 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2015-2018 Danny Robson <danny@nerdcruft.net>
*/
#ifndef CRUFT_UTIL_ALLOC_ARENA_HPP
#define CRUFT_UTIL_ALLOC_ARENA_HPP
#include "../memory/deleter.hpp"
#include "../cast.hpp"
#include "../view.hpp"
#include <memory>
#include <utility>
namespace cruft::alloc {
/// wraps a block allocator with an interface suitable for allocating
/// individual objects.
template <class T>
class arena {
public:
explicit arena (T &store):
m_store (store)
{ ; }
//---------------------------------------------------------------------
template <typename U, typename ...Args>
U*
acquire (Args&&... args)
{
U *data = m_store.template allocate<U> (1).data ();
try {
new (data) U (std::forward<Args> (args)...);
} catch (...) {
m_store.template deallocate<U> ({data,1});
throw;
}
return data;
}
//---------------------------------------------------------------------
template <typename U>
void
release (U *u)
{
u->~U ();
m_store.template deallocate<U> (cruft::view {u,1u});
}
//---------------------------------------------------------------------
template <typename U>
using deleter_t = cruft::memory::owner_deleter<
U,arena<T>,&arena::release
>;
template <typename U>
using unique_t = std::unique_ptr<U,deleter_t<U>>;
// the return type must be auto and the implementation must be inline
// otherwise we trigger an internal compiler error in gcc-5.2.0
// "sorry, unimplemented: mangling offset_ref"
template <typename U, typename ...Args>
auto
unique (Args&& ...args)
{
return unique_t<U> {
acquire<U> (std::forward<Args> (args)...),
deleter_t<U> (*this)
};
}
private:
T &m_store;
};
}
#endif