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_MEMORY_H_ Chris@50: #define KJ_MEMORY_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 "common.h" Chris@50: Chris@50: namespace kj { Chris@50: Chris@50: // ======================================================================================= Chris@50: // Disposer -- Implementation details. Chris@50: Chris@50: class Disposer { Chris@50: // Abstract interface for a thing that "disposes" of objects, where "disposing" usually means Chris@50: // calling the destructor followed by freeing the underlying memory. `Own` encapsulates an Chris@50: // object pointer with corresponding Disposer. Chris@50: // Chris@50: // Few developers will ever touch this interface. It is primarily useful for those implementing Chris@50: // custom memory allocators. Chris@50: Chris@50: protected: Chris@50: // Do not declare a destructor, as doing so will force a global initializer for each HeapDisposer Chris@50: // instance. Eww! Chris@50: Chris@50: virtual void disposeImpl(void* pointer) const = 0; Chris@50: // Disposes of the object, given a pointer to the beginning of the object. If the object is Chris@50: // polymorphic, this pointer is determined by dynamic_cast(). For non-polymorphic types, Chris@50: // Own does not allow any casting, so the pointer exactly matches the original one given to Chris@50: // Own. Chris@50: Chris@50: public: Chris@50: Chris@50: template Chris@50: void dispose(T* object) const; Chris@50: // Helper wrapper around disposeImpl(). Chris@50: // Chris@50: // If T is polymorphic, calls `disposeImpl(dynamic_cast(object))`, otherwise calls Chris@50: // `disposeImpl(implicitCast(object))`. Chris@50: // Chris@50: // Callers must not call dispose() on the same pointer twice, even if the first call throws Chris@50: // an exception. Chris@50: Chris@50: private: Chris@50: template Chris@50: struct Dispose_; Chris@50: }; Chris@50: Chris@50: template Chris@50: class DestructorOnlyDisposer: public Disposer { Chris@50: // A disposer that merely calls the type's destructor and nothing else. Chris@50: Chris@50: public: Chris@50: static const DestructorOnlyDisposer instance; Chris@50: Chris@50: void disposeImpl(void* pointer) const override { Chris@50: reinterpret_cast(pointer)->~T(); Chris@50: } Chris@50: }; Chris@50: Chris@50: template Chris@50: const DestructorOnlyDisposer DestructorOnlyDisposer::instance = DestructorOnlyDisposer(); Chris@50: Chris@50: class NullDisposer: public Disposer { Chris@50: // A disposer that does nothing. Chris@50: Chris@50: public: Chris@50: static const NullDisposer instance; Chris@50: Chris@50: void disposeImpl(void* pointer) const override {} Chris@50: }; Chris@50: Chris@50: // ======================================================================================= Chris@50: // Own -- An owned pointer. Chris@50: Chris@50: template Chris@50: class Own { Chris@50: // A transferrable title to a T. When an Own goes out of scope, the object's Disposer is Chris@50: // called to dispose of it. An Own can be efficiently passed by move, without relocating the Chris@50: // underlying object; this transfers ownership. Chris@50: // Chris@50: // This is much like std::unique_ptr, except: Chris@50: // - You cannot release(). An owned object is not necessarily allocated with new (see next Chris@50: // point), so it would be hard to use release() correctly. Chris@50: // - The deleter is made polymorphic by virtual call rather than by template. This is much Chris@50: // more powerful -- it allows the use of custom allocators, freelists, etc. This could Chris@50: // _almost_ be accomplished with unique_ptr by forcing everyone to use something like Chris@50: // std::unique_ptr, except that things get hairy in the presence of multiple Chris@50: // inheritance and upcasting, and anyway if you force everyone to use a custom deleter Chris@50: // then you've lost any benefit to interoperating with the "standard" unique_ptr. Chris@50: Chris@50: public: Chris@50: KJ_DISALLOW_COPY(Own); Chris@50: inline Own(): disposer(nullptr), ptr(nullptr) {} Chris@50: inline Own(Own&& other) noexcept Chris@50: : disposer(other.disposer), ptr(other.ptr) { other.ptr = nullptr; } Chris@50: inline Own(Own>&& other) noexcept Chris@50: : disposer(other.disposer), ptr(other.ptr) { other.ptr = nullptr; } Chris@50: template ()>> Chris@50: inline Own(Own&& other) noexcept Chris@50: : disposer(other.disposer), ptr(other.ptr) { Chris@50: static_assert(__is_polymorphic(T), Chris@50: "Casting owned pointers requires that the target type is polymorphic."); Chris@50: other.ptr = nullptr; Chris@50: } Chris@50: inline Own(T* ptr, const Disposer& disposer) noexcept: disposer(&disposer), ptr(ptr) {} Chris@50: Chris@50: ~Own() noexcept(false) { dispose(); } Chris@50: Chris@50: inline Own& operator=(Own&& other) { Chris@50: // Move-assingnment operator. Chris@50: Chris@50: // Careful, this might own `other`. Therefore we have to transfer the pointers first, then Chris@50: // dispose. Chris@50: const Disposer* disposerCopy = disposer; Chris@50: T* ptrCopy = ptr; Chris@50: disposer = other.disposer; Chris@50: ptr = other.ptr; Chris@50: other.ptr = nullptr; Chris@50: if (ptrCopy != nullptr) { Chris@50: disposerCopy->dispose(const_cast*>(ptrCopy)); Chris@50: } Chris@50: return *this; Chris@50: } Chris@50: Chris@50: inline Own& operator=(decltype(nullptr)) { Chris@50: dispose(); Chris@50: return *this; Chris@50: } Chris@50: Chris@50: template Chris@50: Own downcast() { Chris@50: // Downcast the pointer to Own, destroying the original pointer. If this pointer does not Chris@50: // actually point at an instance of U, the results are undefined (throws an exception in debug Chris@50: // mode if RTTI is enabled, otherwise you're on your own). Chris@50: Chris@50: Own result; Chris@50: if (ptr != nullptr) { Chris@50: result.ptr = &kj::downcast(*ptr); Chris@50: result.disposer = disposer; Chris@50: ptr = nullptr; Chris@50: } Chris@50: return result; Chris@50: } Chris@50: Chris@50: #define NULLCHECK KJ_IREQUIRE(ptr != nullptr, "null Own<> dereference") Chris@50: inline T* operator->() { NULLCHECK; return ptr; } Chris@50: inline const T* operator->() const { NULLCHECK; return ptr; } Chris@50: inline T& operator*() { NULLCHECK; return *ptr; } Chris@50: inline const T& operator*() const { NULLCHECK; return *ptr; } Chris@50: #undef NULLCHECK Chris@50: inline T* get() { return ptr; } Chris@50: inline const T* get() const { return ptr; } Chris@50: inline operator T*() { return ptr; } Chris@50: inline operator const T*() const { return ptr; } Chris@50: Chris@50: private: Chris@50: const Disposer* disposer; // Only valid if ptr != nullptr. Chris@50: T* ptr; Chris@50: Chris@50: inline explicit Own(decltype(nullptr)): disposer(nullptr), ptr(nullptr) {} Chris@50: Chris@50: inline bool operator==(decltype(nullptr)) { return ptr == nullptr; } Chris@50: inline bool operator!=(decltype(nullptr)) { return ptr != nullptr; } Chris@50: // Only called by Maybe>. Chris@50: Chris@50: inline void dispose() { Chris@50: // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly Chris@50: // dispose again. Chris@50: T* ptrCopy = ptr; Chris@50: if (ptrCopy != nullptr) { Chris@50: ptr = nullptr; Chris@50: disposer->dispose(const_cast*>(ptrCopy)); Chris@50: } Chris@50: } Chris@50: Chris@50: template Chris@50: friend class Own; Chris@50: friend class Maybe>; Chris@50: }; Chris@50: Chris@50: namespace _ { // private Chris@50: Chris@50: template Chris@50: class OwnOwn { Chris@50: public: Chris@50: inline OwnOwn(Own&& value) noexcept: value(kj::mv(value)) {} Chris@50: Chris@50: inline Own& operator*() & { return value; } Chris@50: inline const Own& operator*() const & { return value; } Chris@50: inline Own&& operator*() && { return kj::mv(value); } Chris@50: inline const Own&& operator*() const && { return kj::mv(value); } Chris@50: inline Own* operator->() { return &value; } Chris@50: inline const Own* operator->() const { return &value; } Chris@50: inline operator Own*() { return value ? &value : nullptr; } Chris@50: inline operator const Own*() const { return value ? &value : nullptr; } Chris@50: Chris@50: private: Chris@50: Own value; Chris@50: }; Chris@50: Chris@50: template Chris@50: OwnOwn readMaybe(Maybe>&& maybe) { return OwnOwn(kj::mv(maybe.ptr)); } Chris@50: template Chris@50: Own* readMaybe(Maybe>& maybe) { return maybe.ptr ? &maybe.ptr : nullptr; } Chris@50: template Chris@50: const Own* readMaybe(const Maybe>& maybe) { return maybe.ptr ? &maybe.ptr : nullptr; } Chris@50: Chris@50: } // namespace _ (private) Chris@50: Chris@50: template Chris@50: class Maybe> { Chris@50: public: Chris@50: inline Maybe(): ptr(nullptr) {} Chris@50: inline Maybe(Own&& t) noexcept: ptr(kj::mv(t)) {} Chris@50: inline Maybe(Maybe&& other) noexcept: ptr(kj::mv(other.ptr)) {} Chris@50: Chris@50: template Chris@50: inline Maybe(Maybe>&& other): ptr(mv(other.ptr)) {} Chris@50: Chris@50: inline Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {} Chris@50: Chris@50: inline operator Maybe() { return ptr.get(); } Chris@50: inline operator Maybe() const { return ptr.get(); } Chris@50: Chris@50: inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); return *this; } Chris@50: Chris@50: inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; } Chris@50: inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; } Chris@50: Chris@50: Own& orDefault(Own& defaultValue) { Chris@50: if (ptr == nullptr) { Chris@50: return defaultValue; Chris@50: } else { Chris@50: return ptr; Chris@50: } Chris@50: } Chris@50: const Own& orDefault(const Own& defaultValue) const { Chris@50: if (ptr == nullptr) { Chris@50: return defaultValue; Chris@50: } else { Chris@50: return ptr; Chris@50: } Chris@50: } Chris@50: Chris@50: template Chris@50: auto map(Func&& f) & -> Maybe&>()))> { Chris@50: if (ptr == nullptr) { Chris@50: return nullptr; Chris@50: } else { Chris@50: return f(ptr); Chris@50: } Chris@50: } Chris@50: Chris@50: template Chris@50: auto map(Func&& f) const & -> Maybe&>()))> { Chris@50: if (ptr == nullptr) { Chris@50: return nullptr; Chris@50: } else { Chris@50: return f(ptr); Chris@50: } Chris@50: } Chris@50: Chris@50: template Chris@50: auto map(Func&& f) && -> Maybe&&>()))> { Chris@50: if (ptr == nullptr) { Chris@50: return nullptr; Chris@50: } else { Chris@50: return f(kj::mv(ptr)); Chris@50: } Chris@50: } Chris@50: Chris@50: template Chris@50: auto map(Func&& f) const && -> Maybe&&>()))> { Chris@50: if (ptr == nullptr) { Chris@50: return nullptr; Chris@50: } else { Chris@50: return f(kj::mv(ptr)); Chris@50: } Chris@50: } Chris@50: Chris@50: private: Chris@50: Own ptr; Chris@50: Chris@50: template Chris@50: friend class Maybe; Chris@50: template Chris@50: friend _::OwnOwn _::readMaybe(Maybe>&& maybe); Chris@50: template Chris@50: friend Own* _::readMaybe(Maybe>& maybe); Chris@50: template Chris@50: friend const Own* _::readMaybe(const Maybe>& maybe); Chris@50: }; Chris@50: Chris@50: namespace _ { // private Chris@50: Chris@50: template Chris@50: class HeapDisposer final: public Disposer { Chris@50: public: Chris@50: virtual void disposeImpl(void* pointer) const override { delete reinterpret_cast(pointer); } Chris@50: Chris@50: static const HeapDisposer instance; Chris@50: }; Chris@50: Chris@50: template Chris@50: const HeapDisposer HeapDisposer::instance = HeapDisposer(); Chris@50: Chris@50: } // namespace _ (private) Chris@50: Chris@50: template Chris@50: Own heap(Params&&... params) { Chris@50: // heap(...) allocates a T on the heap, forwarding the parameters to its constructor. The Chris@50: // exact heap implementation is unspecified -- for now it is operator new, but you should not Chris@50: // assume this. (Since we know the object size at delete time, we could actually implement an Chris@50: // allocator that is more efficient than operator new.) Chris@50: Chris@50: return Own(new T(kj::fwd(params)...), _::HeapDisposer::instance); Chris@50: } Chris@50: Chris@50: template Chris@50: Own> heap(T&& orig) { Chris@50: // Allocate a copy (or move) of the argument on the heap. Chris@50: // Chris@50: // The purpose of this overload is to allow you to omit the template parameter as there is only Chris@50: // one argument and the purpose is to copy it. Chris@50: Chris@50: typedef Decay T2; Chris@50: return Own(new T2(kj::fwd(orig)), _::HeapDisposer::instance); Chris@50: } Chris@50: Chris@50: // ======================================================================================= Chris@50: // SpaceFor -- assists in manual allocation Chris@50: Chris@50: template Chris@50: class SpaceFor { Chris@50: // A class which has the same size and alignment as T but does not call its constructor or Chris@50: // destructor automatically. Instead, call construct() to construct a T in the space, which Chris@50: // returns an Own which will take care of calling T's destructor later. Chris@50: Chris@50: public: Chris@50: inline SpaceFor() {} Chris@50: inline ~SpaceFor() {} Chris@50: Chris@50: template Chris@50: Own construct(Params&&... params) { Chris@50: ctor(value, kj::fwd(params)...); Chris@50: return Own(&value, DestructorOnlyDisposer::instance); Chris@50: } Chris@50: Chris@50: private: Chris@50: union { Chris@50: T value; Chris@50: }; Chris@50: }; Chris@50: Chris@50: // ======================================================================================= Chris@50: // Inline implementation details Chris@50: Chris@50: template Chris@50: struct Disposer::Dispose_ { Chris@50: static void dispose(T* object, const Disposer& disposer) { Chris@50: // Note that dynamic_cast does not require RTTI to be enabled, because the offset to Chris@50: // the top of the object is in the vtable -- as it obviously needs to be to correctly implement Chris@50: // operator delete. Chris@50: disposer.disposeImpl(dynamic_cast(object)); Chris@50: } Chris@50: }; Chris@50: template Chris@50: struct Disposer::Dispose_ { Chris@50: static void dispose(T* object, const Disposer& disposer) { Chris@50: disposer.disposeImpl(static_cast(object)); Chris@50: } Chris@50: }; Chris@50: Chris@50: template Chris@50: void Disposer::dispose(T* object) const { Chris@50: Dispose_::dispose(object, *this); Chris@50: } Chris@50: Chris@50: } // namespace kj Chris@50: Chris@50: #endif // KJ_MEMORY_H_