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