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