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