Chris@63: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@63: // Licensed under the MIT License: Chris@63: // Chris@63: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@63: // of this software and associated documentation files (the "Software"), to deal Chris@63: // in the Software without restriction, including without limitation the rights Chris@63: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@63: // copies of the Software, and to permit persons to whom the Software is Chris@63: // furnished to do so, subject to the following conditions: Chris@63: // Chris@63: // The above copyright notice and this permission notice shall be included in Chris@63: // all copies or substantial portions of the Software. Chris@63: // Chris@63: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@63: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@63: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@63: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@63: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@63: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@63: // THE SOFTWARE. Chris@63: Chris@63: #ifndef KJ_MEMORY_H_ Chris@63: #define KJ_MEMORY_H_ Chris@63: Chris@63: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@63: #pragma GCC system_header Chris@63: #endif Chris@63: Chris@63: #include "common.h" Chris@63: Chris@63: namespace kj { Chris@63: Chris@63: // ======================================================================================= Chris@63: // Disposer -- Implementation details. Chris@63: Chris@63: class Disposer { Chris@63: // Abstract interface for a thing that "disposes" of objects, where "disposing" usually means Chris@63: // calling the destructor followed by freeing the underlying memory. `Own` encapsulates an Chris@63: // object pointer with corresponding Disposer. Chris@63: // Chris@63: // Few developers will ever touch this interface. It is primarily useful for those implementing Chris@63: // custom memory allocators. Chris@63: Chris@63: protected: Chris@63: // Do not declare a destructor, as doing so will force a global initializer for each HeapDisposer Chris@63: // instance. Eww! Chris@63: Chris@63: virtual void disposeImpl(void* pointer) const = 0; Chris@63: // Disposes of the object, given a pointer to the beginning of the object. If the object is Chris@63: // polymorphic, this pointer is determined by dynamic_cast(). For non-polymorphic types, Chris@63: // Own does not allow any casting, so the pointer exactly matches the original one given to Chris@63: // Own. Chris@63: Chris@63: public: Chris@63: Chris@63: template Chris@63: void dispose(T* object) const; Chris@63: // Helper wrapper around disposeImpl(). Chris@63: // Chris@63: // If T is polymorphic, calls `disposeImpl(dynamic_cast(object))`, otherwise calls Chris@63: // `disposeImpl(implicitCast(object))`. Chris@63: // Chris@63: // Callers must not call dispose() on the same pointer twice, even if the first call throws Chris@63: // an exception. Chris@63: Chris@63: private: Chris@63: template Chris@63: struct Dispose_; Chris@63: }; Chris@63: Chris@63: template Chris@63: class DestructorOnlyDisposer: public Disposer { Chris@63: // A disposer that merely calls the type's destructor and nothing else. Chris@63: Chris@63: public: Chris@63: static const DestructorOnlyDisposer instance; Chris@63: Chris@63: void disposeImpl(void* pointer) const override { Chris@63: reinterpret_cast(pointer)->~T(); Chris@63: } Chris@63: }; Chris@63: Chris@63: template Chris@63: const DestructorOnlyDisposer DestructorOnlyDisposer::instance = DestructorOnlyDisposer(); Chris@63: Chris@63: class NullDisposer: public Disposer { Chris@63: // A disposer that does nothing. Chris@63: Chris@63: public: Chris@63: static const NullDisposer instance; Chris@63: Chris@63: void disposeImpl(void* pointer) const override {} Chris@63: }; Chris@63: Chris@63: // ======================================================================================= Chris@63: // Own -- An owned pointer. Chris@63: Chris@63: template Chris@63: class Own { Chris@63: // A transferrable title to a T. When an Own goes out of scope, the object's Disposer is Chris@63: // called to dispose of it. An Own can be efficiently passed by move, without relocating the Chris@63: // underlying object; this transfers ownership. Chris@63: // Chris@63: // This is much like std::unique_ptr, except: Chris@63: // - You cannot release(). An owned object is not necessarily allocated with new (see next Chris@63: // point), so it would be hard to use release() correctly. Chris@63: // - The deleter is made polymorphic by virtual call rather than by template. This is much Chris@63: // more powerful -- it allows the use of custom allocators, freelists, etc. This could Chris@63: // _almost_ be accomplished with unique_ptr by forcing everyone to use something like Chris@63: // std::unique_ptr, except that things get hairy in the presence of multiple Chris@63: // inheritance and upcasting, and anyway if you force everyone to use a custom deleter Chris@63: // then you've lost any benefit to interoperating with the "standard" unique_ptr. Chris@63: Chris@63: public: Chris@63: KJ_DISALLOW_COPY(Own); Chris@63: inline Own(): disposer(nullptr), ptr(nullptr) {} Chris@63: inline Own(Own&& other) noexcept Chris@63: : disposer(other.disposer), ptr(other.ptr) { other.ptr = nullptr; } Chris@63: inline Own(Own>&& other) noexcept Chris@63: : disposer(other.disposer), ptr(other.ptr) { other.ptr = nullptr; } Chris@63: template ()>> Chris@63: inline Own(Own&& other) noexcept Chris@63: : disposer(other.disposer), ptr(other.ptr) { Chris@63: static_assert(__is_polymorphic(T), Chris@63: "Casting owned pointers requires that the target type is polymorphic."); Chris@63: other.ptr = nullptr; Chris@63: } Chris@63: inline Own(T* ptr, const Disposer& disposer) noexcept: disposer(&disposer), ptr(ptr) {} Chris@63: Chris@63: ~Own() noexcept(false) { dispose(); } Chris@63: Chris@63: inline Own& operator=(Own&& other) { Chris@63: // Move-assingnment operator. Chris@63: Chris@63: // Careful, this might own `other`. Therefore we have to transfer the pointers first, then Chris@63: // dispose. Chris@63: const Disposer* disposerCopy = disposer; Chris@63: T* ptrCopy = ptr; Chris@63: disposer = other.disposer; Chris@63: ptr = other.ptr; Chris@63: other.ptr = nullptr; Chris@63: if (ptrCopy != nullptr) { Chris@63: disposerCopy->dispose(const_cast*>(ptrCopy)); Chris@63: } Chris@63: return *this; Chris@63: } Chris@63: Chris@63: inline Own& operator=(decltype(nullptr)) { Chris@63: dispose(); Chris@63: return *this; Chris@63: } Chris@63: Chris@63: template Chris@63: Own downcast() { Chris@63: // Downcast the pointer to Own, destroying the original pointer. If this pointer does not Chris@63: // actually point at an instance of U, the results are undefined (throws an exception in debug Chris@63: // mode if RTTI is enabled, otherwise you're on your own). Chris@63: Chris@63: Own result; Chris@63: if (ptr != nullptr) { Chris@63: result.ptr = &kj::downcast(*ptr); Chris@63: result.disposer = disposer; Chris@63: ptr = nullptr; Chris@63: } Chris@63: return result; Chris@63: } Chris@63: Chris@63: #define NULLCHECK KJ_IREQUIRE(ptr != nullptr, "null Own<> dereference") Chris@63: inline T* operator->() { NULLCHECK; return ptr; } Chris@63: inline const T* operator->() const { NULLCHECK; return ptr; } Chris@63: inline T& operator*() { NULLCHECK; return *ptr; } Chris@63: inline const T& operator*() const { NULLCHECK; return *ptr; } Chris@63: #undef NULLCHECK Chris@63: inline T* get() { return ptr; } Chris@63: inline const T* get() const { return ptr; } Chris@63: inline operator T*() { return ptr; } Chris@63: inline operator const T*() const { return ptr; } Chris@63: Chris@63: private: Chris@63: const Disposer* disposer; // Only valid if ptr != nullptr. Chris@63: T* ptr; Chris@63: Chris@63: inline explicit Own(decltype(nullptr)): disposer(nullptr), ptr(nullptr) {} Chris@63: Chris@63: inline bool operator==(decltype(nullptr)) { return ptr == nullptr; } Chris@63: inline bool operator!=(decltype(nullptr)) { return ptr != nullptr; } Chris@63: // Only called by Maybe>. Chris@63: Chris@63: inline void dispose() { Chris@63: // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly Chris@63: // dispose again. Chris@63: T* ptrCopy = ptr; Chris@63: if (ptrCopy != nullptr) { Chris@63: ptr = nullptr; Chris@63: disposer->dispose(const_cast*>(ptrCopy)); Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: friend class Own; Chris@63: friend class Maybe>; Chris@63: }; Chris@63: Chris@63: namespace _ { // private Chris@63: Chris@63: template Chris@63: class OwnOwn { Chris@63: public: Chris@63: inline OwnOwn(Own&& value) noexcept: value(kj::mv(value)) {} Chris@63: Chris@63: inline Own& operator*() & { return value; } Chris@63: inline const Own& operator*() const & { return value; } Chris@63: inline Own&& operator*() && { return kj::mv(value); } Chris@63: inline const Own&& operator*() const && { return kj::mv(value); } Chris@63: inline Own* operator->() { return &value; } Chris@63: inline const Own* operator->() const { return &value; } Chris@63: inline operator Own*() { return value ? &value : nullptr; } Chris@63: inline operator const Own*() const { return value ? &value : nullptr; } Chris@63: Chris@63: private: Chris@63: Own value; Chris@63: }; Chris@63: Chris@63: template Chris@63: OwnOwn readMaybe(Maybe>&& maybe) { return OwnOwn(kj::mv(maybe.ptr)); } Chris@63: template Chris@63: Own* readMaybe(Maybe>& maybe) { return maybe.ptr ? &maybe.ptr : nullptr; } Chris@63: template Chris@63: const Own* readMaybe(const Maybe>& maybe) { return maybe.ptr ? &maybe.ptr : nullptr; } Chris@63: Chris@63: } // namespace _ (private) Chris@63: Chris@63: template Chris@63: class Maybe> { Chris@63: public: Chris@63: inline Maybe(): ptr(nullptr) {} Chris@63: inline Maybe(Own&& t) noexcept: ptr(kj::mv(t)) {} Chris@63: inline Maybe(Maybe&& other) noexcept: ptr(kj::mv(other.ptr)) {} Chris@63: Chris@63: template Chris@63: inline Maybe(Maybe>&& other): ptr(mv(other.ptr)) {} Chris@63: template Chris@63: inline Maybe(Own&& other): ptr(mv(other)) {} Chris@63: Chris@63: inline Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {} Chris@63: Chris@63: inline operator Maybe() { return ptr.get(); } Chris@63: inline operator Maybe() const { return ptr.get(); } Chris@63: Chris@63: inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); return *this; } Chris@63: Chris@63: inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; } Chris@63: inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; } Chris@63: Chris@63: Own& orDefault(Own& defaultValue) { Chris@63: if (ptr == nullptr) { Chris@63: return defaultValue; Chris@63: } else { Chris@63: return ptr; Chris@63: } Chris@63: } Chris@63: const Own& orDefault(const Own& defaultValue) const { Chris@63: if (ptr == nullptr) { Chris@63: return defaultValue; Chris@63: } else { Chris@63: return ptr; Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: auto map(Func&& f) & -> Maybe&>()))> { Chris@63: if (ptr == nullptr) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return f(ptr); Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: auto map(Func&& f) const & -> Maybe&>()))> { Chris@63: if (ptr == nullptr) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return f(ptr); Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: auto map(Func&& f) && -> Maybe&&>()))> { Chris@63: if (ptr == nullptr) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return f(kj::mv(ptr)); Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: auto map(Func&& f) const && -> Maybe&&>()))> { Chris@63: if (ptr == nullptr) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return f(kj::mv(ptr)); Chris@63: } Chris@63: } Chris@63: Chris@63: private: Chris@63: Own ptr; Chris@63: Chris@63: template Chris@63: friend class Maybe; Chris@63: template Chris@63: friend _::OwnOwn _::readMaybe(Maybe>&& maybe); Chris@63: template Chris@63: friend Own* _::readMaybe(Maybe>& maybe); Chris@63: template Chris@63: friend const Own* _::readMaybe(const Maybe>& maybe); Chris@63: }; Chris@63: Chris@63: namespace _ { // private Chris@63: Chris@63: template Chris@63: class HeapDisposer final: public Disposer { Chris@63: public: Chris@63: virtual void disposeImpl(void* pointer) const override { delete reinterpret_cast(pointer); } Chris@63: Chris@63: static const HeapDisposer instance; Chris@63: }; Chris@63: Chris@63: template Chris@63: const HeapDisposer HeapDisposer::instance = HeapDisposer(); Chris@63: Chris@63: } // namespace _ (private) Chris@63: Chris@63: template Chris@63: Own heap(Params&&... params) { Chris@63: // heap(...) allocates a T on the heap, forwarding the parameters to its constructor. The Chris@63: // exact heap implementation is unspecified -- for now it is operator new, but you should not Chris@63: // assume this. (Since we know the object size at delete time, we could actually implement an Chris@63: // allocator that is more efficient than operator new.) Chris@63: Chris@63: return Own(new T(kj::fwd(params)...), _::HeapDisposer::instance); Chris@63: } Chris@63: Chris@63: template Chris@63: Own> heap(T&& orig) { Chris@63: // Allocate a copy (or move) of the argument on the heap. Chris@63: // Chris@63: // The purpose of this overload is to allow you to omit the template parameter as there is only Chris@63: // one argument and the purpose is to copy it. Chris@63: Chris@63: typedef Decay T2; Chris@63: return Own(new T2(kj::fwd(orig)), _::HeapDisposer::instance); Chris@63: } Chris@63: Chris@63: // ======================================================================================= Chris@63: // SpaceFor -- assists in manual allocation Chris@63: Chris@63: template Chris@63: class SpaceFor { Chris@63: // A class which has the same size and alignment as T but does not call its constructor or Chris@63: // destructor automatically. Instead, call construct() to construct a T in the space, which Chris@63: // returns an Own which will take care of calling T's destructor later. Chris@63: Chris@63: public: Chris@63: inline SpaceFor() {} Chris@63: inline ~SpaceFor() {} Chris@63: Chris@63: template Chris@63: Own construct(Params&&... params) { Chris@63: ctor(value, kj::fwd(params)...); Chris@63: return Own(&value, DestructorOnlyDisposer::instance); Chris@63: } Chris@63: Chris@63: private: Chris@63: union { Chris@63: T value; Chris@63: }; Chris@63: }; Chris@63: Chris@63: // ======================================================================================= Chris@63: // Inline implementation details Chris@63: Chris@63: template Chris@63: struct Disposer::Dispose_ { Chris@63: static void dispose(T* object, const Disposer& disposer) { Chris@63: // Note that dynamic_cast does not require RTTI to be enabled, because the offset to Chris@63: // the top of the object is in the vtable -- as it obviously needs to be to correctly implement Chris@63: // operator delete. Chris@63: disposer.disposeImpl(dynamic_cast(object)); Chris@63: } Chris@63: }; Chris@63: template Chris@63: struct Disposer::Dispose_ { Chris@63: static void dispose(T* object, const Disposer& disposer) { Chris@63: disposer.disposeImpl(static_cast(object)); Chris@63: } Chris@63: }; Chris@63: Chris@63: template Chris@63: void Disposer::dispose(T* object) const { Chris@63: Dispose_::dispose(object, *this); Chris@63: } Chris@63: Chris@63: } // namespace kj Chris@63: Chris@63: #endif // KJ_MEMORY_H_