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