annotate osx/include/kj/array.h @ 169:223a55898ab9 tip default

Add null config files
author Chris Cannam <cannam@all-day-breakfast.com>
date Mon, 02 Mar 2020 14:03:47 +0000
parents 45360b968bf4
children
rev   line source
cannam@147 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
cannam@147 2 // Licensed under the MIT License:
cannam@147 3 //
cannam@147 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
cannam@147 5 // of this software and associated documentation files (the "Software"), to deal
cannam@147 6 // in the Software without restriction, including without limitation the rights
cannam@147 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
cannam@147 8 // copies of the Software, and to permit persons to whom the Software is
cannam@147 9 // furnished to do so, subject to the following conditions:
cannam@147 10 //
cannam@147 11 // The above copyright notice and this permission notice shall be included in
cannam@147 12 // all copies or substantial portions of the Software.
cannam@147 13 //
cannam@147 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
cannam@147 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
cannam@147 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
cannam@147 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
cannam@147 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
cannam@147 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
cannam@147 20 // THE SOFTWARE.
cannam@147 21
cannam@147 22 #ifndef KJ_ARRAY_H_
cannam@147 23 #define KJ_ARRAY_H_
cannam@147 24
cannam@147 25 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
cannam@147 26 #pragma GCC system_header
cannam@147 27 #endif
cannam@147 28
cannam@147 29 #include "common.h"
cannam@147 30 #include <string.h>
cannam@147 31 #include <initializer_list>
cannam@147 32
cannam@147 33 namespace kj {
cannam@147 34
cannam@147 35 // =======================================================================================
cannam@147 36 // ArrayDisposer -- Implementation details.
cannam@147 37
cannam@147 38 class ArrayDisposer {
cannam@147 39 // Much like Disposer from memory.h.
cannam@147 40
cannam@147 41 protected:
cannam@147 42 // Do not declare a destructor, as doing so will force a global initializer for
cannam@147 43 // HeapArrayDisposer::instance.
cannam@147 44
cannam@147 45 virtual void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount,
cannam@147 46 size_t capacity, void (*destroyElement)(void*)) const = 0;
cannam@147 47 // Disposes of the array. `destroyElement` invokes the destructor of each element, or is nullptr
cannam@147 48 // if the elements have trivial destructors. `capacity` is the amount of space that was
cannam@147 49 // allocated while `elementCount` is the number of elements that were actually constructed;
cannam@147 50 // these are always the same number for Array<T> but may be different when using ArrayBuilder<T>.
cannam@147 51
cannam@147 52 public:
cannam@147 53
cannam@147 54 template <typename T>
cannam@147 55 void dispose(T* firstElement, size_t elementCount, size_t capacity) const;
cannam@147 56 // Helper wrapper around disposeImpl().
cannam@147 57 //
cannam@147 58 // Callers must not call dispose() on the same array twice, even if the first call throws
cannam@147 59 // an exception.
cannam@147 60
cannam@147 61 private:
cannam@147 62 template <typename T, bool hasTrivialDestructor = __has_trivial_destructor(T)>
cannam@147 63 struct Dispose_;
cannam@147 64 };
cannam@147 65
cannam@147 66 class ExceptionSafeArrayUtil {
cannam@147 67 // Utility class that assists in constructing or destroying elements of an array, where the
cannam@147 68 // constructor or destructor could throw exceptions. In case of an exception,
cannam@147 69 // ExceptionSafeArrayUtil's destructor will call destructors on all elements that have been
cannam@147 70 // constructed but not destroyed. Remember that destructors that throw exceptions are required
cannam@147 71 // to use UnwindDetector to detect unwind and avoid exceptions in this case. Therefore, no more
cannam@147 72 // than one exception will be thrown (and the program will not terminate).
cannam@147 73
cannam@147 74 public:
cannam@147 75 inline ExceptionSafeArrayUtil(void* ptr, size_t elementSize, size_t constructedElementCount,
cannam@147 76 void (*destroyElement)(void*))
cannam@147 77 : pos(reinterpret_cast<byte*>(ptr) + elementSize * constructedElementCount),
cannam@147 78 elementSize(elementSize), constructedElementCount(constructedElementCount),
cannam@147 79 destroyElement(destroyElement) {}
cannam@147 80 KJ_DISALLOW_COPY(ExceptionSafeArrayUtil);
cannam@147 81
cannam@147 82 inline ~ExceptionSafeArrayUtil() noexcept(false) {
cannam@147 83 if (constructedElementCount > 0) destroyAll();
cannam@147 84 }
cannam@147 85
cannam@147 86 void construct(size_t count, void (*constructElement)(void*));
cannam@147 87 // Construct the given number of elements.
cannam@147 88
cannam@147 89 void destroyAll();
cannam@147 90 // Destroy all elements. Call this immediately before ExceptionSafeArrayUtil goes out-of-scope
cannam@147 91 // to ensure that one element throwing an exception does not prevent the others from being
cannam@147 92 // destroyed.
cannam@147 93
cannam@147 94 void release() { constructedElementCount = 0; }
cannam@147 95 // Prevent ExceptionSafeArrayUtil's destructor from destroying the constructed elements.
cannam@147 96 // Call this after you've successfully finished constructing.
cannam@147 97
cannam@147 98 private:
cannam@147 99 byte* pos;
cannam@147 100 size_t elementSize;
cannam@147 101 size_t constructedElementCount;
cannam@147 102 void (*destroyElement)(void*);
cannam@147 103 };
cannam@147 104
cannam@147 105 class DestructorOnlyArrayDisposer: public ArrayDisposer {
cannam@147 106 public:
cannam@147 107 static const DestructorOnlyArrayDisposer instance;
cannam@147 108
cannam@147 109 void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount,
cannam@147 110 size_t capacity, void (*destroyElement)(void*)) const override;
cannam@147 111 };
cannam@147 112
cannam@147 113 class NullArrayDisposer: public ArrayDisposer {
cannam@147 114 // An ArrayDisposer that does nothing. Can be used to construct a fake Arrays that doesn't
cannam@147 115 // actually own its content.
cannam@147 116
cannam@147 117 public:
cannam@147 118 static const NullArrayDisposer instance;
cannam@147 119
cannam@147 120 void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount,
cannam@147 121 size_t capacity, void (*destroyElement)(void*)) const override;
cannam@147 122 };
cannam@147 123
cannam@147 124 // =======================================================================================
cannam@147 125 // Array
cannam@147 126
cannam@147 127 template <typename T>
cannam@147 128 class Array {
cannam@147 129 // An owned array which will automatically be disposed of (using an ArrayDisposer) in the
cannam@147 130 // destructor. Can be moved, but not copied. Much like Own<T>, but for arrays rather than
cannam@147 131 // single objects.
cannam@147 132
cannam@147 133 public:
cannam@147 134 inline Array(): ptr(nullptr), size_(0), disposer(nullptr) {}
cannam@147 135 inline Array(decltype(nullptr)): ptr(nullptr), size_(0), disposer(nullptr) {}
cannam@147 136 inline Array(Array&& other) noexcept
cannam@147 137 : ptr(other.ptr), size_(other.size_), disposer(other.disposer) {
cannam@147 138 other.ptr = nullptr;
cannam@147 139 other.size_ = 0;
cannam@147 140 }
cannam@147 141 inline Array(Array<RemoveConstOrDisable<T>>&& other) noexcept
cannam@147 142 : ptr(other.ptr), size_(other.size_), disposer(other.disposer) {
cannam@147 143 other.ptr = nullptr;
cannam@147 144 other.size_ = 0;
cannam@147 145 }
cannam@147 146 inline Array(T* firstElement, size_t size, const ArrayDisposer& disposer)
cannam@147 147 : ptr(firstElement), size_(size), disposer(&disposer) {}
cannam@147 148
cannam@147 149 KJ_DISALLOW_COPY(Array);
cannam@147 150 inline ~Array() noexcept { dispose(); }
cannam@147 151
cannam@147 152 inline operator ArrayPtr<T>() {
cannam@147 153 return ArrayPtr<T>(ptr, size_);
cannam@147 154 }
cannam@147 155 inline operator ArrayPtr<const T>() const {
cannam@147 156 return ArrayPtr<T>(ptr, size_);
cannam@147 157 }
cannam@147 158 inline ArrayPtr<T> asPtr() {
cannam@147 159 return ArrayPtr<T>(ptr, size_);
cannam@147 160 }
cannam@147 161 inline ArrayPtr<const T> asPtr() const {
cannam@147 162 return ArrayPtr<T>(ptr, size_);
cannam@147 163 }
cannam@147 164
cannam@147 165 inline size_t size() const { return size_; }
cannam@147 166 inline T& operator[](size_t index) const {
cannam@147 167 KJ_IREQUIRE(index < size_, "Out-of-bounds Array access.");
cannam@147 168 return ptr[index];
cannam@147 169 }
cannam@147 170
cannam@147 171 inline const T* begin() const { return ptr; }
cannam@147 172 inline const T* end() const { return ptr + size_; }
cannam@147 173 inline const T& front() const { return *ptr; }
cannam@147 174 inline const T& back() const { return *(ptr + size_ - 1); }
cannam@147 175 inline T* begin() { return ptr; }
cannam@147 176 inline T* end() { return ptr + size_; }
cannam@147 177 inline T& front() { return *ptr; }
cannam@147 178 inline T& back() { return *(ptr + size_ - 1); }
cannam@147 179
cannam@147 180 inline ArrayPtr<T> slice(size_t start, size_t end) {
cannam@147 181 KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds Array::slice().");
cannam@147 182 return ArrayPtr<T>(ptr + start, end - start);
cannam@147 183 }
cannam@147 184 inline ArrayPtr<const T> slice(size_t start, size_t end) const {
cannam@147 185 KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds Array::slice().");
cannam@147 186 return ArrayPtr<const T>(ptr + start, end - start);
cannam@147 187 }
cannam@147 188
cannam@147 189 inline ArrayPtr<const byte> asBytes() const { return asPtr().asBytes(); }
cannam@147 190 inline ArrayPtr<PropagateConst<T, byte>> asBytes() { return asPtr().asBytes(); }
cannam@147 191 inline ArrayPtr<const char> asChars() const { return asPtr().asChars(); }
cannam@147 192 inline ArrayPtr<PropagateConst<T, char>> asChars() { return asPtr().asChars(); }
cannam@147 193
cannam@147 194 inline Array<PropagateConst<T, byte>> releaseAsBytes() {
cannam@147 195 // Like asBytes() but transfers ownership.
cannam@147 196 static_assert(sizeof(T) == sizeof(byte),
cannam@147 197 "releaseAsBytes() only possible on arrays with byte-size elements (e.g. chars).");
cannam@147 198 Array<PropagateConst<T, byte>> result(
cannam@147 199 reinterpret_cast<PropagateConst<T, byte>*>(ptr), size_, *disposer);
cannam@147 200 ptr = nullptr;
cannam@147 201 size_ = 0;
cannam@147 202 return result;
cannam@147 203 }
cannam@147 204 inline Array<PropagateConst<T, char>> releaseAsChars() {
cannam@147 205 // Like asChars() but transfers ownership.
cannam@147 206 static_assert(sizeof(T) == sizeof(PropagateConst<T, char>),
cannam@147 207 "releaseAsChars() only possible on arrays with char-size elements (e.g. bytes).");
cannam@147 208 Array<PropagateConst<T, char>> result(
cannam@147 209 reinterpret_cast<PropagateConst<T, char>*>(ptr), size_, *disposer);
cannam@147 210 ptr = nullptr;
cannam@147 211 size_ = 0;
cannam@147 212 return result;
cannam@147 213 }
cannam@147 214
cannam@147 215 inline bool operator==(decltype(nullptr)) const { return size_ == 0; }
cannam@147 216 inline bool operator!=(decltype(nullptr)) const { return size_ != 0; }
cannam@147 217
cannam@147 218 inline Array& operator=(decltype(nullptr)) {
cannam@147 219 dispose();
cannam@147 220 return *this;
cannam@147 221 }
cannam@147 222
cannam@147 223 inline Array& operator=(Array&& other) {
cannam@147 224 dispose();
cannam@147 225 ptr = other.ptr;
cannam@147 226 size_ = other.size_;
cannam@147 227 disposer = other.disposer;
cannam@147 228 other.ptr = nullptr;
cannam@147 229 other.size_ = 0;
cannam@147 230 return *this;
cannam@147 231 }
cannam@147 232
cannam@147 233 private:
cannam@147 234 T* ptr;
cannam@147 235 size_t size_;
cannam@147 236 const ArrayDisposer* disposer;
cannam@147 237
cannam@147 238 inline void dispose() {
cannam@147 239 // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly
cannam@147 240 // dispose again.
cannam@147 241 T* ptrCopy = ptr;
cannam@147 242 size_t sizeCopy = size_;
cannam@147 243 if (ptrCopy != nullptr) {
cannam@147 244 ptr = nullptr;
cannam@147 245 size_ = 0;
cannam@147 246 disposer->dispose(ptrCopy, sizeCopy, sizeCopy);
cannam@147 247 }
cannam@147 248 }
cannam@147 249
cannam@147 250 template <typename U>
cannam@147 251 friend class Array;
cannam@147 252 };
cannam@147 253
cannam@147 254 static_assert(!canMemcpy<Array<char>>(), "canMemcpy<>() is broken");
cannam@147 255
cannam@147 256 namespace _ { // private
cannam@147 257
cannam@147 258 class HeapArrayDisposer final: public ArrayDisposer {
cannam@147 259 public:
cannam@147 260 template <typename T>
cannam@147 261 static T* allocate(size_t count);
cannam@147 262 template <typename T>
cannam@147 263 static T* allocateUninitialized(size_t count);
cannam@147 264
cannam@147 265 static const HeapArrayDisposer instance;
cannam@147 266
cannam@147 267 private:
cannam@147 268 static void* allocateImpl(size_t elementSize, size_t elementCount, size_t capacity,
cannam@147 269 void (*constructElement)(void*), void (*destroyElement)(void*));
cannam@147 270 // Allocates and constructs the array. Both function pointers are null if the constructor is
cannam@147 271 // trivial, otherwise destroyElement is null if the constructor doesn't throw.
cannam@147 272
cannam@147 273 virtual void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount,
cannam@147 274 size_t capacity, void (*destroyElement)(void*)) const override;
cannam@147 275
cannam@147 276 template <typename T, bool hasTrivialConstructor = __has_trivial_constructor(T),
cannam@147 277 bool hasNothrowConstructor = __has_nothrow_constructor(T)>
cannam@147 278 struct Allocate_;
cannam@147 279 };
cannam@147 280
cannam@147 281 } // namespace _ (private)
cannam@147 282
cannam@147 283 template <typename T>
cannam@147 284 inline Array<T> heapArray(size_t size) {
cannam@147 285 // Much like `heap<T>()` from memory.h, allocates a new array on the heap.
cannam@147 286
cannam@147 287 return Array<T>(_::HeapArrayDisposer::allocate<T>(size), size,
cannam@147 288 _::HeapArrayDisposer::instance);
cannam@147 289 }
cannam@147 290
cannam@147 291 template <typename T> Array<T> heapArray(const T* content, size_t size);
cannam@147 292 template <typename T> Array<T> heapArray(ArrayPtr<T> content);
cannam@147 293 template <typename T> Array<T> heapArray(ArrayPtr<const T> content);
cannam@147 294 template <typename T, typename Iterator> Array<T> heapArray(Iterator begin, Iterator end);
cannam@147 295 template <typename T> Array<T> heapArray(std::initializer_list<T> init);
cannam@147 296 // Allocate a heap array containing a copy of the given content.
cannam@147 297
cannam@147 298 template <typename T, typename Container>
cannam@147 299 Array<T> heapArrayFromIterable(Container&& a) { return heapArray<T>(a.begin(), a.end()); }
cannam@147 300 template <typename T>
cannam@147 301 Array<T> heapArrayFromIterable(Array<T>&& a) { return mv(a); }
cannam@147 302
cannam@147 303 // =======================================================================================
cannam@147 304 // ArrayBuilder
cannam@147 305
cannam@147 306 template <typename T>
cannam@147 307 class ArrayBuilder {
cannam@147 308 // Class which lets you build an Array<T> specifying the exact constructor arguments for each
cannam@147 309 // element, rather than starting by default-constructing them.
cannam@147 310
cannam@147 311 public:
cannam@147 312 ArrayBuilder(): ptr(nullptr), pos(nullptr), endPtr(nullptr) {}
cannam@147 313 ArrayBuilder(decltype(nullptr)): ptr(nullptr), pos(nullptr), endPtr(nullptr) {}
cannam@147 314 explicit ArrayBuilder(RemoveConst<T>* firstElement, size_t capacity,
cannam@147 315 const ArrayDisposer& disposer)
cannam@147 316 : ptr(firstElement), pos(firstElement), endPtr(firstElement + capacity),
cannam@147 317 disposer(&disposer) {}
cannam@147 318 ArrayBuilder(ArrayBuilder&& other)
cannam@147 319 : ptr(other.ptr), pos(other.pos), endPtr(other.endPtr), disposer(other.disposer) {
cannam@147 320 other.ptr = nullptr;
cannam@147 321 other.pos = nullptr;
cannam@147 322 other.endPtr = nullptr;
cannam@147 323 }
cannam@147 324 KJ_DISALLOW_COPY(ArrayBuilder);
cannam@147 325 inline ~ArrayBuilder() noexcept(false) { dispose(); }
cannam@147 326
cannam@147 327 inline operator ArrayPtr<T>() {
cannam@147 328 return arrayPtr(ptr, pos);
cannam@147 329 }
cannam@147 330 inline operator ArrayPtr<const T>() const {
cannam@147 331 return arrayPtr(ptr, pos);
cannam@147 332 }
cannam@147 333 inline ArrayPtr<T> asPtr() {
cannam@147 334 return arrayPtr(ptr, pos);
cannam@147 335 }
cannam@147 336 inline ArrayPtr<const T> asPtr() const {
cannam@147 337 return arrayPtr(ptr, pos);
cannam@147 338 }
cannam@147 339
cannam@147 340 inline size_t size() const { return pos - ptr; }
cannam@147 341 inline size_t capacity() const { return endPtr - ptr; }
cannam@147 342 inline T& operator[](size_t index) const {
cannam@147 343 KJ_IREQUIRE(index < implicitCast<size_t>(pos - ptr), "Out-of-bounds Array access.");
cannam@147 344 return ptr[index];
cannam@147 345 }
cannam@147 346
cannam@147 347 inline const T* begin() const { return ptr; }
cannam@147 348 inline const T* end() const { return pos; }
cannam@147 349 inline const T& front() const { return *ptr; }
cannam@147 350 inline const T& back() const { return *(pos - 1); }
cannam@147 351 inline T* begin() { return ptr; }
cannam@147 352 inline T* end() { return pos; }
cannam@147 353 inline T& front() { return *ptr; }
cannam@147 354 inline T& back() { return *(pos - 1); }
cannam@147 355
cannam@147 356 ArrayBuilder& operator=(ArrayBuilder&& other) {
cannam@147 357 dispose();
cannam@147 358 ptr = other.ptr;
cannam@147 359 pos = other.pos;
cannam@147 360 endPtr = other.endPtr;
cannam@147 361 disposer = other.disposer;
cannam@147 362 other.ptr = nullptr;
cannam@147 363 other.pos = nullptr;
cannam@147 364 other.endPtr = nullptr;
cannam@147 365 return *this;
cannam@147 366 }
cannam@147 367 ArrayBuilder& operator=(decltype(nullptr)) {
cannam@147 368 dispose();
cannam@147 369 return *this;
cannam@147 370 }
cannam@147 371
cannam@147 372 template <typename... Params>
cannam@147 373 T& add(Params&&... params) {
cannam@147 374 KJ_IREQUIRE(pos < endPtr, "Added too many elements to ArrayBuilder.");
cannam@147 375 ctor(*pos, kj::fwd<Params>(params)...);
cannam@147 376 return *pos++;
cannam@147 377 }
cannam@147 378
cannam@147 379 template <typename Container>
cannam@147 380 void addAll(Container&& container) {
cannam@147 381 addAll<decltype(container.begin()), !isReference<Container>()>(
cannam@147 382 container.begin(), container.end());
cannam@147 383 }
cannam@147 384
cannam@147 385 template <typename Iterator, bool move = false>
cannam@147 386 void addAll(Iterator start, Iterator end);
cannam@147 387
cannam@147 388 void removeLast() {
cannam@147 389 KJ_IREQUIRE(pos > ptr, "No elements present to remove.");
cannam@147 390 kj::dtor(*--pos);
cannam@147 391 }
cannam@147 392
cannam@147 393 void truncate(size_t size) {
cannam@147 394 KJ_IREQUIRE(size <= this->size(), "can't use truncate() to expand");
cannam@147 395
cannam@147 396 T* target = ptr + size;
cannam@147 397 if (__has_trivial_destructor(T)) {
cannam@147 398 pos = target;
cannam@147 399 } else {
cannam@147 400 while (pos > target) {
cannam@147 401 kj::dtor(*--pos);
cannam@147 402 }
cannam@147 403 }
cannam@147 404 }
cannam@147 405
cannam@147 406 void resize(size_t size) {
cannam@147 407 KJ_IREQUIRE(size <= capacity(), "can't resize past capacity");
cannam@147 408
cannam@147 409 T* target = ptr + size;
cannam@147 410 if (target > pos) {
cannam@147 411 // expand
cannam@147 412 if (__has_trivial_constructor(T)) {
cannam@147 413 pos = target;
cannam@147 414 } else {
cannam@147 415 while (pos < target) {
cannam@147 416 kj::ctor(*pos++);
cannam@147 417 }
cannam@147 418 }
cannam@147 419 } else {
cannam@147 420 // truncate
cannam@147 421 if (__has_trivial_destructor(T)) {
cannam@147 422 pos = target;
cannam@147 423 } else {
cannam@147 424 while (pos > target) {
cannam@147 425 kj::dtor(*--pos);
cannam@147 426 }
cannam@147 427 }
cannam@147 428 }
cannam@147 429 }
cannam@147 430
cannam@147 431 Array<T> finish() {
cannam@147 432 // We could safely remove this check if we assume that the disposer implementation doesn't
cannam@147 433 // need to know the original capacity, as is thes case with HeapArrayDisposer since it uses
cannam@147 434 // operator new() or if we created a custom disposer for ArrayBuilder which stores the capacity
cannam@147 435 // in a prefix. But that would make it hard to write cleverer heap allocators, and anyway this
cannam@147 436 // check might catch bugs. Probably people should use Vector if they want to build arrays
cannam@147 437 // without knowing the final size in advance.
cannam@147 438 KJ_IREQUIRE(pos == endPtr, "ArrayBuilder::finish() called prematurely.");
cannam@147 439 Array<T> result(reinterpret_cast<T*>(ptr), pos - ptr, *disposer);
cannam@147 440 ptr = nullptr;
cannam@147 441 pos = nullptr;
cannam@147 442 endPtr = nullptr;
cannam@147 443 return result;
cannam@147 444 }
cannam@147 445
cannam@147 446 inline bool isFull() const {
cannam@147 447 return pos == endPtr;
cannam@147 448 }
cannam@147 449
cannam@147 450 private:
cannam@147 451 T* ptr;
cannam@147 452 RemoveConst<T>* pos;
cannam@147 453 T* endPtr;
cannam@147 454 const ArrayDisposer* disposer;
cannam@147 455
cannam@147 456 inline void dispose() {
cannam@147 457 // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly
cannam@147 458 // dispose again.
cannam@147 459 T* ptrCopy = ptr;
cannam@147 460 T* posCopy = pos;
cannam@147 461 T* endCopy = endPtr;
cannam@147 462 if (ptrCopy != nullptr) {
cannam@147 463 ptr = nullptr;
cannam@147 464 pos = nullptr;
cannam@147 465 endPtr = nullptr;
cannam@147 466 disposer->dispose(ptrCopy, posCopy - ptrCopy, endCopy - ptrCopy);
cannam@147 467 }
cannam@147 468 }
cannam@147 469 };
cannam@147 470
cannam@147 471 template <typename T>
cannam@147 472 inline ArrayBuilder<T> heapArrayBuilder(size_t size) {
cannam@147 473 // Like `heapArray<T>()` but does not default-construct the elements. You must construct them
cannam@147 474 // manually by calling `add()`.
cannam@147 475
cannam@147 476 return ArrayBuilder<T>(_::HeapArrayDisposer::allocateUninitialized<RemoveConst<T>>(size),
cannam@147 477 size, _::HeapArrayDisposer::instance);
cannam@147 478 }
cannam@147 479
cannam@147 480 // =======================================================================================
cannam@147 481 // Inline Arrays
cannam@147 482
cannam@147 483 template <typename T, size_t fixedSize>
cannam@147 484 class FixedArray {
cannam@147 485 // A fixed-width array whose storage is allocated inline rather than on the heap.
cannam@147 486
cannam@147 487 public:
cannam@147 488 inline size_t size() const { return fixedSize; }
cannam@147 489 inline T* begin() { return content; }
cannam@147 490 inline T* end() { return content + fixedSize; }
cannam@147 491 inline const T* begin() const { return content; }
cannam@147 492 inline const T* end() const { return content + fixedSize; }
cannam@147 493
cannam@147 494 inline operator ArrayPtr<T>() {
cannam@147 495 return arrayPtr(content, fixedSize);
cannam@147 496 }
cannam@147 497 inline operator ArrayPtr<const T>() const {
cannam@147 498 return arrayPtr(content, fixedSize);
cannam@147 499 }
cannam@147 500
cannam@147 501 inline T& operator[](size_t index) { return content[index]; }
cannam@147 502 inline const T& operator[](size_t index) const { return content[index]; }
cannam@147 503
cannam@147 504 private:
cannam@147 505 T content[fixedSize];
cannam@147 506 };
cannam@147 507
cannam@147 508 template <typename T, size_t fixedSize>
cannam@147 509 class CappedArray {
cannam@147 510 // Like `FixedArray` but can be dynamically resized as long as the size does not exceed the limit
cannam@147 511 // specified by the template parameter.
cannam@147 512 //
cannam@147 513 // TODO(someday): Don't construct elements past currentSize?
cannam@147 514
cannam@147 515 public:
cannam@147 516 inline KJ_CONSTEXPR() CappedArray(): currentSize(fixedSize) {}
cannam@147 517 inline explicit constexpr CappedArray(size_t s): currentSize(s) {}
cannam@147 518
cannam@147 519 inline size_t size() const { return currentSize; }
cannam@147 520 inline void setSize(size_t s) { KJ_IREQUIRE(s <= fixedSize); currentSize = s; }
cannam@147 521 inline T* begin() { return content; }
cannam@147 522 inline T* end() { return content + currentSize; }
cannam@147 523 inline const T* begin() const { return content; }
cannam@147 524 inline const T* end() const { return content + currentSize; }
cannam@147 525
cannam@147 526 inline operator ArrayPtr<T>() {
cannam@147 527 return arrayPtr(content, currentSize);
cannam@147 528 }
cannam@147 529 inline operator ArrayPtr<const T>() const {
cannam@147 530 return arrayPtr(content, currentSize);
cannam@147 531 }
cannam@147 532
cannam@147 533 inline T& operator[](size_t index) { return content[index]; }
cannam@147 534 inline const T& operator[](size_t index) const { return content[index]; }
cannam@147 535
cannam@147 536 private:
cannam@147 537 size_t currentSize;
cannam@147 538 T content[fixedSize];
cannam@147 539 };
cannam@147 540
cannam@147 541 // =======================================================================================
cannam@147 542 // KJ_MAP
cannam@147 543
cannam@147 544 #define KJ_MAP(elementName, array) \
cannam@147 545 ::kj::_::Mapper<KJ_DECLTYPE_REF(array)>(array) * \
cannam@147 546 [&](typename ::kj::_::Mapper<KJ_DECLTYPE_REF(array)>::Element elementName)
cannam@147 547 // Applies some function to every element of an array, returning an Array of the results, with
cannam@147 548 // nice syntax. Example:
cannam@147 549 //
cannam@147 550 // StringPtr foo = "abcd";
cannam@147 551 // Array<char> bar = KJ_MAP(c, foo) -> char { return c + 1; };
cannam@147 552 // KJ_ASSERT(str(bar) == "bcde");
cannam@147 553
cannam@147 554 namespace _ { // private
cannam@147 555
cannam@147 556 template <typename T>
cannam@147 557 struct Mapper {
cannam@147 558 T array;
cannam@147 559 Mapper(T&& array): array(kj::fwd<T>(array)) {}
cannam@147 560 template <typename Func>
cannam@147 561 auto operator*(Func&& func) -> Array<decltype(func(*array.begin()))> {
cannam@147 562 auto builder = heapArrayBuilder<decltype(func(*array.begin()))>(array.size());
cannam@147 563 for (auto iter = array.begin(); iter != array.end(); ++iter) {
cannam@147 564 builder.add(func(*iter));
cannam@147 565 }
cannam@147 566 return builder.finish();
cannam@147 567 }
cannam@147 568 typedef decltype(*kj::instance<T>().begin()) Element;
cannam@147 569 };
cannam@147 570
cannam@147 571 template <typename T, size_t s>
cannam@147 572 struct Mapper<T(&)[s]> {
cannam@147 573 T* array;
cannam@147 574 Mapper(T* array): array(array) {}
cannam@147 575 template <typename Func>
cannam@147 576 auto operator*(Func&& func) -> Array<decltype(func(*array))> {
cannam@147 577 auto builder = heapArrayBuilder<decltype(func(*array))>(s);
cannam@147 578 for (size_t i = 0; i < s; i++) {
cannam@147 579 builder.add(func(array[i]));
cannam@147 580 }
cannam@147 581 return builder.finish();
cannam@147 582 }
cannam@147 583 typedef decltype(*array)& Element;
cannam@147 584 };
cannam@147 585
cannam@147 586 } // namespace _ (private)
cannam@147 587
cannam@147 588 // =======================================================================================
cannam@147 589 // Inline implementation details
cannam@147 590
cannam@147 591 template <typename T>
cannam@147 592 struct ArrayDisposer::Dispose_<T, true> {
cannam@147 593 static void dispose(T* firstElement, size_t elementCount, size_t capacity,
cannam@147 594 const ArrayDisposer& disposer) {
cannam@147 595 disposer.disposeImpl(const_cast<RemoveConst<T>*>(firstElement),
cannam@147 596 sizeof(T), elementCount, capacity, nullptr);
cannam@147 597 }
cannam@147 598 };
cannam@147 599 template <typename T>
cannam@147 600 struct ArrayDisposer::Dispose_<T, false> {
cannam@147 601 static void destruct(void* ptr) {
cannam@147 602 kj::dtor(*reinterpret_cast<T*>(ptr));
cannam@147 603 }
cannam@147 604
cannam@147 605 static void dispose(T* firstElement, size_t elementCount, size_t capacity,
cannam@147 606 const ArrayDisposer& disposer) {
cannam@147 607 disposer.disposeImpl(firstElement, sizeof(T), elementCount, capacity, &destruct);
cannam@147 608 }
cannam@147 609 };
cannam@147 610
cannam@147 611 template <typename T>
cannam@147 612 void ArrayDisposer::dispose(T* firstElement, size_t elementCount, size_t capacity) const {
cannam@147 613 Dispose_<T>::dispose(firstElement, elementCount, capacity, *this);
cannam@147 614 }
cannam@147 615
cannam@147 616 namespace _ { // private
cannam@147 617
cannam@147 618 template <typename T>
cannam@147 619 struct HeapArrayDisposer::Allocate_<T, true, true> {
cannam@147 620 static T* allocate(size_t elementCount, size_t capacity) {
cannam@147 621 return reinterpret_cast<T*>(allocateImpl(
cannam@147 622 sizeof(T), elementCount, capacity, nullptr, nullptr));
cannam@147 623 }
cannam@147 624 };
cannam@147 625 template <typename T>
cannam@147 626 struct HeapArrayDisposer::Allocate_<T, false, true> {
cannam@147 627 static void construct(void* ptr) {
cannam@147 628 kj::ctor(*reinterpret_cast<T*>(ptr));
cannam@147 629 }
cannam@147 630 static T* allocate(size_t elementCount, size_t capacity) {
cannam@147 631 return reinterpret_cast<T*>(allocateImpl(
cannam@147 632 sizeof(T), elementCount, capacity, &construct, nullptr));
cannam@147 633 }
cannam@147 634 };
cannam@147 635 template <typename T>
cannam@147 636 struct HeapArrayDisposer::Allocate_<T, false, false> {
cannam@147 637 static void construct(void* ptr) {
cannam@147 638 kj::ctor(*reinterpret_cast<T*>(ptr));
cannam@147 639 }
cannam@147 640 static void destruct(void* ptr) {
cannam@147 641 kj::dtor(*reinterpret_cast<T*>(ptr));
cannam@147 642 }
cannam@147 643 static T* allocate(size_t elementCount, size_t capacity) {
cannam@147 644 return reinterpret_cast<T*>(allocateImpl(
cannam@147 645 sizeof(T), elementCount, capacity, &construct, &destruct));
cannam@147 646 }
cannam@147 647 };
cannam@147 648
cannam@147 649 template <typename T>
cannam@147 650 T* HeapArrayDisposer::allocate(size_t count) {
cannam@147 651 return Allocate_<T>::allocate(count, count);
cannam@147 652 }
cannam@147 653
cannam@147 654 template <typename T>
cannam@147 655 T* HeapArrayDisposer::allocateUninitialized(size_t count) {
cannam@147 656 return Allocate_<T, true, true>::allocate(0, count);
cannam@147 657 }
cannam@147 658
cannam@147 659 template <typename Element, typename Iterator, bool move, bool = canMemcpy<Element>()>
cannam@147 660 struct CopyConstructArray_;
cannam@147 661
cannam@147 662 template <typename T, bool move>
cannam@147 663 struct CopyConstructArray_<T, T*, move, true> {
cannam@147 664 static inline T* apply(T* __restrict__ pos, T* start, T* end) {
cannam@147 665 memcpy(pos, start, reinterpret_cast<byte*>(end) - reinterpret_cast<byte*>(start));
cannam@147 666 return pos + (end - start);
cannam@147 667 }
cannam@147 668 };
cannam@147 669
cannam@147 670 template <typename T>
cannam@147 671 struct CopyConstructArray_<T, const T*, false, true> {
cannam@147 672 static inline T* apply(T* __restrict__ pos, const T* start, const T* end) {
cannam@147 673 memcpy(pos, start, reinterpret_cast<const byte*>(end) - reinterpret_cast<const byte*>(start));
cannam@147 674 return pos + (end - start);
cannam@147 675 }
cannam@147 676 };
cannam@147 677
cannam@147 678 template <typename T, typename Iterator, bool move>
cannam@147 679 struct CopyConstructArray_<T, Iterator, move, true> {
cannam@147 680 static inline T* apply(T* __restrict__ pos, Iterator start, Iterator end) {
cannam@147 681 // Since both the copy constructor and assignment operator are trivial, we know that assignment
cannam@147 682 // is equivalent to copy-constructing. So we can make this case somewhat easier for the
cannam@147 683 // compiler to optimize.
cannam@147 684 while (start != end) {
cannam@147 685 *pos++ = *start++;
cannam@147 686 }
cannam@147 687 return pos;
cannam@147 688 }
cannam@147 689 };
cannam@147 690
cannam@147 691 template <typename T, typename Iterator>
cannam@147 692 struct CopyConstructArray_<T, Iterator, false, false> {
cannam@147 693 struct ExceptionGuard {
cannam@147 694 T* start;
cannam@147 695 T* pos;
cannam@147 696 inline explicit ExceptionGuard(T* pos): start(pos), pos(pos) {}
cannam@147 697 ~ExceptionGuard() noexcept(false) {
cannam@147 698 while (pos > start) {
cannam@147 699 dtor(*--pos);
cannam@147 700 }
cannam@147 701 }
cannam@147 702 };
cannam@147 703
cannam@147 704 static T* apply(T* __restrict__ pos, Iterator start, Iterator end) {
cannam@147 705 // Verify that T can be *implicitly* constructed from the source values.
cannam@147 706 if (false) implicitCast<T>(*start);
cannam@147 707
cannam@147 708 if (noexcept(T(*start))) {
cannam@147 709 while (start != end) {
cannam@147 710 ctor(*pos++, *start++);
cannam@147 711 }
cannam@147 712 return pos;
cannam@147 713 } else {
cannam@147 714 // Crap. This is complicated.
cannam@147 715 ExceptionGuard guard(pos);
cannam@147 716 while (start != end) {
cannam@147 717 ctor(*guard.pos, *start++);
cannam@147 718 ++guard.pos;
cannam@147 719 }
cannam@147 720 guard.start = guard.pos;
cannam@147 721 return guard.pos;
cannam@147 722 }
cannam@147 723 }
cannam@147 724 };
cannam@147 725
cannam@147 726 template <typename T, typename Iterator>
cannam@147 727 struct CopyConstructArray_<T, Iterator, true, false> {
cannam@147 728 // Actually move-construct.
cannam@147 729
cannam@147 730 struct ExceptionGuard {
cannam@147 731 T* start;
cannam@147 732 T* pos;
cannam@147 733 inline explicit ExceptionGuard(T* pos): start(pos), pos(pos) {}
cannam@147 734 ~ExceptionGuard() noexcept(false) {
cannam@147 735 while (pos > start) {
cannam@147 736 dtor(*--pos);
cannam@147 737 }
cannam@147 738 }
cannam@147 739 };
cannam@147 740
cannam@147 741 static T* apply(T* __restrict__ pos, Iterator start, Iterator end) {
cannam@147 742 // Verify that T can be *implicitly* constructed from the source values.
cannam@147 743 if (false) implicitCast<T>(kj::mv(*start));
cannam@147 744
cannam@147 745 if (noexcept(T(kj::mv(*start)))) {
cannam@147 746 while (start != end) {
cannam@147 747 ctor(*pos++, kj::mv(*start++));
cannam@147 748 }
cannam@147 749 return pos;
cannam@147 750 } else {
cannam@147 751 // Crap. This is complicated.
cannam@147 752 ExceptionGuard guard(pos);
cannam@147 753 while (start != end) {
cannam@147 754 ctor(*guard.pos, kj::mv(*start++));
cannam@147 755 ++guard.pos;
cannam@147 756 }
cannam@147 757 guard.start = guard.pos;
cannam@147 758 return guard.pos;
cannam@147 759 }
cannam@147 760 }
cannam@147 761 };
cannam@147 762
cannam@147 763 } // namespace _ (private)
cannam@147 764
cannam@147 765 template <typename T>
cannam@147 766 template <typename Iterator, bool move>
cannam@147 767 void ArrayBuilder<T>::addAll(Iterator start, Iterator end) {
cannam@147 768 pos = _::CopyConstructArray_<RemoveConst<T>, Decay<Iterator>, move>::apply(pos, start, end);
cannam@147 769 }
cannam@147 770
cannam@147 771 template <typename T>
cannam@147 772 Array<T> heapArray(const T* content, size_t size) {
cannam@147 773 ArrayBuilder<T> builder = heapArrayBuilder<T>(size);
cannam@147 774 builder.addAll(content, content + size);
cannam@147 775 return builder.finish();
cannam@147 776 }
cannam@147 777
cannam@147 778 template <typename T>
cannam@147 779 Array<T> heapArray(T* content, size_t size) {
cannam@147 780 ArrayBuilder<T> builder = heapArrayBuilder<T>(size);
cannam@147 781 builder.addAll(content, content + size);
cannam@147 782 return builder.finish();
cannam@147 783 }
cannam@147 784
cannam@147 785 template <typename T>
cannam@147 786 Array<T> heapArray(ArrayPtr<T> content) {
cannam@147 787 ArrayBuilder<T> builder = heapArrayBuilder<T>(content.size());
cannam@147 788 builder.addAll(content);
cannam@147 789 return builder.finish();
cannam@147 790 }
cannam@147 791
cannam@147 792 template <typename T>
cannam@147 793 Array<T> heapArray(ArrayPtr<const T> content) {
cannam@147 794 ArrayBuilder<T> builder = heapArrayBuilder<T>(content.size());
cannam@147 795 builder.addAll(content);
cannam@147 796 return builder.finish();
cannam@147 797 }
cannam@147 798
cannam@147 799 template <typename T, typename Iterator> Array<T>
cannam@147 800 heapArray(Iterator begin, Iterator end) {
cannam@147 801 ArrayBuilder<T> builder = heapArrayBuilder<T>(end - begin);
cannam@147 802 builder.addAll(begin, end);
cannam@147 803 return builder.finish();
cannam@147 804 }
cannam@147 805
cannam@147 806 template <typename T>
cannam@147 807 inline Array<T> heapArray(std::initializer_list<T> init) {
cannam@147 808 return heapArray<T>(init.begin(), init.end());
cannam@147 809 }
cannam@147 810
cannam@147 811 } // namespace kj
cannam@147 812
cannam@147 813 #endif // KJ_ARRAY_H_