jpayne@69: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors jpayne@69: // Licensed under the MIT License: jpayne@69: // jpayne@69: // Permission is hereby granted, free of charge, to any person obtaining a copy jpayne@69: // of this software and associated documentation files (the "Software"), to deal jpayne@69: // in the Software without restriction, including without limitation the rights jpayne@69: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell jpayne@69: // copies of the Software, and to permit persons to whom the Software is jpayne@69: // furnished to do so, subject to the following conditions: jpayne@69: // jpayne@69: // The above copyright notice and this permission notice shall be included in jpayne@69: // all copies or substantial portions of the Software. jpayne@69: // jpayne@69: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR jpayne@69: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, jpayne@69: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE jpayne@69: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER jpayne@69: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, jpayne@69: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN jpayne@69: // THE SOFTWARE. jpayne@69: jpayne@69: #pragma once jpayne@69: jpayne@69: #include "memory.h" jpayne@69: #include jpayne@69: #include jpayne@69: jpayne@69: KJ_BEGIN_HEADER jpayne@69: jpayne@69: namespace kj { jpayne@69: jpayne@69: // ======================================================================================= jpayne@69: // ArrayDisposer -- Implementation details. jpayne@69: jpayne@69: class ArrayDisposer { jpayne@69: // Much like Disposer from memory.h. jpayne@69: jpayne@69: protected: jpayne@69: // Do not declare a destructor, as doing so will force a global initializer for jpayne@69: // HeapArrayDisposer::instance. jpayne@69: jpayne@69: virtual void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount, jpayne@69: size_t capacity, void (*destroyElement)(void*)) const = 0; jpayne@69: // Disposes of the array. `destroyElement` invokes the destructor of each element, or is nullptr jpayne@69: // if the elements have trivial destructors. `capacity` is the amount of space that was jpayne@69: // allocated while `elementCount` is the number of elements that were actually constructed; jpayne@69: // these are always the same number for Array but may be different when using ArrayBuilder. jpayne@69: jpayne@69: public: jpayne@69: jpayne@69: template jpayne@69: void dispose(T* firstElement, size_t elementCount, size_t capacity) const; jpayne@69: // Helper wrapper around disposeImpl(). jpayne@69: // jpayne@69: // Callers must not call dispose() on the same array twice, even if the first call throws jpayne@69: // an exception. jpayne@69: jpayne@69: private: jpayne@69: template jpayne@69: struct Dispose_; jpayne@69: }; jpayne@69: jpayne@69: class ExceptionSafeArrayUtil { jpayne@69: // Utility class that assists in constructing or destroying elements of an array, where the jpayne@69: // constructor or destructor could throw exceptions. In case of an exception, jpayne@69: // ExceptionSafeArrayUtil's destructor will call destructors on all elements that have been jpayne@69: // constructed but not destroyed. Remember that destructors that throw exceptions are required jpayne@69: // to use UnwindDetector to detect unwind and avoid exceptions in this case. Therefore, no more jpayne@69: // than one exception will be thrown (and the program will not terminate). jpayne@69: jpayne@69: public: jpayne@69: inline ExceptionSafeArrayUtil(void* ptr, size_t elementSize, size_t constructedElementCount, jpayne@69: void (*destroyElement)(void*)) jpayne@69: : pos(reinterpret_cast(ptr) + elementSize * constructedElementCount), jpayne@69: elementSize(elementSize), constructedElementCount(constructedElementCount), jpayne@69: destroyElement(destroyElement) {} jpayne@69: KJ_DISALLOW_COPY_AND_MOVE(ExceptionSafeArrayUtil); jpayne@69: jpayne@69: inline ~ExceptionSafeArrayUtil() noexcept(false) { jpayne@69: if (constructedElementCount > 0) destroyAll(); jpayne@69: } jpayne@69: jpayne@69: void construct(size_t count, void (*constructElement)(void*)); jpayne@69: // Construct the given number of elements. jpayne@69: jpayne@69: void destroyAll(); jpayne@69: // Destroy all elements. Call this immediately before ExceptionSafeArrayUtil goes out-of-scope jpayne@69: // to ensure that one element throwing an exception does not prevent the others from being jpayne@69: // destroyed. jpayne@69: jpayne@69: void release() { constructedElementCount = 0; } jpayne@69: // Prevent ExceptionSafeArrayUtil's destructor from destroying the constructed elements. jpayne@69: // Call this after you've successfully finished constructing. jpayne@69: jpayne@69: private: jpayne@69: byte* pos; jpayne@69: size_t elementSize; jpayne@69: size_t constructedElementCount; jpayne@69: void (*destroyElement)(void*); jpayne@69: }; jpayne@69: jpayne@69: class DestructorOnlyArrayDisposer: public ArrayDisposer { jpayne@69: public: jpayne@69: static const DestructorOnlyArrayDisposer instance; jpayne@69: jpayne@69: void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount, jpayne@69: size_t capacity, void (*destroyElement)(void*)) const override; jpayne@69: }; jpayne@69: jpayne@69: class NullArrayDisposer: public ArrayDisposer { jpayne@69: // An ArrayDisposer that does nothing. Can be used to construct a fake Arrays that doesn't jpayne@69: // actually own its content. jpayne@69: jpayne@69: public: jpayne@69: static const NullArrayDisposer instance; jpayne@69: jpayne@69: void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount, jpayne@69: size_t capacity, void (*destroyElement)(void*)) const override; jpayne@69: }; jpayne@69: jpayne@69: // ======================================================================================= jpayne@69: // Array jpayne@69: jpayne@69: template jpayne@69: class Array { jpayne@69: // An owned array which will automatically be disposed of (using an ArrayDisposer) in the jpayne@69: // destructor. Can be moved, but not copied. Much like Own, but for arrays rather than jpayne@69: // single objects. jpayne@69: jpayne@69: public: jpayne@69: inline Array(): ptr(nullptr), size_(0), disposer(nullptr) {} jpayne@69: inline Array(decltype(nullptr)): ptr(nullptr), size_(0), disposer(nullptr) {} jpayne@69: inline Array(Array&& other) noexcept jpayne@69: : ptr(other.ptr), size_(other.size_), disposer(other.disposer) { jpayne@69: other.ptr = nullptr; jpayne@69: other.size_ = 0; jpayne@69: } jpayne@69: inline Array(Array>&& other) noexcept jpayne@69: : ptr(other.ptr), size_(other.size_), disposer(other.disposer) { jpayne@69: other.ptr = nullptr; jpayne@69: other.size_ = 0; jpayne@69: } jpayne@69: inline Array(T* firstElement KJ_LIFETIMEBOUND, size_t size, const ArrayDisposer& disposer) jpayne@69: : ptr(firstElement), size_(size), disposer(&disposer) {} jpayne@69: jpayne@69: KJ_DISALLOW_COPY(Array); jpayne@69: inline ~Array() noexcept { dispose(); } jpayne@69: jpayne@69: inline operator ArrayPtr() KJ_LIFETIMEBOUND { jpayne@69: return ArrayPtr(ptr, size_); jpayne@69: } jpayne@69: inline operator ArrayPtr() const KJ_LIFETIMEBOUND { jpayne@69: return ArrayPtr(ptr, size_); jpayne@69: } jpayne@69: inline ArrayPtr asPtr() KJ_LIFETIMEBOUND { jpayne@69: return ArrayPtr(ptr, size_); jpayne@69: } jpayne@69: inline ArrayPtr asPtr() const KJ_LIFETIMEBOUND { jpayne@69: return ArrayPtr(ptr, size_); jpayne@69: } jpayne@69: jpayne@69: inline size_t size() const { return size_; } jpayne@69: inline T& operator[](size_t index) KJ_LIFETIMEBOUND { jpayne@69: KJ_IREQUIRE(index < size_, "Out-of-bounds Array access."); jpayne@69: return ptr[index]; jpayne@69: } jpayne@69: inline const T& operator[](size_t index) const KJ_LIFETIMEBOUND { jpayne@69: KJ_IREQUIRE(index < size_, "Out-of-bounds Array access."); jpayne@69: return ptr[index]; jpayne@69: } jpayne@69: jpayne@69: inline const T* begin() const KJ_LIFETIMEBOUND { return ptr; } jpayne@69: inline const T* end() const KJ_LIFETIMEBOUND { return ptr + size_; } jpayne@69: inline const T& front() const KJ_LIFETIMEBOUND { return *ptr; } jpayne@69: inline const T& back() const KJ_LIFETIMEBOUND { return *(ptr + size_ - 1); } jpayne@69: inline T* begin() KJ_LIFETIMEBOUND { return ptr; } jpayne@69: inline T* end() KJ_LIFETIMEBOUND { return ptr + size_; } jpayne@69: inline T& front() KJ_LIFETIMEBOUND { return *ptr; } jpayne@69: inline T& back() KJ_LIFETIMEBOUND { return *(ptr + size_ - 1); } jpayne@69: jpayne@69: template jpayne@69: inline bool operator==(const U& other) const { return asPtr() == other; } jpayne@69: template jpayne@69: inline bool operator!=(const U& other) const { return asPtr() != other; } jpayne@69: jpayne@69: inline ArrayPtr slice(size_t start, size_t end) KJ_LIFETIMEBOUND { jpayne@69: KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds Array::slice()."); jpayne@69: return ArrayPtr(ptr + start, end - start); jpayne@69: } jpayne@69: inline ArrayPtr slice(size_t start, size_t end) const KJ_LIFETIMEBOUND { jpayne@69: KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds Array::slice()."); jpayne@69: return ArrayPtr(ptr + start, end - start); jpayne@69: } jpayne@69: jpayne@69: inline ArrayPtr asBytes() const KJ_LIFETIMEBOUND { return asPtr().asBytes(); } jpayne@69: inline ArrayPtr> asBytes() KJ_LIFETIMEBOUND { return asPtr().asBytes(); } jpayne@69: inline ArrayPtr asChars() const KJ_LIFETIMEBOUND { return asPtr().asChars(); } jpayne@69: inline ArrayPtr> asChars() KJ_LIFETIMEBOUND { return asPtr().asChars(); } jpayne@69: jpayne@69: inline Array> releaseAsBytes() { jpayne@69: // Like asBytes() but transfers ownership. jpayne@69: static_assert(sizeof(T) == sizeof(byte), jpayne@69: "releaseAsBytes() only possible on arrays with byte-size elements (e.g. chars)."); jpayne@69: Array> result( jpayne@69: reinterpret_cast*>(ptr), size_, *disposer); jpayne@69: ptr = nullptr; jpayne@69: size_ = 0; jpayne@69: return result; jpayne@69: } jpayne@69: inline Array> releaseAsChars() { jpayne@69: // Like asChars() but transfers ownership. jpayne@69: static_assert(sizeof(T) == sizeof(PropagateConst), jpayne@69: "releaseAsChars() only possible on arrays with char-size elements (e.g. bytes)."); jpayne@69: Array> result( jpayne@69: reinterpret_cast*>(ptr), size_, *disposer); jpayne@69: ptr = nullptr; jpayne@69: size_ = 0; jpayne@69: return result; jpayne@69: } jpayne@69: jpayne@69: inline bool operator==(decltype(nullptr)) const { return size_ == 0; } jpayne@69: inline bool operator!=(decltype(nullptr)) const { return size_ != 0; } jpayne@69: jpayne@69: inline Array& operator=(decltype(nullptr)) { jpayne@69: dispose(); jpayne@69: return *this; jpayne@69: } jpayne@69: jpayne@69: inline Array& operator=(Array&& other) { jpayne@69: dispose(); jpayne@69: ptr = other.ptr; jpayne@69: size_ = other.size_; jpayne@69: disposer = other.disposer; jpayne@69: other.ptr = nullptr; jpayne@69: other.size_ = 0; jpayne@69: return *this; jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: Array attach(Attachments&&... attachments) KJ_WARN_UNUSED_RESULT; jpayne@69: // Like Own::attach(), but attaches to an Array. jpayne@69: jpayne@69: private: jpayne@69: T* ptr; jpayne@69: size_t size_; jpayne@69: const ArrayDisposer* disposer; jpayne@69: jpayne@69: inline void dispose() { jpayne@69: // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly jpayne@69: // dispose again. jpayne@69: T* ptrCopy = ptr; jpayne@69: size_t sizeCopy = size_; jpayne@69: if (ptrCopy != nullptr) { jpayne@69: ptr = nullptr; jpayne@69: size_ = 0; jpayne@69: disposer->dispose(ptrCopy, sizeCopy, sizeCopy); jpayne@69: } jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: friend class Array; jpayne@69: template jpayne@69: friend class ArrayBuilder; jpayne@69: }; jpayne@69: jpayne@69: static_assert(!canMemcpy>(), "canMemcpy<>() is broken"); jpayne@69: jpayne@69: namespace _ { // private jpayne@69: jpayne@69: class HeapArrayDisposer final: public ArrayDisposer { jpayne@69: public: jpayne@69: template jpayne@69: static T* allocate(size_t count); jpayne@69: template jpayne@69: static T* allocateUninitialized(size_t count); jpayne@69: jpayne@69: static const HeapArrayDisposer instance; jpayne@69: jpayne@69: private: jpayne@69: static void* allocateImpl(size_t elementSize, size_t elementCount, size_t capacity, jpayne@69: void (*constructElement)(void*), void (*destroyElement)(void*)); jpayne@69: // Allocates and constructs the array. Both function pointers are null if the constructor is jpayne@69: // trivial, otherwise destroyElement is null if the constructor doesn't throw. jpayne@69: jpayne@69: virtual void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount, jpayne@69: size_t capacity, void (*destroyElement)(void*)) const override; jpayne@69: jpayne@69: template jpayne@69: struct Allocate_; jpayne@69: }; jpayne@69: jpayne@69: } // namespace _ (private) jpayne@69: jpayne@69: template jpayne@69: inline Array heapArray(size_t size) { jpayne@69: // Much like `heap()` from memory.h, allocates a new array on the heap. jpayne@69: jpayne@69: return Array(_::HeapArrayDisposer::allocate(size), size, jpayne@69: _::HeapArrayDisposer::instance); jpayne@69: } jpayne@69: jpayne@69: template Array heapArray(const T* content, size_t size); jpayne@69: template Array heapArray(ArrayPtr content); jpayne@69: template Array heapArray(ArrayPtr content); jpayne@69: template Array heapArray(Iterator begin, Iterator end); jpayne@69: template Array heapArray(std::initializer_list init); jpayne@69: // Allocate a heap array containing a copy of the given content. jpayne@69: jpayne@69: template jpayne@69: Array heapArrayFromIterable(Container&& a) { return heapArray(a.begin(), a.end()); } jpayne@69: template jpayne@69: Array heapArrayFromIterable(Array&& a) { return mv(a); } jpayne@69: jpayne@69: // ======================================================================================= jpayne@69: // ArrayBuilder jpayne@69: jpayne@69: template jpayne@69: class ArrayBuilder { jpayne@69: // Class which lets you build an Array specifying the exact constructor arguments for each jpayne@69: // element, rather than starting by default-constructing them. jpayne@69: jpayne@69: public: jpayne@69: ArrayBuilder(): ptr(nullptr), pos(nullptr), endPtr(nullptr) {} jpayne@69: ArrayBuilder(decltype(nullptr)): ptr(nullptr), pos(nullptr), endPtr(nullptr) {} jpayne@69: explicit ArrayBuilder(RemoveConst* firstElement, size_t capacity, jpayne@69: const ArrayDisposer& disposer) jpayne@69: : ptr(firstElement), pos(firstElement), endPtr(firstElement + capacity), jpayne@69: disposer(&disposer) {} jpayne@69: ArrayBuilder(ArrayBuilder&& other) jpayne@69: : ptr(other.ptr), pos(other.pos), endPtr(other.endPtr), disposer(other.disposer) { jpayne@69: other.ptr = nullptr; jpayne@69: other.pos = nullptr; jpayne@69: other.endPtr = nullptr; jpayne@69: } jpayne@69: ArrayBuilder(Array&& other) jpayne@69: : ptr(other.ptr), pos(other.ptr + other.size_), endPtr(pos), disposer(other.disposer) { jpayne@69: // Create an already-full ArrayBuilder from an Array of the same type. This constructor jpayne@69: // primarily exists to enable Vector to be constructed from Array. jpayne@69: other.ptr = nullptr; jpayne@69: other.size_ = 0; jpayne@69: } jpayne@69: KJ_DISALLOW_COPY(ArrayBuilder); jpayne@69: inline ~ArrayBuilder() noexcept(false) { dispose(); } jpayne@69: jpayne@69: inline operator ArrayPtr() KJ_LIFETIMEBOUND { jpayne@69: return arrayPtr(ptr, pos); jpayne@69: } jpayne@69: inline operator ArrayPtr() const KJ_LIFETIMEBOUND { jpayne@69: return arrayPtr(ptr, pos); jpayne@69: } jpayne@69: inline ArrayPtr asPtr() KJ_LIFETIMEBOUND { jpayne@69: return arrayPtr(ptr, pos); jpayne@69: } jpayne@69: inline ArrayPtr asPtr() const KJ_LIFETIMEBOUND { jpayne@69: return arrayPtr(ptr, pos); jpayne@69: } jpayne@69: jpayne@69: inline size_t size() const { return pos - ptr; } jpayne@69: inline size_t capacity() const { return endPtr - ptr; } jpayne@69: inline T& operator[](size_t index) KJ_LIFETIMEBOUND { jpayne@69: KJ_IREQUIRE(index < implicitCast(pos - ptr), "Out-of-bounds Array access."); jpayne@69: return ptr[index]; jpayne@69: } jpayne@69: inline const T& operator[](size_t index) const KJ_LIFETIMEBOUND { jpayne@69: KJ_IREQUIRE(index < implicitCast(pos - ptr), "Out-of-bounds Array access."); jpayne@69: return ptr[index]; jpayne@69: } jpayne@69: jpayne@69: inline const T* begin() const KJ_LIFETIMEBOUND { return ptr; } jpayne@69: inline const T* end() const KJ_LIFETIMEBOUND { return pos; } jpayne@69: inline const T& front() const KJ_LIFETIMEBOUND { return *ptr; } jpayne@69: inline const T& back() const KJ_LIFETIMEBOUND { return *(pos - 1); } jpayne@69: inline T* begin() KJ_LIFETIMEBOUND { return ptr; } jpayne@69: inline T* end() KJ_LIFETIMEBOUND { return pos; } jpayne@69: inline T& front() KJ_LIFETIMEBOUND { return *ptr; } jpayne@69: inline T& back() KJ_LIFETIMEBOUND { return *(pos - 1); } jpayne@69: jpayne@69: ArrayBuilder& operator=(ArrayBuilder&& other) { jpayne@69: dispose(); jpayne@69: ptr = other.ptr; jpayne@69: pos = other.pos; jpayne@69: endPtr = other.endPtr; jpayne@69: disposer = other.disposer; jpayne@69: other.ptr = nullptr; jpayne@69: other.pos = nullptr; jpayne@69: other.endPtr = nullptr; jpayne@69: return *this; jpayne@69: } jpayne@69: ArrayBuilder& operator=(decltype(nullptr)) { jpayne@69: dispose(); jpayne@69: return *this; jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: T& add(Params&&... params) KJ_LIFETIMEBOUND { jpayne@69: KJ_IREQUIRE(pos < endPtr, "Added too many elements to ArrayBuilder."); jpayne@69: ctor(*pos, kj::fwd(params)...); jpayne@69: return *pos++; jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: void addAll(Container&& container) { jpayne@69: addAll()>( jpayne@69: container.begin(), container.end()); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: void addAll(Iterator start, Iterator end); jpayne@69: jpayne@69: void removeLast() { jpayne@69: KJ_IREQUIRE(pos > ptr, "No elements present to remove."); jpayne@69: kj::dtor(*--pos); jpayne@69: } jpayne@69: jpayne@69: void truncate(size_t size) { jpayne@69: KJ_IREQUIRE(size <= this->size(), "can't use truncate() to expand"); jpayne@69: jpayne@69: T* target = ptr + size; jpayne@69: if (KJ_HAS_TRIVIAL_DESTRUCTOR(T)) { jpayne@69: pos = target; jpayne@69: } else { jpayne@69: while (pos > target) { jpayne@69: kj::dtor(*--pos); jpayne@69: } jpayne@69: } jpayne@69: } jpayne@69: jpayne@69: void clear() { jpayne@69: if (KJ_HAS_TRIVIAL_DESTRUCTOR(T)) { jpayne@69: pos = ptr; jpayne@69: } else { jpayne@69: while (pos > ptr) { jpayne@69: kj::dtor(*--pos); jpayne@69: } jpayne@69: } jpayne@69: } jpayne@69: jpayne@69: void resize(size_t size) { jpayne@69: KJ_IREQUIRE(size <= capacity(), "can't resize past capacity"); jpayne@69: jpayne@69: T* target = ptr + size; jpayne@69: if (target > pos) { jpayne@69: // expand jpayne@69: if (KJ_HAS_TRIVIAL_CONSTRUCTOR(T)) { jpayne@69: pos = target; jpayne@69: } else { jpayne@69: while (pos < target) { jpayne@69: kj::ctor(*pos++); jpayne@69: } jpayne@69: } jpayne@69: } else { jpayne@69: // truncate jpayne@69: if (KJ_HAS_TRIVIAL_DESTRUCTOR(T)) { jpayne@69: pos = target; jpayne@69: } else { jpayne@69: while (pos > target) { jpayne@69: kj::dtor(*--pos); jpayne@69: } jpayne@69: } jpayne@69: } jpayne@69: } jpayne@69: jpayne@69: Array finish() { jpayne@69: // We could safely remove this check if we assume that the disposer implementation doesn't jpayne@69: // need to know the original capacity, as is the case with HeapArrayDisposer since it uses jpayne@69: // operator new() or if we created a custom disposer for ArrayBuilder which stores the capacity jpayne@69: // in a prefix. But that would make it hard to write cleverer heap allocators, and anyway this jpayne@69: // check might catch bugs. Probably people should use Vector if they want to build arrays jpayne@69: // without knowing the final size in advance. jpayne@69: KJ_IREQUIRE(pos == endPtr, "ArrayBuilder::finish() called prematurely."); jpayne@69: Array result(reinterpret_cast(ptr), pos - ptr, *disposer); jpayne@69: ptr = nullptr; jpayne@69: pos = nullptr; jpayne@69: endPtr = nullptr; jpayne@69: return result; jpayne@69: } jpayne@69: jpayne@69: inline bool isFull() const { jpayne@69: return pos == endPtr; jpayne@69: } jpayne@69: jpayne@69: private: jpayne@69: T* ptr; jpayne@69: RemoveConst* pos; jpayne@69: T* endPtr; jpayne@69: const ArrayDisposer* disposer = &NullArrayDisposer::instance; jpayne@69: jpayne@69: inline void dispose() { jpayne@69: // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly jpayne@69: // dispose again. jpayne@69: T* ptrCopy = ptr; jpayne@69: T* posCopy = pos; jpayne@69: T* endCopy = endPtr; jpayne@69: if (ptrCopy != nullptr) { jpayne@69: ptr = nullptr; jpayne@69: pos = nullptr; jpayne@69: endPtr = nullptr; jpayne@69: disposer->dispose(ptrCopy, posCopy - ptrCopy, endCopy - ptrCopy); jpayne@69: } jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: inline ArrayBuilder heapArrayBuilder(size_t size) { jpayne@69: // Like `heapArray()` but does not default-construct the elements. You must construct them jpayne@69: // manually by calling `add()`. jpayne@69: jpayne@69: return ArrayBuilder(_::HeapArrayDisposer::allocateUninitialized>(size), jpayne@69: size, _::HeapArrayDisposer::instance); jpayne@69: } jpayne@69: jpayne@69: // ======================================================================================= jpayne@69: // Inline Arrays jpayne@69: jpayne@69: template jpayne@69: class FixedArray { jpayne@69: // A fixed-width array whose storage is allocated inline rather than on the heap. jpayne@69: jpayne@69: public: jpayne@69: inline constexpr size_t size() const { return fixedSize; } jpayne@69: inline constexpr T* begin() KJ_LIFETIMEBOUND { return content; } jpayne@69: inline constexpr T* end() KJ_LIFETIMEBOUND { return content + fixedSize; } jpayne@69: inline constexpr const T* begin() const KJ_LIFETIMEBOUND { return content; } jpayne@69: inline constexpr const T* end() const KJ_LIFETIMEBOUND { return content + fixedSize; } jpayne@69: jpayne@69: inline constexpr operator ArrayPtr() KJ_LIFETIMEBOUND { jpayne@69: return arrayPtr(content, fixedSize); jpayne@69: } jpayne@69: inline constexpr operator ArrayPtr() const KJ_LIFETIMEBOUND { jpayne@69: return arrayPtr(content, fixedSize); jpayne@69: } jpayne@69: jpayne@69: inline constexpr T& operator[](size_t index) KJ_LIFETIMEBOUND { return content[index]; } jpayne@69: inline constexpr const T& operator[](size_t index) const KJ_LIFETIMEBOUND { jpayne@69: return content[index]; jpayne@69: } jpayne@69: jpayne@69: private: jpayne@69: T content[fixedSize]; jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: class CappedArray { jpayne@69: // Like `FixedArray` but can be dynamically resized as long as the size does not exceed the limit jpayne@69: // specified by the template parameter. jpayne@69: // jpayne@69: // TODO(someday): Don't construct elements past currentSize? jpayne@69: jpayne@69: public: jpayne@69: inline KJ_CONSTEXPR() CappedArray(): currentSize(fixedSize) {} jpayne@69: inline explicit constexpr CappedArray(size_t s): currentSize(s) {} jpayne@69: jpayne@69: inline size_t size() const { return currentSize; } jpayne@69: inline void setSize(size_t s) { KJ_IREQUIRE(s <= fixedSize); currentSize = s; } jpayne@69: inline T* begin() KJ_LIFETIMEBOUND { return content; } jpayne@69: inline T* end() KJ_LIFETIMEBOUND { return content + currentSize; } jpayne@69: inline const T* begin() const KJ_LIFETIMEBOUND { return content; } jpayne@69: inline const T* end() const KJ_LIFETIMEBOUND { return content + currentSize; } jpayne@69: jpayne@69: inline operator ArrayPtr() KJ_LIFETIMEBOUND { jpayne@69: return arrayPtr(content, currentSize); jpayne@69: } jpayne@69: inline operator ArrayPtr() const KJ_LIFETIMEBOUND { jpayne@69: return arrayPtr(content, currentSize); jpayne@69: } jpayne@69: jpayne@69: inline T& operator[](size_t index) KJ_LIFETIMEBOUND { return content[index]; } jpayne@69: inline const T& operator[](size_t index) const KJ_LIFETIMEBOUND { return content[index]; } jpayne@69: jpayne@69: private: jpayne@69: size_t currentSize; jpayne@69: T content[fixedSize]; jpayne@69: }; jpayne@69: jpayne@69: // ======================================================================================= jpayne@69: // KJ_MAP jpayne@69: jpayne@69: #define KJ_MAP(elementName, array) \ jpayne@69: ::kj::_::Mapper(array) * \ jpayne@69: [&](typename ::kj::_::Mapper::Element elementName) jpayne@69: // Applies some function to every element of an array, returning an Array of the results, with jpayne@69: // nice syntax. Example: jpayne@69: // jpayne@69: // StringPtr foo = "abcd"; jpayne@69: // Array bar = KJ_MAP(c, foo) -> char { return c + 1; }; jpayne@69: // KJ_ASSERT(str(bar) == "bcde"); jpayne@69: jpayne@69: namespace _ { // private jpayne@69: jpayne@69: template jpayne@69: struct Mapper { jpayne@69: T array; jpayne@69: Mapper(T&& array): array(kj::fwd(array)) {} jpayne@69: template jpayne@69: auto operator*(Func&& func) -> Array { jpayne@69: auto builder = heapArrayBuilder(array.size()); jpayne@69: for (auto iter = array.begin(); iter != array.end(); ++iter) { jpayne@69: builder.add(func(*iter)); jpayne@69: } jpayne@69: return builder.finish(); jpayne@69: } jpayne@69: typedef decltype(*kj::instance().begin()) Element; jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: struct Mapper { jpayne@69: T* array; jpayne@69: Mapper(T* array): array(array) {} jpayne@69: template jpayne@69: auto operator*(Func&& func) -> Array { jpayne@69: auto builder = heapArrayBuilder(s); jpayne@69: for (size_t i = 0; i < s; i++) { jpayne@69: builder.add(func(array[i])); jpayne@69: } jpayne@69: return builder.finish(); jpayne@69: } jpayne@69: typedef decltype(*array)& Element; jpayne@69: }; jpayne@69: jpayne@69: } // namespace _ (private) jpayne@69: jpayne@69: // ======================================================================================= jpayne@69: // Inline implementation details jpayne@69: jpayne@69: template jpayne@69: struct ArrayDisposer::Dispose_ { jpayne@69: static void dispose(T* firstElement, size_t elementCount, size_t capacity, jpayne@69: const ArrayDisposer& disposer) { jpayne@69: disposer.disposeImpl(const_cast*>(firstElement), jpayne@69: sizeof(T), elementCount, capacity, nullptr); jpayne@69: } jpayne@69: }; jpayne@69: template jpayne@69: struct ArrayDisposer::Dispose_ { jpayne@69: static void destruct(void* ptr) { jpayne@69: kj::dtor(*reinterpret_cast(ptr)); jpayne@69: } jpayne@69: jpayne@69: static void dispose(T* firstElement, size_t elementCount, size_t capacity, jpayne@69: const ArrayDisposer& disposer) { jpayne@69: disposer.disposeImpl(const_cast*>(firstElement), jpayne@69: sizeof(T), elementCount, capacity, &destruct); jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: void ArrayDisposer::dispose(T* firstElement, size_t elementCount, size_t capacity) const { jpayne@69: Dispose_::dispose(firstElement, elementCount, capacity, *this); jpayne@69: } jpayne@69: jpayne@69: namespace _ { // private jpayne@69: jpayne@69: template jpayne@69: struct HeapArrayDisposer::Allocate_ { jpayne@69: static T* allocate(size_t elementCount, size_t capacity) { jpayne@69: return reinterpret_cast(allocateImpl( jpayne@69: sizeof(T), elementCount, capacity, nullptr, nullptr)); jpayne@69: } jpayne@69: }; jpayne@69: template jpayne@69: struct HeapArrayDisposer::Allocate_ { jpayne@69: static void construct(void* ptr) { jpayne@69: kj::ctor(*reinterpret_cast(ptr)); jpayne@69: } jpayne@69: static T* allocate(size_t elementCount, size_t capacity) { jpayne@69: return reinterpret_cast(allocateImpl( jpayne@69: sizeof(T), elementCount, capacity, &construct, nullptr)); jpayne@69: } jpayne@69: }; jpayne@69: template jpayne@69: struct HeapArrayDisposer::Allocate_ { jpayne@69: static void construct(void* ptr) { jpayne@69: kj::ctor(*reinterpret_cast(ptr)); jpayne@69: } jpayne@69: static void destruct(void* ptr) { jpayne@69: kj::dtor(*reinterpret_cast(ptr)); jpayne@69: } jpayne@69: static T* allocate(size_t elementCount, size_t capacity) { jpayne@69: return reinterpret_cast(allocateImpl( jpayne@69: sizeof(T), elementCount, capacity, &construct, &destruct)); jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: T* HeapArrayDisposer::allocate(size_t count) { jpayne@69: return Allocate_::allocate(count, count); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: T* HeapArrayDisposer::allocateUninitialized(size_t count) { jpayne@69: return Allocate_::allocate(0, count); jpayne@69: } jpayne@69: jpayne@69: template ()> jpayne@69: struct CopyConstructArray_; jpayne@69: jpayne@69: template jpayne@69: struct CopyConstructArray_ { jpayne@69: static inline T* apply(T* __restrict__ pos, T* start, T* end) { jpayne@69: if (end != start) { jpayne@69: memcpy(pos, start, reinterpret_cast(end) - reinterpret_cast(start)); jpayne@69: } jpayne@69: return pos + (end - start); jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: struct CopyConstructArray_ { jpayne@69: static inline T* apply(T* __restrict__ pos, const T* start, const T* end) { jpayne@69: if (end != start) { jpayne@69: memcpy(pos, start, reinterpret_cast(end) - reinterpret_cast(start)); jpayne@69: } jpayne@69: return pos + (end - start); jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: struct CopyConstructArray_ { jpayne@69: static inline T* apply(T* __restrict__ pos, Iterator start, Iterator end) { jpayne@69: // Since both the copy constructor and assignment operator are trivial, we know that assignment jpayne@69: // is equivalent to copy-constructing. So we can make this case somewhat easier for the jpayne@69: // compiler to optimize. jpayne@69: while (start != end) { jpayne@69: *pos++ = *start++; jpayne@69: } jpayne@69: return pos; jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: struct CopyConstructArray_ { jpayne@69: struct ExceptionGuard { jpayne@69: T* start; jpayne@69: T* pos; jpayne@69: inline explicit ExceptionGuard(T* pos): start(pos), pos(pos) {} jpayne@69: ~ExceptionGuard() noexcept(false) { jpayne@69: while (pos > start) { jpayne@69: dtor(*--pos); jpayne@69: } jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: static T* apply(T* __restrict__ pos, Iterator start, Iterator end) { jpayne@69: // Verify that T can be *implicitly* constructed from the source values. jpayne@69: if (false) implicitCast(*start); jpayne@69: jpayne@69: if (noexcept(T(*start))) { jpayne@69: while (start != end) { jpayne@69: ctor(*pos++, *start++); jpayne@69: } jpayne@69: return pos; jpayne@69: } else { jpayne@69: // Crap. This is complicated. jpayne@69: ExceptionGuard guard(pos); jpayne@69: while (start != end) { jpayne@69: ctor(*guard.pos, *start++); jpayne@69: ++guard.pos; jpayne@69: } jpayne@69: guard.start = guard.pos; jpayne@69: return guard.pos; jpayne@69: } jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: struct CopyConstructArray_ { jpayne@69: // Actually move-construct. jpayne@69: jpayne@69: struct ExceptionGuard { jpayne@69: T* start; jpayne@69: T* pos; jpayne@69: inline explicit ExceptionGuard(T* pos): start(pos), pos(pos) {} jpayne@69: ~ExceptionGuard() noexcept(false) { jpayne@69: while (pos > start) { jpayne@69: dtor(*--pos); jpayne@69: } jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: static T* apply(T* __restrict__ pos, Iterator start, Iterator end) { jpayne@69: // Verify that T can be *implicitly* constructed from the source values. jpayne@69: if (false) implicitCast(kj::mv(*start)); jpayne@69: jpayne@69: if (noexcept(T(kj::mv(*start)))) { jpayne@69: while (start != end) { jpayne@69: ctor(*pos++, kj::mv(*start++)); jpayne@69: } jpayne@69: return pos; jpayne@69: } else { jpayne@69: // Crap. This is complicated. jpayne@69: ExceptionGuard guard(pos); jpayne@69: while (start != end) { jpayne@69: ctor(*guard.pos, kj::mv(*start++)); jpayne@69: ++guard.pos; jpayne@69: } jpayne@69: guard.start = guard.pos; jpayne@69: return guard.pos; jpayne@69: } jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: } // namespace _ (private) jpayne@69: jpayne@69: template jpayne@69: template jpayne@69: void ArrayBuilder::addAll(Iterator start, Iterator end) { jpayne@69: pos = _::CopyConstructArray_, Decay, move>::apply(pos, start, end); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: Array heapArray(const T* content, size_t size) { jpayne@69: ArrayBuilder builder = heapArrayBuilder(size); jpayne@69: builder.addAll(content, content + size); jpayne@69: return builder.finish(); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: Array heapArray(T* content, size_t size) { jpayne@69: ArrayBuilder builder = heapArrayBuilder(size); jpayne@69: builder.addAll(content, content + size); jpayne@69: return builder.finish(); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: Array heapArray(ArrayPtr content) { jpayne@69: ArrayBuilder builder = heapArrayBuilder(content.size()); jpayne@69: builder.addAll(content); jpayne@69: return builder.finish(); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: Array heapArray(ArrayPtr content) { jpayne@69: ArrayBuilder builder = heapArrayBuilder(content.size()); jpayne@69: builder.addAll(content); jpayne@69: return builder.finish(); jpayne@69: } jpayne@69: jpayne@69: template Array jpayne@69: heapArray(Iterator begin, Iterator end) { jpayne@69: ArrayBuilder builder = heapArrayBuilder(end - begin); jpayne@69: builder.addAll(begin, end); jpayne@69: return builder.finish(); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: inline Array heapArray(std::initializer_list init) { jpayne@69: return heapArray(init.begin(), init.end()); jpayne@69: } jpayne@69: jpayne@69: #if KJ_CPP_STD > 201402L jpayne@69: template jpayne@69: inline Array> arr(T&& param1, Params&&... params) { jpayne@69: ArrayBuilder> builder = heapArrayBuilder>(sizeof...(params) + 1); jpayne@69: (builder.add(kj::fwd(param1)), ... , builder.add(kj::fwd(params))); jpayne@69: return builder.finish(); jpayne@69: } jpayne@69: template jpayne@69: inline Array> arrOf(Params&&... params) { jpayne@69: ArrayBuilder> builder = heapArrayBuilder>(sizeof...(params)); jpayne@69: (... , builder.add(kj::fwd(params))); jpayne@69: return builder.finish(); jpayne@69: } jpayne@69: #endif jpayne@69: jpayne@69: namespace _ { // private jpayne@69: jpayne@69: template jpayne@69: struct ArrayDisposableOwnedBundle final: public ArrayDisposer, public OwnedBundle { jpayne@69: ArrayDisposableOwnedBundle(T&&... values): OwnedBundle(kj::fwd(values)...) {} jpayne@69: void disposeImpl(void*, size_t, size_t, size_t, void (*)(void*)) const override { delete this; } jpayne@69: }; jpayne@69: jpayne@69: } // namespace _ (private) jpayne@69: jpayne@69: template jpayne@69: template jpayne@69: Array Array::attach(Attachments&&... attachments) { jpayne@69: T* ptrCopy = ptr; jpayne@69: auto sizeCopy = size_; jpayne@69: jpayne@69: KJ_IREQUIRE(ptrCopy != nullptr, "cannot attach to null pointer"); jpayne@69: jpayne@69: // HACK: If someone accidentally calls .attach() on a null pointer in opt mode, try our best to jpayne@69: // accomplish reasonable behavior: We turn the pointer non-null but still invalid, so that the jpayne@69: // disposer will still be called when the pointer goes out of scope. jpayne@69: if (ptrCopy == nullptr) ptrCopy = reinterpret_cast(1); jpayne@69: jpayne@69: auto bundle = new _::ArrayDisposableOwnedBundle, Attachments...>( jpayne@69: kj::mv(*this), kj::fwd(attachments)...); jpayne@69: return Array(ptrCopy, sizeCopy, *bundle); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: template jpayne@69: Array ArrayPtr::attach(Attachments&&... attachments) const { jpayne@69: T* ptrCopy = ptr; jpayne@69: jpayne@69: KJ_IREQUIRE(ptrCopy != nullptr, "cannot attach to null pointer"); jpayne@69: jpayne@69: // HACK: If someone accidentally calls .attach() on a null pointer in opt mode, try our best to jpayne@69: // accomplish reasonable behavior: We turn the pointer non-null but still invalid, so that the jpayne@69: // disposer will still be called when the pointer goes out of scope. jpayne@69: if (ptrCopy == nullptr) ptrCopy = reinterpret_cast(1); jpayne@69: jpayne@69: auto bundle = new _::ArrayDisposableOwnedBundle( jpayne@69: kj::fwd(attachments)...); jpayne@69: return Array(ptrCopy, size_, *bundle); jpayne@69: } jpayne@69: jpayne@69: } // namespace kj jpayne@69: jpayne@69: KJ_END_HEADER