annotate win32-mingw/include/capnp/arena.h @ 79:91c729825bca pa_catalina

Update build for AUDIO_COMPONENT_FIX
author Chris Cannam
date Wed, 30 Oct 2019 12:40:34 +0000
parents eccd51b72864
children
rev   line source
Chris@64 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
Chris@64 2 // Licensed under the MIT License:
Chris@64 3 //
Chris@64 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
Chris@64 5 // of this software and associated documentation files (the "Software"), to deal
Chris@64 6 // in the Software without restriction, including without limitation the rights
Chris@64 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
Chris@64 8 // copies of the Software, and to permit persons to whom the Software is
Chris@64 9 // furnished to do so, subject to the following conditions:
Chris@64 10 //
Chris@64 11 // The above copyright notice and this permission notice shall be included in
Chris@64 12 // all copies or substantial portions of the Software.
Chris@64 13 //
Chris@64 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Chris@64 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Chris@64 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Chris@64 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Chris@64 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
Chris@64 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
Chris@64 20 // THE SOFTWARE.
Chris@64 21
Chris@64 22 #ifndef CAPNP_ARENA_H_
Chris@64 23 #define CAPNP_ARENA_H_
Chris@64 24
Chris@64 25 #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS)
Chris@64 26 #pragma GCC system_header
Chris@64 27 #endif
Chris@64 28
Chris@64 29 #ifndef CAPNP_PRIVATE
Chris@64 30 #error "This header is only meant to be included by Cap'n Proto's own source code."
Chris@64 31 #endif
Chris@64 32
Chris@64 33 #include <kj/common.h>
Chris@64 34 #include <kj/mutex.h>
Chris@64 35 #include <kj/exception.h>
Chris@64 36 #include <kj/vector.h>
Chris@64 37 #include <kj/units.h>
Chris@64 38 #include "common.h"
Chris@64 39 #include "message.h"
Chris@64 40 #include "layout.h"
Chris@64 41 #include <unordered_map>
Chris@64 42
Chris@64 43 #if !CAPNP_LITE
Chris@64 44 #include "capability.h"
Chris@64 45 #endif // !CAPNP_LITE
Chris@64 46
Chris@64 47 namespace capnp {
Chris@64 48
Chris@64 49 #if !CAPNP_LITE
Chris@64 50 class ClientHook;
Chris@64 51 #endif // !CAPNP_LITE
Chris@64 52
Chris@64 53 namespace _ { // private
Chris@64 54
Chris@64 55 class SegmentReader;
Chris@64 56 class SegmentBuilder;
Chris@64 57 class Arena;
Chris@64 58 class BuilderArena;
Chris@64 59 class ReadLimiter;
Chris@64 60
Chris@64 61 class Segment;
Chris@64 62 typedef kj::Id<uint32_t, Segment> SegmentId;
Chris@64 63
Chris@64 64 class ReadLimiter {
Chris@64 65 // Used to keep track of how much data has been processed from a message, and cut off further
Chris@64 66 // processing if and when a particular limit is reached. This is primarily intended to guard
Chris@64 67 // against maliciously-crafted messages which contain cycles or overlapping structures. Cycles
Chris@64 68 // and overlapping are not permitted by the Cap'n Proto format because in many cases they could
Chris@64 69 // be used to craft a deceptively small message which could consume excessive server resources to
Chris@64 70 // process, perhaps even sending it into an infinite loop. Actually detecting overlaps would be
Chris@64 71 // time-consuming, so instead we just keep track of how many words worth of data structures the
Chris@64 72 // receiver has actually dereferenced and error out if this gets too high.
Chris@64 73 //
Chris@64 74 // This counting takes place as you call getters (for non-primitive values) on the message
Chris@64 75 // readers. If you call the same getter twice, the data it returns may be double-counted. This
Chris@64 76 // should not be a big deal in most cases -- just set the read limit high enough that it will
Chris@64 77 // only trigger in unreasonable cases.
Chris@64 78 //
Chris@64 79 // This class is "safe" to use from multiple threads for its intended use case. Threads may
Chris@64 80 // overwrite each others' changes to the counter, but this is OK because it only means that the
Chris@64 81 // limit is enforced a bit less strictly -- it will still kick in eventually.
Chris@64 82
Chris@64 83 public:
Chris@64 84 inline explicit ReadLimiter(); // No limit.
Chris@64 85 inline explicit ReadLimiter(WordCount64 limit); // Limit to the given number of words.
Chris@64 86
Chris@64 87 inline void reset(WordCount64 limit);
Chris@64 88
Chris@64 89 KJ_ALWAYS_INLINE(bool canRead(WordCount64 amount, Arena* arena));
Chris@64 90
Chris@64 91 void unread(WordCount64 amount);
Chris@64 92 // Adds back some words to the limit. Useful when the caller knows they are double-reading
Chris@64 93 // some data.
Chris@64 94
Chris@64 95 private:
Chris@64 96 volatile uint64_t limit;
Chris@64 97 // Current limit, decremented each time catRead() is called. Volatile because multiple threads
Chris@64 98 // could be trying to modify it at once. (This is not real thread-safety, but good enough for
Chris@64 99 // the purpose of this class. See class comment.)
Chris@64 100
Chris@64 101 KJ_DISALLOW_COPY(ReadLimiter);
Chris@64 102 };
Chris@64 103
Chris@64 104 #if !CAPNP_LITE
Chris@64 105 class BrokenCapFactory {
Chris@64 106 // Callback for constructing broken caps. We use this so that we can avoid arena.c++ having a
Chris@64 107 // link-time dependency on capability code that lives in libcapnp-rpc.
Chris@64 108
Chris@64 109 public:
Chris@64 110 virtual kj::Own<ClientHook> newBrokenCap(kj::StringPtr description) = 0;
Chris@64 111 virtual kj::Own<ClientHook> newNullCap() = 0;
Chris@64 112 };
Chris@64 113 #endif // !CAPNP_LITE
Chris@64 114
Chris@64 115 class SegmentReader {
Chris@64 116 public:
Chris@64 117 inline SegmentReader(Arena* arena, SegmentId id, const word* ptr, SegmentWordCount size,
Chris@64 118 ReadLimiter* readLimiter);
Chris@64 119
Chris@64 120 KJ_ALWAYS_INLINE(const word* checkOffset(const word* from, ptrdiff_t offset));
Chris@64 121 // Adds the given offset to the given pointer, checks that it is still within the bounds of the
Chris@64 122 // segment, then returns it. Note that the "end" pointer of the segment (which technically points
Chris@64 123 // to the word after the last in the segment) is considered in-bounds for this purpose, so you
Chris@64 124 // can't necessarily dereference it. You must call checkObject() next to check that the object
Chris@64 125 // you want to read is entirely in-bounds.
Chris@64 126 //
Chris@64 127 // If `from + offset` is out-of-range, this returns a pointer to the end of the segment. Thus,
Chris@64 128 // any non-zero-sized object will fail `checkObject()`. We do this instead of throwing to save
Chris@64 129 // some code footprint.
Chris@64 130
Chris@64 131 KJ_ALWAYS_INLINE(bool checkObject(const word* start, WordCountN<31> size));
Chris@64 132 // Assuming that `start` is in-bounds for this segment (probably checked using `checkOffset()`),
Chris@64 133 // check that `start + size` is also in-bounds, and hence the whole area in-between is valid.
Chris@64 134
Chris@64 135 KJ_ALWAYS_INLINE(bool amplifiedRead(WordCount virtualAmount));
Chris@64 136 // Indicates that the reader should pretend that `virtualAmount` additional data was read even
Chris@64 137 // though no actual pointer was traversed. This is used e.g. when reading a struct list pointer
Chris@64 138 // where the element sizes are zero -- the sender could set the list size arbitrarily high and
Chris@64 139 // cause the receiver to iterate over this list even though the message itself is small, so we
Chris@64 140 // need to defend against DoS attacks based on this.
Chris@64 141
Chris@64 142 inline Arena* getArena();
Chris@64 143 inline SegmentId getSegmentId();
Chris@64 144
Chris@64 145 inline const word* getStartPtr();
Chris@64 146 inline SegmentWordCount getOffsetTo(const word* ptr);
Chris@64 147 inline SegmentWordCount getSize();
Chris@64 148
Chris@64 149 inline kj::ArrayPtr<const word> getArray();
Chris@64 150
Chris@64 151 inline void unread(WordCount64 amount);
Chris@64 152 // Add back some words to the ReadLimiter.
Chris@64 153
Chris@64 154 private:
Chris@64 155 Arena* arena;
Chris@64 156 SegmentId id;
Chris@64 157 kj::ArrayPtr<const word> ptr; // size guaranteed to fit in SEGMENT_WORD_COUNT_BITS bits
Chris@64 158 ReadLimiter* readLimiter;
Chris@64 159
Chris@64 160 KJ_DISALLOW_COPY(SegmentReader);
Chris@64 161
Chris@64 162 friend class SegmentBuilder;
Chris@64 163
Chris@64 164 static void abortCheckObjectFault();
Chris@64 165 // Called in debug mode in cases that would segfault in opt mode. (Should be impossible!)
Chris@64 166 };
Chris@64 167
Chris@64 168 class SegmentBuilder: public SegmentReader {
Chris@64 169 public:
Chris@64 170 inline SegmentBuilder(BuilderArena* arena, SegmentId id, word* ptr, SegmentWordCount size,
Chris@64 171 ReadLimiter* readLimiter, SegmentWordCount wordsUsed = ZERO * WORDS);
Chris@64 172 inline SegmentBuilder(BuilderArena* arena, SegmentId id, const word* ptr, SegmentWordCount size,
Chris@64 173 ReadLimiter* readLimiter);
Chris@64 174 inline SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr),
Chris@64 175 ReadLimiter* readLimiter);
Chris@64 176
Chris@64 177 KJ_ALWAYS_INLINE(word* allocate(SegmentWordCount amount));
Chris@64 178
Chris@64 179 KJ_ALWAYS_INLINE(void checkWritable());
Chris@64 180 // Throw an exception if the segment is read-only (meaning it is a reference to external data).
Chris@64 181
Chris@64 182 KJ_ALWAYS_INLINE(word* getPtrUnchecked(SegmentWordCount offset));
Chris@64 183 // Get a writable pointer into the segment. Throws an exception if the segment is read-only (i.e.
Chris@64 184 // a reference to external immutable data).
Chris@64 185
Chris@64 186 inline BuilderArena* getArena();
Chris@64 187
Chris@64 188 inline kj::ArrayPtr<const word> currentlyAllocated();
Chris@64 189
Chris@64 190 inline void reset();
Chris@64 191
Chris@64 192 inline bool isWritable() { return !readOnly; }
Chris@64 193
Chris@64 194 inline void tryTruncate(word* from, word* to);
Chris@64 195 // If `from` points just past the current end of the segment, then move the end back to `to`.
Chris@64 196 // Otherwise, do nothing.
Chris@64 197
Chris@64 198 inline bool tryExtend(word* from, word* to);
Chris@64 199 // If `from` points just past the current end of the segment, and `to` is within the segment
Chris@64 200 // boundaries, then move the end up to `to` and return true. Otherwise, do nothing and return
Chris@64 201 // false.
Chris@64 202
Chris@64 203 private:
Chris@64 204 word* pos;
Chris@64 205 // Pointer to a pointer to the current end point of the segment, i.e. the location where the
Chris@64 206 // next object should be allocated.
Chris@64 207
Chris@64 208 bool readOnly;
Chris@64 209
Chris@64 210 void throwNotWritable();
Chris@64 211
Chris@64 212 KJ_DISALLOW_COPY(SegmentBuilder);
Chris@64 213 };
Chris@64 214
Chris@64 215 class Arena {
Chris@64 216 public:
Chris@64 217 virtual ~Arena() noexcept(false);
Chris@64 218
Chris@64 219 virtual SegmentReader* tryGetSegment(SegmentId id) = 0;
Chris@64 220 // Gets the segment with the given ID, or return nullptr if no such segment exists.
Chris@64 221
Chris@64 222 virtual void reportReadLimitReached() = 0;
Chris@64 223 // Called to report that the read limit has been reached. See ReadLimiter, below. This invokes
Chris@64 224 // the VALIDATE_INPUT() macro which may throw an exception; if it returns normally, the caller
Chris@64 225 // will need to continue with default values.
Chris@64 226 };
Chris@64 227
Chris@64 228 class ReaderArena final: public Arena {
Chris@64 229 public:
Chris@64 230 explicit ReaderArena(MessageReader* message);
Chris@64 231 ~ReaderArena() noexcept(false);
Chris@64 232 KJ_DISALLOW_COPY(ReaderArena);
Chris@64 233
Chris@64 234 // implements Arena ------------------------------------------------
Chris@64 235 SegmentReader* tryGetSegment(SegmentId id) override;
Chris@64 236 void reportReadLimitReached() override;
Chris@64 237
Chris@64 238 private:
Chris@64 239 MessageReader* message;
Chris@64 240 ReadLimiter readLimiter;
Chris@64 241
Chris@64 242 // Optimize for single-segment messages so that small messages are handled quickly.
Chris@64 243 SegmentReader segment0;
Chris@64 244
Chris@64 245 typedef std::unordered_map<uint, kj::Own<SegmentReader>> SegmentMap;
Chris@64 246 kj::MutexGuarded<kj::Maybe<kj::Own<SegmentMap>>> moreSegments;
Chris@64 247 // We need to mutex-guard the segment map because we lazily initialize segments when they are
Chris@64 248 // first requested, but a Reader is allowed to be used concurrently in multiple threads. Luckily
Chris@64 249 // this only applies to large messages.
Chris@64 250 //
Chris@64 251 // TODO(perf): Thread-local thing instead? Some kind of lockless map? Or do sharing of data
Chris@64 252 // in a different way, where you have to construct a new MessageReader in each thread (but
Chris@64 253 // possibly backed by the same data)?
Chris@64 254
Chris@64 255 ReaderArena(MessageReader* message, kj::ArrayPtr<const word> firstSegment);
Chris@64 256 ReaderArena(MessageReader* message, const word* firstSegment, SegmentWordCount firstSegmentSize);
Chris@64 257 };
Chris@64 258
Chris@64 259 class BuilderArena final: public Arena {
Chris@64 260 // A BuilderArena that does not allow the injection of capabilities.
Chris@64 261
Chris@64 262 public:
Chris@64 263 explicit BuilderArena(MessageBuilder* message);
Chris@64 264 BuilderArena(MessageBuilder* message, kj::ArrayPtr<MessageBuilder::SegmentInit> segments);
Chris@64 265 ~BuilderArena() noexcept(false);
Chris@64 266 KJ_DISALLOW_COPY(BuilderArena);
Chris@64 267
Chris@64 268 inline SegmentBuilder* getRootSegment() { return &segment0; }
Chris@64 269
Chris@64 270 kj::ArrayPtr<const kj::ArrayPtr<const word>> getSegmentsForOutput();
Chris@64 271 // Get an array of all the segments, suitable for writing out. This only returns the allocated
Chris@64 272 // portion of each segment, whereas tryGetSegment() returns something that includes
Chris@64 273 // not-yet-allocated space.
Chris@64 274
Chris@64 275 inline CapTableBuilder* getLocalCapTable() {
Chris@64 276 // Return a CapTableBuilder that merely implements local loopback. That is, you can set
Chris@64 277 // capabilities, then read the same capabilities back, but there is no intent ever to transmit
Chris@64 278 // these capabilities. A MessageBuilder that isn't imbued with some other CapTable uses this
Chris@64 279 // by default.
Chris@64 280 //
Chris@64 281 // TODO(cleanup): It's sort of a hack that this exists. In theory, perhaps, unimbued
Chris@64 282 // MessageBuilders should throw exceptions on any attempt to access capability fields, like
Chris@64 283 // unimbued MessageReaders do. However, lots of code exists which uses MallocMessageBuilder
Chris@64 284 // as a temporary holder for data to be copied in and out (without being serialized), and it
Chris@64 285 // is expected that such data can include capabilities, which is admittedly reasonable.
Chris@64 286 // Therefore, all MessageBuilders must have a cap table by default. Arguably we should
Chris@64 287 // deprecate this usage and instead define a new helper type for this exact purpose.
Chris@64 288
Chris@64 289 return &localCapTable;
Chris@64 290 }
Chris@64 291
Chris@64 292 SegmentBuilder* getSegment(SegmentId id);
Chris@64 293 // Get the segment with the given id. Crashes or throws an exception if no such segment exists.
Chris@64 294
Chris@64 295 struct AllocateResult {
Chris@64 296 SegmentBuilder* segment;
Chris@64 297 word* words;
Chris@64 298 };
Chris@64 299
Chris@64 300 AllocateResult allocate(SegmentWordCount amount);
Chris@64 301 // Find a segment with at least the given amount of space available and allocate the space.
Chris@64 302 // Note that allocating directly from a particular segment is much faster, but allocating from
Chris@64 303 // the arena is guaranteed to succeed. Therefore callers should try to allocate from a specific
Chris@64 304 // segment first if there is one, then fall back to the arena.
Chris@64 305
Chris@64 306 SegmentBuilder* addExternalSegment(kj::ArrayPtr<const word> content);
Chris@64 307 // Add a new segment to the arena which points to some existing memory region. The segment is
Chris@64 308 // assumed to be completley full; the arena will never allocate from it. In fact, the segment
Chris@64 309 // is considered read-only. Any attempt to get a Builder pointing into this segment will throw
Chris@64 310 // an exception. Readers are allowed, however.
Chris@64 311 //
Chris@64 312 // This can be used to inject some external data into a message without a copy, e.g. embedding a
Chris@64 313 // large mmap'd file into a message as `Data` without forcing that data to actually be read in
Chris@64 314 // from disk (until the message itself is written out). `Orphanage` provides the public API for
Chris@64 315 // this feature.
Chris@64 316
Chris@64 317 // implements Arena ------------------------------------------------
Chris@64 318 SegmentReader* tryGetSegment(SegmentId id) override;
Chris@64 319 void reportReadLimitReached() override;
Chris@64 320
Chris@64 321 private:
Chris@64 322 MessageBuilder* message;
Chris@64 323 ReadLimiter dummyLimiter;
Chris@64 324
Chris@64 325 class LocalCapTable: public CapTableBuilder {
Chris@64 326 #if !CAPNP_LITE
Chris@64 327 public:
Chris@64 328 kj::Maybe<kj::Own<ClientHook>> extractCap(uint index) override;
Chris@64 329 uint injectCap(kj::Own<ClientHook>&& cap) override;
Chris@64 330 void dropCap(uint index) override;
Chris@64 331
Chris@64 332 private:
Chris@64 333 kj::Vector<kj::Maybe<kj::Own<ClientHook>>> capTable;
Chris@64 334 #endif // ! CAPNP_LITE
Chris@64 335 };
Chris@64 336
Chris@64 337 LocalCapTable localCapTable;
Chris@64 338
Chris@64 339 SegmentBuilder segment0;
Chris@64 340 kj::ArrayPtr<const word> segment0ForOutput;
Chris@64 341
Chris@64 342 struct MultiSegmentState {
Chris@64 343 kj::Vector<kj::Own<SegmentBuilder>> builders;
Chris@64 344 kj::Vector<kj::ArrayPtr<const word>> forOutput;
Chris@64 345 };
Chris@64 346 kj::Maybe<kj::Own<MultiSegmentState>> moreSegments;
Chris@64 347
Chris@64 348 SegmentBuilder* segmentWithSpace = nullptr;
Chris@64 349 // When allocating, look for space in this segment first before resorting to allocating a new
Chris@64 350 // segment. This is not necessarily the last segment because addExternalSegment() may add a
Chris@64 351 // segment that is already-full, in which case we don't update this pointer.
Chris@64 352
Chris@64 353 template <typename T> // Can be `word` or `const word`.
Chris@64 354 SegmentBuilder* addSegmentInternal(kj::ArrayPtr<T> content);
Chris@64 355 };
Chris@64 356
Chris@64 357 // =======================================================================================
Chris@64 358
Chris@64 359 inline ReadLimiter::ReadLimiter()
Chris@64 360 : limit(kj::maxValue) {}
Chris@64 361
Chris@64 362 inline ReadLimiter::ReadLimiter(WordCount64 limit): limit(unbound(limit / WORDS)) {}
Chris@64 363
Chris@64 364 inline void ReadLimiter::reset(WordCount64 limit) { this->limit = unbound(limit / WORDS); }
Chris@64 365
Chris@64 366 inline bool ReadLimiter::canRead(WordCount64 amount, Arena* arena) {
Chris@64 367 // Be careful not to store an underflowed value into `limit`, even if multiple threads are
Chris@64 368 // decrementing it.
Chris@64 369 uint64_t current = limit;
Chris@64 370 if (KJ_UNLIKELY(unbound(amount / WORDS) > current)) {
Chris@64 371 arena->reportReadLimitReached();
Chris@64 372 return false;
Chris@64 373 } else {
Chris@64 374 limit = current - unbound(amount / WORDS);
Chris@64 375 return true;
Chris@64 376 }
Chris@64 377 }
Chris@64 378
Chris@64 379 // -------------------------------------------------------------------
Chris@64 380
Chris@64 381 inline SegmentReader::SegmentReader(Arena* arena, SegmentId id, const word* ptr,
Chris@64 382 SegmentWordCount size, ReadLimiter* readLimiter)
Chris@64 383 : arena(arena), id(id), ptr(kj::arrayPtr(ptr, unbound(size / WORDS))),
Chris@64 384 readLimiter(readLimiter) {}
Chris@64 385
Chris@64 386 inline const word* SegmentReader::checkOffset(const word* from, ptrdiff_t offset) {
Chris@64 387 ptrdiff_t min = ptr.begin() - from;
Chris@64 388 ptrdiff_t max = ptr.end() - from;
Chris@64 389 if (offset >= min && offset <= max) {
Chris@64 390 return from + offset;
Chris@64 391 } else {
Chris@64 392 return ptr.end();
Chris@64 393 }
Chris@64 394 }
Chris@64 395
Chris@64 396 inline bool SegmentReader::checkObject(const word* start, WordCountN<31> size) {
Chris@64 397 auto startOffset = intervalLength(ptr.begin(), start, MAX_SEGMENT_WORDS);
Chris@64 398 #ifdef KJ_DEBUG
Chris@64 399 if (startOffset > bounded(ptr.size()) * WORDS) {
Chris@64 400 abortCheckObjectFault();
Chris@64 401 }
Chris@64 402 #endif
Chris@64 403 return startOffset + size <= bounded(ptr.size()) * WORDS &&
Chris@64 404 readLimiter->canRead(size, arena);
Chris@64 405 }
Chris@64 406
Chris@64 407 inline bool SegmentReader::amplifiedRead(WordCount virtualAmount) {
Chris@64 408 return readLimiter->canRead(virtualAmount, arena);
Chris@64 409 }
Chris@64 410
Chris@64 411 inline Arena* SegmentReader::getArena() { return arena; }
Chris@64 412 inline SegmentId SegmentReader::getSegmentId() { return id; }
Chris@64 413 inline const word* SegmentReader::getStartPtr() { return ptr.begin(); }
Chris@64 414 inline SegmentWordCount SegmentReader::getOffsetTo(const word* ptr) {
Chris@64 415 KJ_IREQUIRE(this->ptr.begin() <= ptr && ptr <= this->ptr.end());
Chris@64 416 return intervalLength(this->ptr.begin(), ptr, MAX_SEGMENT_WORDS);
Chris@64 417 }
Chris@64 418 inline SegmentWordCount SegmentReader::getSize() {
Chris@64 419 return assumeBits<SEGMENT_WORD_COUNT_BITS>(ptr.size()) * WORDS;
Chris@64 420 }
Chris@64 421 inline kj::ArrayPtr<const word> SegmentReader::getArray() { return ptr; }
Chris@64 422 inline void SegmentReader::unread(WordCount64 amount) { readLimiter->unread(amount); }
Chris@64 423
Chris@64 424 // -------------------------------------------------------------------
Chris@64 425
Chris@64 426 inline SegmentBuilder::SegmentBuilder(
Chris@64 427 BuilderArena* arena, SegmentId id, word* ptr, SegmentWordCount size,
Chris@64 428 ReadLimiter* readLimiter, SegmentWordCount wordsUsed)
Chris@64 429 : SegmentReader(arena, id, ptr, size, readLimiter),
Chris@64 430 pos(ptr + wordsUsed), readOnly(false) {}
Chris@64 431 inline SegmentBuilder::SegmentBuilder(
Chris@64 432 BuilderArena* arena, SegmentId id, const word* ptr, SegmentWordCount size,
Chris@64 433 ReadLimiter* readLimiter)
Chris@64 434 : SegmentReader(arena, id, ptr, size, readLimiter),
Chris@64 435 // const_cast is safe here because the member won't ever be dereferenced because it appears
Chris@64 436 // to point to the end of the segment anyway.
Chris@64 437 pos(const_cast<word*>(ptr + size)), readOnly(true) {}
Chris@64 438 inline SegmentBuilder::SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr),
Chris@64 439 ReadLimiter* readLimiter)
Chris@64 440 : SegmentReader(arena, id, nullptr, ZERO * WORDS, readLimiter),
Chris@64 441 pos(nullptr), readOnly(false) {}
Chris@64 442
Chris@64 443 inline word* SegmentBuilder::allocate(SegmentWordCount amount) {
Chris@64 444 if (intervalLength(pos, ptr.end(), MAX_SEGMENT_WORDS) < amount) {
Chris@64 445 // Not enough space in the segment for this allocation.
Chris@64 446 return nullptr;
Chris@64 447 } else {
Chris@64 448 // Success.
Chris@64 449 word* result = pos;
Chris@64 450 pos = pos + amount;
Chris@64 451 return result;
Chris@64 452 }
Chris@64 453 }
Chris@64 454
Chris@64 455 inline void SegmentBuilder::checkWritable() {
Chris@64 456 if (KJ_UNLIKELY(readOnly)) throwNotWritable();
Chris@64 457 }
Chris@64 458
Chris@64 459 inline word* SegmentBuilder::getPtrUnchecked(SegmentWordCount offset) {
Chris@64 460 return const_cast<word*>(ptr.begin() + offset);
Chris@64 461 }
Chris@64 462
Chris@64 463 inline BuilderArena* SegmentBuilder::getArena() {
Chris@64 464 // Down-cast safe because SegmentBuilder's constructor always initializes its SegmentReader base
Chris@64 465 // class with an Arena pointer that actually points to a BuilderArena.
Chris@64 466 return static_cast<BuilderArena*>(arena);
Chris@64 467 }
Chris@64 468
Chris@64 469 inline kj::ArrayPtr<const word> SegmentBuilder::currentlyAllocated() {
Chris@64 470 return kj::arrayPtr(ptr.begin(), pos - ptr.begin());
Chris@64 471 }
Chris@64 472
Chris@64 473 inline void SegmentBuilder::reset() {
Chris@64 474 word* start = getPtrUnchecked(ZERO * WORDS);
Chris@64 475 memset(start, 0, (pos - start) * sizeof(word));
Chris@64 476 pos = start;
Chris@64 477 }
Chris@64 478
Chris@64 479 inline void SegmentBuilder::tryTruncate(word* from, word* to) {
Chris@64 480 if (pos == from) pos = to;
Chris@64 481 }
Chris@64 482
Chris@64 483 inline bool SegmentBuilder::tryExtend(word* from, word* to) {
Chris@64 484 // Careful about overflow.
Chris@64 485 if (pos == from && to <= ptr.end() && to >= from) {
Chris@64 486 pos = to;
Chris@64 487 return true;
Chris@64 488 } else {
Chris@64 489 return false;
Chris@64 490 }
Chris@64 491 }
Chris@64 492
Chris@64 493 } // namespace _ (private)
Chris@64 494 } // namespace capnp
Chris@64 495
Chris@64 496 #endif // CAPNP_ARENA_H_