annotate win64-msvc/include/capnp/message.h @ 47:d93140aac40b

Current Capnp libs and headers from git
author Chris Cannam
date Thu, 20 Oct 2016 18:15:38 +0100
parents
children 0f2d93caa50c
rev   line source
Chris@47 1 // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
Chris@47 2 // Licensed under the MIT License:
Chris@47 3 //
Chris@47 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
Chris@47 5 // of this software and associated documentation files (the "Software"), to deal
Chris@47 6 // in the Software without restriction, including without limitation the rights
Chris@47 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
Chris@47 8 // copies of the Software, and to permit persons to whom the Software is
Chris@47 9 // furnished to do so, subject to the following conditions:
Chris@47 10 //
Chris@47 11 // The above copyright notice and this permission notice shall be included in
Chris@47 12 // all copies or substantial portions of the Software.
Chris@47 13 //
Chris@47 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Chris@47 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Chris@47 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Chris@47 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Chris@47 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
Chris@47 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
Chris@47 20 // THE SOFTWARE.
Chris@47 21
Chris@47 22 #include <kj/common.h>
Chris@47 23 #include <kj/memory.h>
Chris@47 24 #include <kj/mutex.h>
Chris@47 25 #include <kj/debug.h>
Chris@47 26 #include "common.h"
Chris@47 27 #include "layout.h"
Chris@47 28 #include "any.h"
Chris@47 29
Chris@47 30 #ifndef CAPNP_MESSAGE_H_
Chris@47 31 #define CAPNP_MESSAGE_H_
Chris@47 32
Chris@47 33 #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS)
Chris@47 34 #pragma GCC system_header
Chris@47 35 #endif
Chris@47 36
Chris@47 37 namespace capnp {
Chris@47 38
Chris@47 39 namespace _ { // private
Chris@47 40 class ReaderArena;
Chris@47 41 class BuilderArena;
Chris@47 42 }
Chris@47 43
Chris@47 44 class StructSchema;
Chris@47 45 class Orphanage;
Chris@47 46 template <typename T>
Chris@47 47 class Orphan;
Chris@47 48
Chris@47 49 // =======================================================================================
Chris@47 50
Chris@47 51 struct ReaderOptions {
Chris@47 52 // Options controlling how data is read.
Chris@47 53
Chris@47 54 uint64_t traversalLimitInWords = 8 * 1024 * 1024;
Chris@47 55 // Limits how many total words of data are allowed to be traversed. Traversal is counted when
Chris@47 56 // a new struct or list builder is obtained, e.g. from a get() accessor. This means that calling
Chris@47 57 // the getter for the same sub-struct multiple times will cause it to be double-counted. Once
Chris@47 58 // the traversal limit is reached, an error will be reported.
Chris@47 59 //
Chris@47 60 // This limit exists for security reasons. It is possible for an attacker to construct a message
Chris@47 61 // in which multiple pointers point at the same location. This is technically invalid, but hard
Chris@47 62 // to detect. Using such a message, an attacker could cause a message which is small on the wire
Chris@47 63 // to appear much larger when actually traversed, possibly exhausting server resources leading to
Chris@47 64 // denial-of-service.
Chris@47 65 //
Chris@47 66 // It makes sense to set a traversal limit that is much larger than the underlying message.
Chris@47 67 // Together with sensible coding practices (e.g. trying to avoid calling sub-object getters
Chris@47 68 // multiple times, which is expensive anyway), this should provide adequate protection without
Chris@47 69 // inconvenience.
Chris@47 70 //
Chris@47 71 // The default limit is 64 MiB. This may or may not be a sensible number for any given use case,
Chris@47 72 // but probably at least prevents easy exploitation while also avoiding causing problems in most
Chris@47 73 // typical cases.
Chris@47 74
Chris@47 75 int nestingLimit = 64;
Chris@47 76 // Limits how deeply-nested a message structure can be, e.g. structs containing other structs or
Chris@47 77 // lists of structs.
Chris@47 78 //
Chris@47 79 // Like the traversal limit, this limit exists for security reasons. Since it is common to use
Chris@47 80 // recursive code to traverse recursive data structures, an attacker could easily cause a stack
Chris@47 81 // overflow by sending a very-deeply-nested (or even cyclic) message, without the message even
Chris@47 82 // being very large. The default limit of 64 is probably low enough to prevent any chance of
Chris@47 83 // stack overflow, yet high enough that it is never a problem in practice.
Chris@47 84 };
Chris@47 85
Chris@47 86 class MessageReader {
Chris@47 87 // Abstract interface for an object used to read a Cap'n Proto message. Subclasses of
Chris@47 88 // MessageReader are responsible for reading the raw, flat message content. Callers should
Chris@47 89 // usually call `messageReader.getRoot<MyStructType>()` to get a `MyStructType::Reader`
Chris@47 90 // representing the root of the message, then use that to traverse the message content.
Chris@47 91 //
Chris@47 92 // Some common subclasses of `MessageReader` include `SegmentArrayMessageReader`, whose
Chris@47 93 // constructor accepts pointers to the raw data, and `StreamFdMessageReader` (from
Chris@47 94 // `serialize.h`), which reads the message from a file descriptor. One might implement other
Chris@47 95 // subclasses to handle things like reading from shared memory segments, mmap()ed files, etc.
Chris@47 96
Chris@47 97 public:
Chris@47 98 MessageReader(ReaderOptions options);
Chris@47 99 // It is suggested that subclasses take ReaderOptions as a constructor parameter, but give it a
Chris@47 100 // default value of "ReaderOptions()". The base class constructor doesn't have a default value
Chris@47 101 // in order to remind subclasses that they really need to give the user a way to provide this.
Chris@47 102
Chris@47 103 virtual ~MessageReader() noexcept(false);
Chris@47 104
Chris@47 105 virtual kj::ArrayPtr<const word> getSegment(uint id) = 0;
Chris@47 106 // Gets the segment with the given ID, or returns null if no such segment exists. This method
Chris@47 107 // will be called at most once for each segment ID.
Chris@47 108
Chris@47 109 inline const ReaderOptions& getOptions();
Chris@47 110 // Get the options passed to the constructor.
Chris@47 111
Chris@47 112 template <typename RootType>
Chris@47 113 typename RootType::Reader getRoot();
Chris@47 114 // Get the root struct of the message, interpreting it as the given struct type.
Chris@47 115
Chris@47 116 template <typename RootType, typename SchemaType>
Chris@47 117 typename RootType::Reader getRoot(SchemaType schema);
Chris@47 118 // Dynamically interpret the root struct of the message using the given schema (a StructSchema).
Chris@47 119 // RootType in this case must be DynamicStruct, and you must #include <capnp/dynamic.h> to
Chris@47 120 // use this.
Chris@47 121
Chris@47 122 bool isCanonical();
Chris@47 123 // Returns whether the message encoded in the reader is in canonical form.
Chris@47 124
Chris@47 125 private:
Chris@47 126 ReaderOptions options;
Chris@47 127
Chris@47 128 // Space in which we can construct a ReaderArena. We don't use ReaderArena directly here
Chris@47 129 // because we don't want clients to have to #include arena.h, which itself includes a bunch of
Chris@47 130 // big STL headers. We don't use a pointer to a ReaderArena because that would require an
Chris@47 131 // extra malloc on every message which could be expensive when processing small messages.
Chris@47 132 void* arenaSpace[15 + sizeof(kj::MutexGuarded<void*>) / sizeof(void*)];
Chris@47 133 bool allocatedArena;
Chris@47 134
Chris@47 135 _::ReaderArena* arena() { return reinterpret_cast<_::ReaderArena*>(arenaSpace); }
Chris@47 136 AnyPointer::Reader getRootInternal();
Chris@47 137 };
Chris@47 138
Chris@47 139 class MessageBuilder {
Chris@47 140 // Abstract interface for an object used to allocate and build a message. Subclasses of
Chris@47 141 // MessageBuilder are responsible for allocating the space in which the message will be written.
Chris@47 142 // The most common subclass is `MallocMessageBuilder`, but other subclasses may be used to do
Chris@47 143 // tricky things like allocate messages in shared memory or mmap()ed files.
Chris@47 144 //
Chris@47 145 // Creating a new message ususually means allocating a new MessageBuilder (ideally on the stack)
Chris@47 146 // and then calling `messageBuilder.initRoot<MyStructType>()` to get a `MyStructType::Builder`.
Chris@47 147 // That, in turn, can be used to fill in the message content. When done, you can call
Chris@47 148 // `messageBuilder.getSegmentsForOutput()` to get a list of flat data arrays containing the
Chris@47 149 // message.
Chris@47 150
Chris@47 151 public:
Chris@47 152 MessageBuilder();
Chris@47 153 virtual ~MessageBuilder() noexcept(false);
Chris@47 154 KJ_DISALLOW_COPY(MessageBuilder);
Chris@47 155
Chris@47 156 struct SegmentInit {
Chris@47 157 kj::ArrayPtr<word> space;
Chris@47 158
Chris@47 159 size_t wordsUsed;
Chris@47 160 // Number of words in `space` which are used; the rest are free space in which additional
Chris@47 161 // objects may be allocated.
Chris@47 162 };
Chris@47 163
Chris@47 164 explicit MessageBuilder(kj::ArrayPtr<SegmentInit> segments);
Chris@47 165 // Create a MessageBuilder backed by existing memory. This is an advanced interface that most
Chris@47 166 // people should not use. THIS METHOD IS INSECURE; see below.
Chris@47 167 //
Chris@47 168 // This allows a MessageBuilder to be constructed to modify an in-memory message without first
Chris@47 169 // making a copy of the content. This is especially useful in conjunction with mmap().
Chris@47 170 //
Chris@47 171 // The contents of each segment must outlive the MessageBuilder, but the SegmentInit array itself
Chris@47 172 // only need outlive the constructor.
Chris@47 173 //
Chris@47 174 // SECURITY: Do not use this in conjunction with untrusted data. This constructor assumes that
Chris@47 175 // the input message is valid. This constructor is designed to be used with data you control,
Chris@47 176 // e.g. an mmap'd file which is owned and accessed by only one program. When reading data you
Chris@47 177 // do not trust, you *must* load it into a Reader and then copy into a Builder as a means of
Chris@47 178 // validating the content.
Chris@47 179 //
Chris@47 180 // WARNING: It is NOT safe to initialize a MessageBuilder in this way from memory that is
Chris@47 181 // currently in use by another MessageBuilder or MessageReader. Other readers/builders will
Chris@47 182 // not observe changes to the segment sizes nor newly-allocated segments caused by allocating
Chris@47 183 // new objects in this message.
Chris@47 184
Chris@47 185 virtual kj::ArrayPtr<word> allocateSegment(uint minimumSize) = 0;
Chris@47 186 // Allocates an array of at least the given number of words, throwing an exception or crashing if
Chris@47 187 // this is not possible. It is expected that this method will usually return more space than
Chris@47 188 // requested, and the caller should use that extra space as much as possible before allocating
Chris@47 189 // more. The returned space remains valid at least until the MessageBuilder is destroyed.
Chris@47 190 //
Chris@47 191 // Cap'n Proto will only call this once at a time, so the subclass need not worry about
Chris@47 192 // thread-safety.
Chris@47 193
Chris@47 194 template <typename RootType>
Chris@47 195 typename RootType::Builder initRoot();
Chris@47 196 // Initialize the root struct of the message as the given struct type.
Chris@47 197
Chris@47 198 template <typename Reader>
Chris@47 199 void setRoot(Reader&& value);
Chris@47 200 // Set the root struct to a deep copy of the given struct.
Chris@47 201
Chris@47 202 template <typename RootType>
Chris@47 203 typename RootType::Builder getRoot();
Chris@47 204 // Get the root struct of the message, interpreting it as the given struct type.
Chris@47 205
Chris@47 206 template <typename RootType, typename SchemaType>
Chris@47 207 typename RootType::Builder getRoot(SchemaType schema);
Chris@47 208 // Dynamically interpret the root struct of the message using the given schema (a StructSchema).
Chris@47 209 // RootType in this case must be DynamicStruct, and you must #include <capnp/dynamic.h> to
Chris@47 210 // use this.
Chris@47 211
Chris@47 212 template <typename RootType, typename SchemaType>
Chris@47 213 typename RootType::Builder initRoot(SchemaType schema);
Chris@47 214 // Dynamically init the root struct of the message using the given schema (a StructSchema).
Chris@47 215 // RootType in this case must be DynamicStruct, and you must #include <capnp/dynamic.h> to
Chris@47 216 // use this.
Chris@47 217
Chris@47 218 template <typename T>
Chris@47 219 void adoptRoot(Orphan<T>&& orphan);
Chris@47 220 // Like setRoot() but adopts the orphan without copying.
Chris@47 221
Chris@47 222 kj::ArrayPtr<const kj::ArrayPtr<const word>> getSegmentsForOutput();
Chris@47 223 // Get the raw data that makes up the message.
Chris@47 224
Chris@47 225 Orphanage getOrphanage();
Chris@47 226
Chris@47 227 bool isCanonical();
Chris@47 228 // Check whether the message builder is in canonical form
Chris@47 229
Chris@47 230 private:
Chris@47 231 void* arenaSpace[22];
Chris@47 232 // Space in which we can construct a BuilderArena. We don't use BuilderArena directly here
Chris@47 233 // because we don't want clients to have to #include arena.h, which itself includes a bunch of
Chris@47 234 // big STL headers. We don't use a pointer to a BuilderArena because that would require an
Chris@47 235 // extra malloc on every message which could be expensive when processing small messages.
Chris@47 236
Chris@47 237 bool allocatedArena = false;
Chris@47 238 // We have to initialize the arena lazily because when we do so we want to allocate the root
Chris@47 239 // pointer immediately, and this will allocate a segment, which requires a virtual function
Chris@47 240 // call on the MessageBuilder. We can't do such a call in the constructor since the subclass
Chris@47 241 // isn't constructed yet. This is kind of annoying because it means that getOrphanage() is
Chris@47 242 // not thread-safe, but that shouldn't be a huge deal...
Chris@47 243
Chris@47 244 _::BuilderArena* arena() { return reinterpret_cast<_::BuilderArena*>(arenaSpace); }
Chris@47 245 _::SegmentBuilder* getRootSegment();
Chris@47 246 AnyPointer::Builder getRootInternal();
Chris@47 247 };
Chris@47 248
Chris@47 249 template <typename RootType>
Chris@47 250 typename RootType::Reader readMessageUnchecked(const word* data);
Chris@47 251 // IF THE INPUT IS INVALID, THIS MAY CRASH, CORRUPT MEMORY, CREATE A SECURITY HOLE IN YOUR APP,
Chris@47 252 // MURDER YOUR FIRST-BORN CHILD, AND/OR BRING ABOUT ETERNAL DAMNATION ON ALL OF HUMANITY. DO NOT
Chris@47 253 // USE UNLESS YOU UNDERSTAND THE CONSEQUENCES.
Chris@47 254 //
Chris@47 255 // Given a pointer to a known-valid message located in a single contiguous memory segment,
Chris@47 256 // returns a reader for that message. No bounds-checking will be done while traversing this
Chris@47 257 // message. Use this only if you have already verified that all pointers are valid and in-bounds,
Chris@47 258 // and there are no far pointers in the message.
Chris@47 259 //
Chris@47 260 // To create a message that can be passed to this function, build a message using a MallocAllocator
Chris@47 261 // whose preferred segment size is larger than the message size. This guarantees that the message
Chris@47 262 // will be allocated as a single segment, meaning getSegmentsForOutput() returns a single word
Chris@47 263 // array. That word array is your message; you may pass a pointer to its first word into
Chris@47 264 // readMessageUnchecked() to read the message.
Chris@47 265 //
Chris@47 266 // This can be particularly handy for embedding messages in generated code: you can
Chris@47 267 // embed the raw bytes (using AlignedData) then make a Reader for it using this. This is the way
Chris@47 268 // default values are embedded in code generated by the Cap'n Proto compiler. E.g., if you have
Chris@47 269 // a message MyMessage, you can read its default value like so:
Chris@47 270 // MyMessage::Reader reader = Message<MyMessage>::readMessageUnchecked(MyMessage::DEFAULT.words);
Chris@47 271 //
Chris@47 272 // To sanitize a message from an untrusted source such that it can be safely passed to
Chris@47 273 // readMessageUnchecked(), use copyToUnchecked().
Chris@47 274
Chris@47 275 template <typename Reader>
Chris@47 276 void copyToUnchecked(Reader&& reader, kj::ArrayPtr<word> uncheckedBuffer);
Chris@47 277 // Copy the content of the given reader into the given buffer, such that it can safely be passed to
Chris@47 278 // readMessageUnchecked(). The buffer's size must be exactly reader.totalSizeInWords() + 1,
Chris@47 279 // otherwise an exception will be thrown. The buffer must be zero'd before calling.
Chris@47 280
Chris@47 281 template <typename RootType>
Chris@47 282 typename RootType::Reader readDataStruct(kj::ArrayPtr<const word> data);
Chris@47 283 // Interprets the given data as a single, data-only struct. Only primitive fields (booleans,
Chris@47 284 // numbers, and enums) will be readable; all pointers will be null. This is useful if you want
Chris@47 285 // to use Cap'n Proto as a language/platform-neutral way to pack some bits.
Chris@47 286 //
Chris@47 287 // The input is a word array rather than a byte array to enforce alignment. If you have a byte
Chris@47 288 // array which you know is word-aligned (or if your platform supports unaligned reads and you don't
Chris@47 289 // mind the performance penalty), then you can use `reinterpret_cast` to convert a byte array into
Chris@47 290 // a word array:
Chris@47 291 //
Chris@47 292 // kj::arrayPtr(reinterpret_cast<const word*>(bytes.begin()),
Chris@47 293 // reinterpret_cast<const word*>(bytes.end()))
Chris@47 294
Chris@47 295 template <typename BuilderType>
Chris@47 296 typename kj::ArrayPtr<const word> writeDataStruct(BuilderType builder);
Chris@47 297 // Given a struct builder, get the underlying data section as a word array, suitable for passing
Chris@47 298 // to `readDataStruct()`.
Chris@47 299 //
Chris@47 300 // Note that you may call `.toBytes()` on the returned value to convert to `ArrayPtr<const byte>`.
Chris@47 301
Chris@47 302 template <typename Type>
Chris@47 303 static typename Type::Reader defaultValue();
Chris@47 304 // Get a default instance of the given struct or list type.
Chris@47 305 //
Chris@47 306 // TODO(cleanup): Find a better home for this function?
Chris@47 307
Chris@47 308 // =======================================================================================
Chris@47 309
Chris@47 310 class SegmentArrayMessageReader: public MessageReader {
Chris@47 311 // A simple MessageReader that reads from an array of word arrays representing all segments.
Chris@47 312 // In particular you can read directly from the output of MessageBuilder::getSegmentsForOutput()
Chris@47 313 // (although it would probably make more sense to call builder.getRoot().asReader() in that case).
Chris@47 314
Chris@47 315 public:
Chris@47 316 SegmentArrayMessageReader(kj::ArrayPtr<const kj::ArrayPtr<const word>> segments,
Chris@47 317 ReaderOptions options = ReaderOptions());
Chris@47 318 // Creates a message pointing at the given segment array, without taking ownership of the
Chris@47 319 // segments. All arrays passed in must remain valid until the MessageReader is destroyed.
Chris@47 320
Chris@47 321 KJ_DISALLOW_COPY(SegmentArrayMessageReader);
Chris@47 322 ~SegmentArrayMessageReader() noexcept(false);
Chris@47 323
Chris@47 324 virtual kj::ArrayPtr<const word> getSegment(uint id) override;
Chris@47 325
Chris@47 326 private:
Chris@47 327 kj::ArrayPtr<const kj::ArrayPtr<const word>> segments;
Chris@47 328 };
Chris@47 329
Chris@47 330 enum class AllocationStrategy: uint8_t {
Chris@47 331 FIXED_SIZE,
Chris@47 332 // The builder will prefer to allocate the same amount of space for each segment with no
Chris@47 333 // heuristic growth. It will still allocate larger segments when the preferred size is too small
Chris@47 334 // for some single object. This mode is generally not recommended, but can be particularly useful
Chris@47 335 // for testing in order to force a message to allocate a predictable number of segments. Note
Chris@47 336 // that you can force every single object in the message to be located in a separate segment by
Chris@47 337 // using this mode with firstSegmentWords = 0.
Chris@47 338
Chris@47 339 GROW_HEURISTICALLY
Chris@47 340 // The builder will heuristically decide how much space to allocate for each segment. Each
Chris@47 341 // allocated segment will be progressively larger than the previous segments on the assumption
Chris@47 342 // that message sizes are exponentially distributed. The total number of segments that will be
Chris@47 343 // allocated for a message of size n is O(log n).
Chris@47 344 };
Chris@47 345
Chris@47 346 constexpr uint SUGGESTED_FIRST_SEGMENT_WORDS = 1024;
Chris@47 347 constexpr AllocationStrategy SUGGESTED_ALLOCATION_STRATEGY = AllocationStrategy::GROW_HEURISTICALLY;
Chris@47 348
Chris@47 349 class MallocMessageBuilder: public MessageBuilder {
Chris@47 350 // A simple MessageBuilder that uses malloc() (actually, calloc()) to allocate segments. This
Chris@47 351 // implementation should be reasonable for any case that doesn't require writing the message to
Chris@47 352 // a specific location in memory.
Chris@47 353
Chris@47 354 public:
Chris@47 355 explicit MallocMessageBuilder(uint firstSegmentWords = SUGGESTED_FIRST_SEGMENT_WORDS,
Chris@47 356 AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY);
Chris@47 357 // Creates a BuilderContext which allocates at least the given number of words for the first
Chris@47 358 // segment, and then uses the given strategy to decide how much to allocate for subsequent
Chris@47 359 // segments. When choosing a value for firstSegmentWords, consider that:
Chris@47 360 // 1) Reading and writing messages gets slower when multiple segments are involved, so it's good
Chris@47 361 // if most messages fit in a single segment.
Chris@47 362 // 2) Unused bytes will not be written to the wire, so generally it is not a big deal to allocate
Chris@47 363 // more space than you need. It only becomes problematic if you are allocating many messages
Chris@47 364 // in parallel and thus use lots of memory, or if you allocate so much extra space that just
Chris@47 365 // zeroing it out becomes a bottleneck.
Chris@47 366 // The defaults have been chosen to be reasonable for most people, so don't change them unless you
Chris@47 367 // have reason to believe you need to.
Chris@47 368
Chris@47 369 explicit MallocMessageBuilder(kj::ArrayPtr<word> firstSegment,
Chris@47 370 AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY);
Chris@47 371 // This version always returns the given array for the first segment, and then proceeds with the
Chris@47 372 // allocation strategy. This is useful for optimization when building lots of small messages in
Chris@47 373 // a tight loop: you can reuse the space for the first segment.
Chris@47 374 //
Chris@47 375 // firstSegment MUST be zero-initialized. MallocMessageBuilder's destructor will write new zeros
Chris@47 376 // over any space that was used so that it can be reused.
Chris@47 377
Chris@47 378 KJ_DISALLOW_COPY(MallocMessageBuilder);
Chris@47 379 virtual ~MallocMessageBuilder() noexcept(false);
Chris@47 380
Chris@47 381 virtual kj::ArrayPtr<word> allocateSegment(uint minimumSize) override;
Chris@47 382
Chris@47 383 private:
Chris@47 384 uint nextSize;
Chris@47 385 AllocationStrategy allocationStrategy;
Chris@47 386
Chris@47 387 bool ownFirstSegment;
Chris@47 388 bool returnedFirstSegment;
Chris@47 389
Chris@47 390 void* firstSegment;
Chris@47 391
Chris@47 392 struct MoreSegments;
Chris@47 393 kj::Maybe<kj::Own<MoreSegments>> moreSegments;
Chris@47 394 };
Chris@47 395
Chris@47 396 class FlatMessageBuilder: public MessageBuilder {
Chris@47 397 // THIS IS NOT THE CLASS YOU'RE LOOKING FOR.
Chris@47 398 //
Chris@47 399 // If you want to write a message into already-existing scratch space, use `MallocMessageBuilder`
Chris@47 400 // and pass the scratch space to its constructor. It will then only fall back to malloc() if
Chris@47 401 // the scratch space is not large enough.
Chris@47 402 //
Chris@47 403 // Do NOT use this class unless you really know what you're doing. This class is problematic
Chris@47 404 // because it requires advance knowledge of the size of your message, which is usually impossible
Chris@47 405 // to determine without actually building the message. The class was created primarily to
Chris@47 406 // implement `copyToUnchecked()`, which itself exists only to support other internal parts of
Chris@47 407 // the Cap'n Proto implementation.
Chris@47 408
Chris@47 409 public:
Chris@47 410 explicit FlatMessageBuilder(kj::ArrayPtr<word> array);
Chris@47 411 KJ_DISALLOW_COPY(FlatMessageBuilder);
Chris@47 412 virtual ~FlatMessageBuilder() noexcept(false);
Chris@47 413
Chris@47 414 void requireFilled();
Chris@47 415 // Throws an exception if the flat array is not exactly full.
Chris@47 416
Chris@47 417 virtual kj::ArrayPtr<word> allocateSegment(uint minimumSize) override;
Chris@47 418
Chris@47 419 private:
Chris@47 420 kj::ArrayPtr<word> array;
Chris@47 421 bool allocated;
Chris@47 422 };
Chris@47 423
Chris@47 424 // =======================================================================================
Chris@47 425 // implementation details
Chris@47 426
Chris@47 427 inline const ReaderOptions& MessageReader::getOptions() {
Chris@47 428 return options;
Chris@47 429 }
Chris@47 430
Chris@47 431 template <typename RootType>
Chris@47 432 inline typename RootType::Reader MessageReader::getRoot() {
Chris@47 433 return getRootInternal().getAs<RootType>();
Chris@47 434 }
Chris@47 435
Chris@47 436 template <typename RootType>
Chris@47 437 inline typename RootType::Builder MessageBuilder::initRoot() {
Chris@47 438 return getRootInternal().initAs<RootType>();
Chris@47 439 }
Chris@47 440
Chris@47 441 template <typename Reader>
Chris@47 442 inline void MessageBuilder::setRoot(Reader&& value) {
Chris@47 443 getRootInternal().setAs<FromReader<Reader>>(value);
Chris@47 444 }
Chris@47 445
Chris@47 446 template <typename RootType>
Chris@47 447 inline typename RootType::Builder MessageBuilder::getRoot() {
Chris@47 448 return getRootInternal().getAs<RootType>();
Chris@47 449 }
Chris@47 450
Chris@47 451 template <typename T>
Chris@47 452 void MessageBuilder::adoptRoot(Orphan<T>&& orphan) {
Chris@47 453 return getRootInternal().adopt(kj::mv(orphan));
Chris@47 454 }
Chris@47 455
Chris@47 456 template <typename RootType, typename SchemaType>
Chris@47 457 typename RootType::Reader MessageReader::getRoot(SchemaType schema) {
Chris@47 458 return getRootInternal().getAs<RootType>(schema);
Chris@47 459 }
Chris@47 460
Chris@47 461 template <typename RootType, typename SchemaType>
Chris@47 462 typename RootType::Builder MessageBuilder::getRoot(SchemaType schema) {
Chris@47 463 return getRootInternal().getAs<RootType>(schema);
Chris@47 464 }
Chris@47 465
Chris@47 466 template <typename RootType, typename SchemaType>
Chris@47 467 typename RootType::Builder MessageBuilder::initRoot(SchemaType schema) {
Chris@47 468 return getRootInternal().initAs<RootType>(schema);
Chris@47 469 }
Chris@47 470
Chris@47 471 template <typename RootType>
Chris@47 472 typename RootType::Reader readMessageUnchecked(const word* data) {
Chris@47 473 return AnyPointer::Reader(_::PointerReader::getRootUnchecked(data)).getAs<RootType>();
Chris@47 474 }
Chris@47 475
Chris@47 476 template <typename Reader>
Chris@47 477 void copyToUnchecked(Reader&& reader, kj::ArrayPtr<word> uncheckedBuffer) {
Chris@47 478 FlatMessageBuilder builder(uncheckedBuffer);
Chris@47 479 builder.setRoot(kj::fwd<Reader>(reader));
Chris@47 480 builder.requireFilled();
Chris@47 481 }
Chris@47 482
Chris@47 483 template <typename RootType>
Chris@47 484 typename RootType::Reader readDataStruct(kj::ArrayPtr<const word> data) {
Chris@47 485 return typename RootType::Reader(_::StructReader(data));
Chris@47 486 }
Chris@47 487
Chris@47 488 template <typename BuilderType>
Chris@47 489 typename kj::ArrayPtr<const word> writeDataStruct(BuilderType builder) {
Chris@47 490 auto bytes = _::PointerHelpers<FromBuilder<BuilderType>>::getInternalBuilder(kj::mv(builder))
Chris@47 491 .getDataSectionAsBlob();
Chris@47 492 return kj::arrayPtr(reinterpret_cast<word*>(bytes.begin()),
Chris@47 493 reinterpret_cast<word*>(bytes.end()));
Chris@47 494 }
Chris@47 495
Chris@47 496 template <typename Type>
Chris@47 497 static typename Type::Reader defaultValue() {
Chris@47 498 return typename Type::Reader(_::StructReader());
Chris@47 499 }
Chris@47 500
Chris@47 501 template <typename T>
Chris@47 502 kj::Array<word> canonicalize(T&& reader) {
Chris@47 503 return _::PointerHelpers<FromReader<T>>::getInternalReader(reader).canonicalize();
Chris@47 504 }
Chris@47 505
Chris@47 506 } // namespace capnp
Chris@47 507
Chris@47 508 #endif // CAPNP_MESSAGE_H_