annotate win64-msvc/include/capnp/message.h @ 148:b4bfdf10c4b3

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