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