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