layout.h 43.6 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21

Kenton Varda's avatar
Kenton Varda committed
22 23
// This file is NOT intended for use by clients, except in generated code.
//
Kenton Varda's avatar
Kenton Varda committed
24 25 26 27
// This file defines low-level, non-type-safe classes for traversing the Cap'n Proto memory layout
// (which is also its wire format).  Code generated by the Cap'n Proto compiler uses these classes,
// as does other parts of the Cap'n proto library which provide a higher-level interface for
// dynamic introspection.
Kenton Varda's avatar
Kenton Varda committed
28

Kenton Varda's avatar
Kenton Varda committed
29 30
#ifndef CAPNP_LAYOUT_H_
#define CAPNP_LAYOUT_H_
31

Kenton Varda's avatar
Kenton Varda committed
32
#include <kj/common.h>
33
#include <kj/memory.h>
34
#include "common.h"
Kenton Varda's avatar
Kenton Varda committed
35
#include "blob.h"
36
#include "endian.h"
37

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#if __mips__ && !defined(CAPNP_CANONICALIZE_NAN)
#define CAPNP_CANONICALIZE_NAN 1
// Explicitly detect NaNs and canonicalize them to the quiet NaN value as would be returned by
// __builtin_nan("") on systems implementing the IEEE-754 recommended (but not required) NaN
// signalling/quiet differentiation (such as x86).  Unfortunately, some architectures -- in
// particular, MIPS -- represent quiet vs. signalling nans differently than the rest of the world.
// Canonicalizing them makes output consistent (which is important!), but hurts performance
// slightly.
//
// Note that trying to convert MIPS NaNs to standard NaNs without losing data doesn't work.
// Signaling vs. quiet is indicated by a bit, with the meaning being the opposite on MIPS vs.
// everyone else.  It would be great if we could just flip that bit, but we can't, because if the
// significand is all-zero, then the value is infinity rather than NaN.  This means that on most
// machines, where the bit indicates quietness, there is one more quiet NaN value than signalling
// NaN value, whereas on MIPS there is one more sNaN than qNaN, and thus there is no isomorphic
// mapping that properly preserves quietness.  Instead of doing something hacky, we just give up
// and blow away NaN payloads, because no one uses them anyway.
#endif

57
namespace capnp {
58

59
class ClientHook;
60

61
namespace _ {  // private
Kenton Varda's avatar
Kenton Varda committed
62

63 64
class PointerBuilder;
class PointerReader;
65 66 67 68
class StructBuilder;
class StructReader;
class ListBuilder;
class ListReader;
69
class OrphanBuilder;
70
struct WirePointer;
71
struct WireHelpers;
72 73
class SegmentReader;
class SegmentBuilder;
74
class Arena;
75
class BuilderArena;
76

77
// =============================================================================
78 79

enum class FieldSize: uint8_t {
80
  // TODO(cleanup):  Rename to FieldLayout or maybe ValueLayout.
81

82 83 84 85 86
  // Notice that each member of this enum, when representing a list element size, represents a
  // size that is greater than or equal to the previous members, since INLINE_COMPOSITE is used
  // only for multi-word structs.  This is important because it allows us to compare FieldSize
  // values for the purpose of deciding when we need to upgrade a list.

87 88 89 90 91 92 93
  VOID = 0,
  BIT = 1,
  BYTE = 2,
  TWO_BYTES = 3,
  FOUR_BYTES = 4,
  EIGHT_BYTES = 5,

94
  POINTER = 6,  // Indicates that the field lives in the pointer section, not the data section.
95 96 97 98

  INLINE_COMPOSITE = 7
  // A composite type of fixed width.  This serves two purposes:
  // 1) For lists of composite types where all the elements would have the exact same width,
99
  //    allocating a list of pointers which in turn point at the elements would waste space.  We
100 101 102
  //    can avoid a layer of indirection by placing all the elements in a flat sequence, and only
  //    indicating the element properties (e.g. field count for structs) once.
  //
103 104
  //    Specifically, a list pointer indicating INLINE_COMPOSITE element size actually points to
  //    a "tag" describing one element.  This tag is formatted like a wire pointer, but the
105
  //    "offset" instead stores the element count of the list.  The flat list of elements appears
106
  //    immediately after the tag.  In the list pointer itself, the element count is replaced with
107 108 109
  //    a word count for the whole list (excluding tag).  This allows the tag and elements to be
  //    precached in a single step rather than two sequential steps.
  //
110
  //    It is NOT intended to be possible to substitute an INLINE_COMPOSITE list for a POINTER
111 112 113 114 115 116 117 118 119 120
  //    list or vice-versa without breaking recipients.  Recipients expect one or the other
  //    depending on the message definition.
  //
  //    However, it IS allowed to substitute an INLINE_COMPOSITE list -- specifically, of structs --
  //    when a list was expected, or vice versa, with the assumption that the first field of the
  //    struct (field number zero) correspond to the element type.  This allows a list of
  //    primitives to be upgraded to a list of structs, avoiding the need to use parallel arrays
  //    when you realize that you need to attach some extra information to each element of some
  //    primitive list.
  //
121 122
  // 2) At one point there was a notion of "inline" struct fields, but it was deemed too much of
  //    an implementation burden for too little gain, and so was deleted.
123 124 125
};

typedef decltype(BITS / ELEMENTS) BitsPerElement;
126
typedef decltype(POINTERS / ELEMENTS) PointersPerElement;
127

Kenton Varda's avatar
Kenton Varda committed
128 129 130 131 132 133 134 135 136 137
static constexpr BitsPerElement BITS_PER_ELEMENT_TABLE[8] = {
    0 * BITS / ELEMENTS,
    1 * BITS / ELEMENTS,
    8 * BITS / ELEMENTS,
    16 * BITS / ELEMENTS,
    32 * BITS / ELEMENTS,
    64 * BITS / ELEMENTS,
    0 * BITS / ELEMENTS,
    0 * BITS / ELEMENTS
};
138

139
inline constexpr BitsPerElement dataBitsPerElement(FieldSize size) {
140
  return _::BITS_PER_ELEMENT_TABLE[static_cast<int>(size)];
141 142
}

143
inline constexpr PointersPerElement pointersPerElement(FieldSize size) {
144
  return size == FieldSize::POINTER ? 1 * POINTERS / ELEMENTS : 0 * POINTERS / ELEMENTS;
145 146
}

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
template <size_t size> struct ElementSizeForByteSize;
template <> struct ElementSizeForByteSize<1> { static constexpr FieldSize value = FieldSize::BYTE; };
template <> struct ElementSizeForByteSize<2> { static constexpr FieldSize value = FieldSize::TWO_BYTES; };
template <> struct ElementSizeForByteSize<4> { static constexpr FieldSize value = FieldSize::FOUR_BYTES; };
template <> struct ElementSizeForByteSize<8> { static constexpr FieldSize value = FieldSize::EIGHT_BYTES; };

template <typename T> struct ElementSizeForType {
  static constexpr FieldSize value =
      // Primitive types that aren't special-cased below can be determined from sizeof().
      kind<T>() == Kind::PRIMITIVE ? ElementSizeForByteSize<sizeof(T)>::value :
      kind<T>() == Kind::ENUM ? FieldSize::TWO_BYTES :
      kind<T>() == Kind::STRUCT ? FieldSize::INLINE_COMPOSITE :

      // Everything else is a pointer.
      FieldSize::POINTER;
162 163
};

164 165 166
// Void and bool are special.
template <> struct ElementSizeForType<Void> { static constexpr FieldSize value = FieldSize::VOID; };
template <> struct ElementSizeForType<bool> { static constexpr FieldSize value = FieldSize::BIT; };
167

168 169 170 171 172 173 174 175 176 177
// Lists and blobs are pointers, not structs.
template <typename T, bool b> struct ElementSizeForType<List<T, b>> {
  static constexpr FieldSize value = FieldSize::POINTER;
};
template <> struct ElementSizeForType<Text> {
  static constexpr FieldSize value = FieldSize::POINTER;
};
template <> struct ElementSizeForType<Data> {
  static constexpr FieldSize value = FieldSize::POINTER;
};
178

179 180 181 182 183
template <typename T>
inline constexpr FieldSize elementSizeForType() {
  return ElementSizeForType<T>::value;
}

184 185 186 187 188 189 190 191 192 193 194 195 196 197
struct MessageSizeCounts {
  WordCount64 wordCount;
  uint capCount;

  MessageSizeCounts& operator+=(const MessageSizeCounts& other) {
    wordCount += other.wordCount;
    capCount += other.capCount;
    return *this;
  }

  MessageSize asPublic() {
    return MessageSize { wordCount / WORDS, capCount };
  }
};
198 199 200

// =============================================================================

201 202 203 204 205 206 207 208 209
template <int wordCount>
union AlignedData {
  // Useful for declaring static constant data blobs as an array of bytes, but forcing those
  // bytes to be word-aligned.

  uint8_t bytes[wordCount * sizeof(word)];
  word words[wordCount];
};

210 211
struct StructSize {
  WordCount16 data;
212
  WirePointerCount16 pointers;
213

214 215 216 217
  FieldSize preferredListEncoding;
  // Preferred size to use when encoding a list of this struct.  This is INLINE_COMPOSITE if and
  // only if the struct is larger than one word; otherwise the struct list can be encoded more
  // efficiently by encoding it as if it were some primitive type.
218

219
  inline constexpr WordCount total() const { return data + pointers * WORDS_PER_POINTER; }
220 221

  StructSize() = default;
222
  inline constexpr StructSize(WordCount data, WirePointerCount pointers,
223 224
                              FieldSize preferredListEncoding)
      : data(data), pointers(pointers), preferredListEncoding(preferredListEncoding) {}
225 226
};

227
template <typename T> struct StructSize_;
228 229
// Specialized for every struct type with member:  static constexpr StructSize value"

230
template <typename T, typename = typename StructSize_<T>::Exists>
231
inline constexpr StructSize structSize() {
232
  return StructSize_<T>::value;
233
}
234 235 236 237
template <typename T, typename CapnpPrivate = typename T::_capnpPrivate, bool = false>
inline constexpr StructSize structSize() {
  return CapnpPrivate::structSize;
}
238

239 240
// -------------------------------------------------------------------
// Masking of default values
241

242 243 244 245 246
template <typename T, Kind kind = kind<T>()> struct Mask_;
template <typename T> struct Mask_<T, Kind::PRIMITIVE> { typedef T Type; };
template <typename T> struct Mask_<T, Kind::ENUM> { typedef uint16_t Type; };
template <> struct Mask_<float, Kind::PRIMITIVE> { typedef uint32_t Type; };
template <> struct Mask_<double, Kind::PRIMITIVE> { typedef uint64_t Type; };
247

248
template <typename T> struct Mask_<T, Kind::OTHER> {
249 250 251
  // Union discriminants end up here.
  static_assert(sizeof(T) == 2, "Don't know how to mask this type.");
  typedef uint16_t Type;
252 253
};

254
template <typename T>
255
using Mask = typename Mask_<T>::Type;
256 257

template <typename T>
258
KJ_ALWAYS_INLINE(Mask<T> mask(T value, Mask<T> mask));
259
template <typename T>
260
KJ_ALWAYS_INLINE(T unmask(Mask<T> value, Mask<T> mask));
261 262

template <typename T>
263 264
inline Mask<T> mask(T value, Mask<T> mask) {
  return static_cast<Mask<T> >(value) ^ mask;
265 266 267 268
}

template <>
inline uint32_t mask<float>(float value, uint32_t mask) {
269 270
#if CAPNP_CANONICALIZE_NAN
  if (value != value) {
271
    return 0x7fc00000u ^ mask;
272 273 274
  }
#endif

275 276 277 278 279 280 281 282
  uint32_t i;
  static_assert(sizeof(i) == sizeof(value), "float is not 32 bits?");
  memcpy(&i, &value, sizeof(value));
  return i ^ mask;
}

template <>
inline uint64_t mask<double>(double value, uint64_t mask) {
283 284
#if CAPNP_CANONICALIZE_NAN
  if (value != value) {
285
    return 0x7ff8000000000000ull ^ mask;
286 287 288
  }
#endif

289 290 291 292 293 294 295
  uint64_t i;
  static_assert(sizeof(i) == sizeof(value), "double is not 64 bits?");
  memcpy(&i, &value, sizeof(value));
  return i ^ mask;
}

template <typename T>
296
inline T unmask(Mask<T> value, Mask<T> mask) {
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  return static_cast<T>(value ^ mask);
}

template <>
inline float unmask<float>(uint32_t value, uint32_t mask) {
  value ^= mask;
  float result;
  static_assert(sizeof(result) == sizeof(value), "float is not 32 bits?");
  memcpy(&result, &value, sizeof(value));
  return result;
}

template <>
inline double unmask<double>(uint64_t value, uint64_t mask) {
  value ^= mask;
  double result;
  static_assert(sizeof(result) == sizeof(value), "double is not 64 bits?");
  memcpy(&result, &value, sizeof(value));
  return result;
}

318 319
// -------------------------------------------------------------------

320 321 322 323 324 325
class PointerBuilder: public kj::DisallowConstCopy {
  // Represents a single pointer, usually embedded in a struct or a list.

public:
  inline PointerBuilder(): segment(nullptr), pointer(nullptr) {}

Kenton Varda's avatar
Kenton Varda committed
326 327 328 329
  static inline PointerBuilder getRoot(SegmentBuilder* segment, word* location);
  // Get a PointerBuilder representing a message root located in the given segment at the given
  // location.

330 331 332
  bool isNull();

  StructBuilder getStruct(StructSize size, const word* defaultValue);
David Renshaw's avatar
David Renshaw committed
333
  ListBuilder getList(FieldSize elementSize, const word* defaultValue);
334 335
  ListBuilder getStructList(StructSize elementSize, const word* defaultValue);
  template <typename T> typename T::Builder getBlob(const void* defaultValue,ByteCount defaultSize);
336
  kj::Own<ClientHook> getCapability();
337 338 339 340 341 342 343 344 345 346 347 348 349 350
  // Get methods:  Get the value.  If it is null, initialize it to a copy of the default value.
  // The default value is encoded as an "unchecked message" for structs, lists, and objects, or a
  // simple byte array for blobs.

  StructBuilder initStruct(StructSize size);
  ListBuilder initList(FieldSize elementSize, ElementCount elementCount);
  ListBuilder initStructList(ElementCount elementCount, StructSize size);
  template <typename T> typename T::Builder initBlob(ByteCount size);
  // Init methods:  Initialize the pointer to a newly-allocated object, discarding the existing
  // object.

  void setStruct(const StructReader& value);
  void setList(const ListReader& value);
  template <typename T> void setBlob(typename T::Reader value);
351
  void setCapability(kj::Own<ClientHook>&& cap);
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
  // Set methods:  Initialize the pointer to a newly-allocated copy of the given value, discarding
  // the existing object.

  void adopt(OrphanBuilder&& orphan);
  // Set the pointer to point at the given orphaned value.

  OrphanBuilder disown();
  // Set the pointer to null and return its previous value as an orphan.

  void clear();
  // Clear the pointer to null, discarding its previous value.

  void transferFrom(PointerBuilder other);
  // Equivalent to `adopt(other.disown())`.

  void copyFrom(PointerReader other);
  // Equivalent to `set(other.get())`.

370 371
  PointerReader asReader() const;

372
  BuilderArena* getArena() const;
373 374
  // Get the arena containing this pointer.

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
private:
  SegmentBuilder* segment;     // Memory segment in which the pointer resides.
  WirePointer* pointer;        // Pointer to the pointer.

  inline PointerBuilder(SegmentBuilder* segment, WirePointer* pointer)
      : segment(segment), pointer(pointer) {}

  friend class StructBuilder;
  friend class ListBuilder;
};

class PointerReader {
public:
  inline PointerReader(): segment(nullptr), pointer(nullptr), nestingLimit(0x7fffffff) {}

Kenton Varda's avatar
Kenton Varda committed
390 391 392 393 394 395 396
  static PointerReader getRoot(SegmentReader* segment, const word* location, int nestingLimit);
  // Get a PointerReader representing a message root located in the given segment at the given
  // location.

  static inline PointerReader getRootUnchecked(const word* location);
  // Get a PointerReader for an unchecked message.

397
  MessageSizeCounts targetSize() const;
Kenton Varda's avatar
Kenton Varda committed
398 399 400 401 402 403
  // Return the total size of the target object and everything to which it points.  Does not count
  // far pointer overhead.  This is useful for deciding how much space is needed to copy the object
  // into a flat array.  However, the caller is advised NOT to treat this value as secure.  Instead,
  // use the result as a hint for allocating the first segment, do the copy, and then throw an
  // exception if it overruns.

404 405 406 407 408 409
  bool isNull() const;

  StructReader getStruct(const word* defaultValue) const;
  ListReader getList(FieldSize expectedElementSize, const word* defaultValue) const;
  template <typename T>
  typename T::Reader getBlob(const void* defaultValue, ByteCount defaultSize) const;
410
  kj::Own<ClientHook> getCapability() const;
411 412 413 414 415 416 417 418 419
  // Get methods:  Get the value.  If it is null, return the default value instead.
  // The default value is encoded as an "unchecked message" for structs, lists, and objects, or a
  // simple byte array for blobs.

  const word* getUnchecked() const;
  // If this is an unchecked message, get a word* pointing at the location of the pointer.  This
  // word* can actually be passed to readUnchecked() to read the designated sub-object later.  If
  // this isn't an unchecked message, throws an exception.

420 421 422
  kj::Maybe<Arena&> getArena() const;
  // Get the arena containing this pointer.

423 424 425 426 427 428 429 430 431 432 433 434 435
private:
  SegmentReader* segment;      // Memory segment in which the pointer resides.
  const WirePointer* pointer;  // Pointer to the pointer.  null = treat as null pointer.

  int nestingLimit;
  // Limits the depth of message structures to guard against stack-overflow-based DoS attacks.
  // Once this reaches zero, further pointers will be pruned.

  inline PointerReader(SegmentReader* segment, const WirePointer* pointer, int nestingLimit)
      : segment(segment), pointer(pointer), nestingLimit(nestingLimit) {}

  friend class StructReader;
  friend class ListReader;
436
  friend class PointerBuilder;
437
  friend class OrphanBuilder;
438 439
};

440
// -------------------------------------------------------------------
Kenton Varda's avatar
Kenton Varda committed
441

442
class StructBuilder: public kj::DisallowConstCopy {
443
public:
444
  inline StructBuilder(): segment(nullptr), data(nullptr), pointers(nullptr), bit0Offset(0) {}
445

446 447 448 449
  inline word* getLocation() { return reinterpret_cast<word*>(data); }
  // Get the object's location.  Only valid for independently-allocated objects (i.e. not list
  // elements).

450
  inline BitCount getDataSectionSize() const { return dataSize; }
451
  inline WirePointerCount getPointerSectionSize() const { return pointerCount; }
452 453
  inline Data::Builder getDataSectionAsBlob();

454 455 456 457
  template <typename T>
  KJ_ALWAYS_INLINE(bool hasDataField(ElementCount offset));
  // Return true if the field is set to something other than its default value.

458
  template <typename T>
459
  KJ_ALWAYS_INLINE(T getDataField(ElementCount offset));
460
  // Gets the data field value of the given type at the given offset.  The offset is measured in
461 462
  // multiples of the field size, determined by the type.

463
  template <typename T>
464
  KJ_ALWAYS_INLINE(T getDataField(ElementCount offset, Mask<T> mask));
465 466 467
  // Like getDataField() but applies the given XOR mask to the data on load.  Used for reading
  // fields with non-zero default values.

468
  template <typename T>
469
  KJ_ALWAYS_INLINE(void setDataField(
470
      ElementCount offset, kj::NoInfer<T> value));
471 472
  // Sets the data field value at the given offset.

473
  template <typename T>
474
  KJ_ALWAYS_INLINE(void setDataField(
475
      ElementCount offset, kj::NoInfer<T> value, Mask<T> mask));
476 477 478
  // Like setDataField() but applies the given XOR mask before storing.  Used for writing fields
  // with non-zero default values.

479 480
  KJ_ALWAYS_INLINE(PointerBuilder getPointerField(WirePointerCount ptrIndex));
  // Get a builder for a pointer field given the index within the pointer section.
481

482 483 484
  void clearAll();
  // Clear all pointers and data.

485 486 487 488 489
  void transferContentFrom(StructBuilder other);
  // Adopt all pointers from `other`, and also copy all data.  If `other`'s sections are larger
  // than this, the extra data is not transferred, meaning there is a risk of data loss when
  // transferring from messages built with future versions of the protocol.

490 491 492 493 494
  void copyContentFrom(StructReader other);
  // Copy content from `other`.  If `other`'s sections are larger than this, the extra data is not
  // copied, meaning there is a risk of data loss when copying from messages built with future
  // versions of the protocol.

495
  StructReader asReader() const;
496
  // Gets a StructReader pointing at the same memory.
497

498 499 500
  BuilderArena* getArena();
  // Gets the arena in which this object is allocated.

501
private:
502
  SegmentBuilder* segment;     // Memory segment in which the struct resides.
Kenton Varda's avatar
Kenton Varda committed
503
  void* data;                  // Pointer to the encoded data.
504
  WirePointer* pointers;   // Pointer to the encoded pointers.
505

506
  BitCount32 dataSize;
507
  // Size of data section.  We use a bit count rather than a word count to more easily handle the
508 509
  // case of struct lists encoded with less than a word per element.

510
  WirePointerCount16 pointerCount;  // Size of the pointer section.
511 512 513 514 515 516

  BitCount8 bit0Offset;
  // A special hack:  If dataSize == 1 bit, then bit0Offset is the offset of that bit within the
  // byte pointed to by `data`.  In all other cases, this is zero.  This is needed to implement
  // struct lists where each struct is one bit.

517 518 519 520
  inline StructBuilder(SegmentBuilder* segment, void* data, WirePointer* pointers,
                       BitCount dataSize, WirePointerCount pointerCount, BitCount8 bit0Offset)
      : segment(segment), data(data), pointers(pointers),
        dataSize(dataSize), pointerCount(pointerCount), bit0Offset(bit0Offset) {}
521

522
  friend class ListBuilder;
523
  friend struct WireHelpers;
524
  friend class OrphanBuilder;
525 526
};

527
class StructReader {
528
public:
529
  inline StructReader()
530
      : segment(nullptr), data(nullptr), pointers(nullptr), dataSize(0),
531
        pointerCount(0), bit0Offset(0), nestingLimit(0x7fffffff) {}
532

Kenton Varda's avatar
Kenton Varda committed
533 534
  const void* getLocation() const { return data; }

535
  inline BitCount getDataSectionSize() const { return dataSize; }
536
  inline WirePointerCount getPointerSectionSize() const { return pointerCount; }
537 538
  inline Data::Reader getDataSectionAsBlob();

539 540 541 542
  template <typename T>
  KJ_ALWAYS_INLINE(bool hasDataField(ElementCount offset) const);
  // Return true if the field is set to something other than its default value.

543
  template <typename T>
544
  KJ_ALWAYS_INLINE(T getDataField(ElementCount offset) const);
545
  // Get the data field value of the given type at the given offset.  The offset is measured in
546
  // multiples of the field size, determined by the type.  Returns zero if the offset is past the
547
  // end of the struct's data section.
548 549

  template <typename T>
550
  KJ_ALWAYS_INLINE(
551
      T getDataField(ElementCount offset, Mask<T> mask) const);
552 553
  // Like getDataField(offset), but applies the given XOR mask to the result.  Used for reading
  // fields with non-zero default values.
554

555 556 557
  KJ_ALWAYS_INLINE(PointerReader getPointerField(WirePointerCount ptrIndex) const);
  // Get a reader for a pointer field given the index within the pointer section.  If the index
  // is out-of-bounds, returns a null pointer.
558

559
  MessageSizeCounts totalSize() const;
560 561 562 563 564 565
  // Return the total size of the struct and everything to which it points.  Does not count far
  // pointer overhead.  This is useful for deciding how much space is needed to copy the struct
  // into a flat array.  However, the caller is advised NOT to treat this value as secure.  Instead,
  // use the result as a hint for allocating the first segment, do the copy, and then throw an
  // exception if it overruns.

566
private:
Kenton Varda's avatar
Kenton Varda committed
567
  SegmentReader* segment;  // Memory segment in which the struct resides.
568

569
  const void* data;
570
  const WirePointer* pointers;
571

572
  BitCount32 dataSize;
573
  // Size of data section.  We use a bit count rather than a word count to more easily handle the
574 575
  // case of struct lists encoded with less than a word per element.

576
  WirePointerCount16 pointerCount;  // Size of the pointer section.
577

578 579 580 581 582 583 584 585 586 587
  BitCount8 bit0Offset;
  // A special hack:  If dataSize == 1 bit, then bit0Offset is the offset of that bit within the
  // byte pointed to by `data`.  In all other cases, this is zero.  This is needed to implement
  // struct lists where each struct is one bit.
  //
  // TODO(someday):  Consider packing this together with dataSize, since we have 10 extra bits
  //   there doing nothing -- or arguably 12 bits, if you consider that 2-bit and 4-bit sizes
  //   aren't allowed.  Consider that we could have a method like getDataSizeIn<T>() which is
  //   specialized to perform the correct shifts for each size.

588
  int nestingLimit;
589 590
  // Limits the depth of message structures to guard against stack-overflow-based DoS attacks.
  // Once this reaches zero, further pointers will be pruned.
591
  // TODO(perf):  Limit to 8 bits for better alignment?
592

593 594
  inline StructReader(SegmentReader* segment, const void* data, const WirePointer* pointers,
                      BitCount dataSize, WirePointerCount pointerCount, BitCount8 bit0Offset,
595
                      int nestingLimit)
596 597
      : segment(segment), data(data), pointers(pointers),
        dataSize(dataSize), pointerCount(pointerCount), bit0Offset(bit0Offset),
598
        nestingLimit(nestingLimit) {}
599

600 601
  friend class ListReader;
  friend class StructBuilder;
602 603 604 605 606
  friend struct WireHelpers;
};

// -------------------------------------------------------------------

607
class ListBuilder: public kj::DisallowConstCopy {
608
public:
609
  inline ListBuilder()
610
      : segment(nullptr), ptr(nullptr), elementCount(0 * ELEMENTS),
611
        step(0 * BITS / ELEMENTS) {}
612

613 614 615 616 617 618 619 620 621 622 623
  inline word* getLocation() {
    // Get the object's location.  Only valid for independently-allocated objects (i.e. not list
    // elements).

    if (step * ELEMENTS <= BITS_PER_WORD * WORDS) {
      return reinterpret_cast<word*>(ptr);
    } else {
      return reinterpret_cast<word*>(ptr) - POINTER_SIZE_IN_WORDS;
    }
  }

624
  inline ElementCount size() const;
625 626
  // The number of elements in the list.

627 628 629 630
  Text::Builder asText();
  Data::Builder asData();
  // Reinterpret the list as a blob.  Throws an exception if the elements are not byte-sized.

631
  template <typename T>
632
  KJ_ALWAYS_INLINE(T getDataElement(ElementCount index));
633 634 635
  // Get the element of the given type at the given index.

  template <typename T>
636
  KJ_ALWAYS_INLINE(void setDataElement(
637
      ElementCount index, kj::NoInfer<T> value));
638
  // Set the element at the given index.
639

640
  KJ_ALWAYS_INLINE(PointerBuilder getPointerElement(ElementCount index));
Kenton Varda's avatar
Kenton Varda committed
641

642
  StructBuilder getStructElement(ElementCount index);
643

644 645
  ListReader asReader() const;
  // Get a ListReader pointing at the same memory.
646

647 648 649
  BuilderArena* getArena();
  // Gets the arena in which this object is allocated.

650
private:
Kenton Varda's avatar
Kenton Varda committed
651
  SegmentBuilder* segment;  // Memory segment in which the list resides.
652

653
  byte* ptr;  // Pointer to list content.
654

655
  ElementCount elementCount;  // Number of elements in the list.
656

657
  decltype(BITS / ELEMENTS) step;
658
  // The distance between elements.
659 660

  BitCount32 structDataSize;
661
  WirePointerCount16 structPointerCount;
662 663
  // The struct properties to use when interpreting the elements as structs.  All lists can be
  // interpreted as struct lists, so these are always filled in.
664

665
  inline ListBuilder(SegmentBuilder* segment, void* ptr,
666
                     decltype(BITS / ELEMENTS) step, ElementCount size,
667
                     BitCount structDataSize, WirePointerCount structPointerCount)
668
      : segment(segment), ptr(reinterpret_cast<byte*>(ptr)),
669
        elementCount(size), step(step), structDataSize(structDataSize),
670
        structPointerCount(structPointerCount) {}
671

672
  friend class StructBuilder;
673
  friend struct WireHelpers;
674
  friend class OrphanBuilder;
675 676
};

677
class ListReader {
678
public:
679
  inline ListReader()
680
      : segment(nullptr), ptr(nullptr), elementCount(0), step(0 * BITS / ELEMENTS),
681
        structDataSize(0), structPointerCount(0), nestingLimit(0x7fffffff) {}
682

683
  inline ElementCount size() const;
684 685
  // The number of elements in the list.

686 687 688 689
  Text::Reader asText();
  Data::Reader asData();
  // Reinterpret the list as a blob.  Throws an exception if the elements are not byte-sized.

690
  template <typename T>
691
  KJ_ALWAYS_INLINE(T getDataElement(ElementCount index) const);
692 693
  // Get the element of the given type at the given index.

694
  KJ_ALWAYS_INLINE(PointerReader getPointerElement(ElementCount index) const);
695

696
  StructReader getStructElement(ElementCount index) const;
697

698
private:
Kenton Varda's avatar
Kenton Varda committed
699
  SegmentReader* segment;  // Memory segment in which the list resides.
700

701
  const byte* ptr;  // Pointer to list content.
702

703
  ElementCount elementCount;  // Number of elements in the list.
704

705
  decltype(BITS / ELEMENTS) step;
706
  // The distance between elements.
707

708
  BitCount32 structDataSize;
709
  WirePointerCount16 structPointerCount;
710 711
  // The struct properties to use when interpreting the elements as structs.  All lists can be
  // interpreted as struct lists, so these are always filled in.
712

713
  int nestingLimit;
714 715 716
  // Limits the depth of message structures to guard against stack-overflow-based DoS attacks.
  // Once this reaches zero, further pointers will be pruned.

717
  inline ListReader(SegmentReader* segment, const void* ptr,
718
                    ElementCount elementCount, decltype(BITS / ELEMENTS) step,
719
                    BitCount structDataSize, WirePointerCount structPointerCount,
720 721
                    int nestingLimit)
      : segment(segment), ptr(reinterpret_cast<const byte*>(ptr)), elementCount(elementCount),
722
        step(step), structDataSize(structDataSize),
723
        structPointerCount(structPointerCount), nestingLimit(nestingLimit) {}
724

725 726
  friend class StructReader;
  friend class ListBuilder;
727
  friend struct WireHelpers;
728
  friend class OrphanBuilder;
729 730
};

731 732
// -------------------------------------------------------------------

733 734 735 736
class OrphanBuilder {
public:
  inline OrphanBuilder(): segment(nullptr), location(nullptr) { memset(&tag, 0, sizeof(tag)); }
  OrphanBuilder(const OrphanBuilder& other) = delete;
737
  inline OrphanBuilder(OrphanBuilder&& other) noexcept;
738
  inline ~OrphanBuilder() noexcept(false);
739 740 741 742 743 744 745 746 747 748 749

  static OrphanBuilder initStruct(BuilderArena* arena, StructSize size);
  static OrphanBuilder initList(BuilderArena* arena, ElementCount elementCount,
                                FieldSize elementSize);
  static OrphanBuilder initStructList(BuilderArena* arena, ElementCount elementCount,
                                      StructSize elementSize);
  static OrphanBuilder initText(BuilderArena* arena, ByteCount size);
  static OrphanBuilder initData(BuilderArena* arena, ByteCount size);

  static OrphanBuilder copy(BuilderArena* arena, StructReader copyFrom);
  static OrphanBuilder copy(BuilderArena* arena, ListReader copyFrom);
750
  static OrphanBuilder copy(BuilderArena* arena, PointerReader copyFrom);
751 752
  static OrphanBuilder copy(BuilderArena* arena, Text::Reader copyFrom);
  static OrphanBuilder copy(BuilderArena* arena, Data::Reader copyFrom);
753
  static OrphanBuilder copy(BuilderArena* arena, kj::Own<ClientHook> copyFrom);
754

755 756
  static OrphanBuilder referenceExternalData(BuilderArena* arena, Data::Reader data);

757 758 759
  OrphanBuilder& operator=(const OrphanBuilder& other) = delete;
  inline OrphanBuilder& operator=(OrphanBuilder&& other);

760 761
  inline bool operator==(decltype(nullptr)) const { return location == nullptr; }
  inline bool operator!=(decltype(nullptr)) const { return location != nullptr; }
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776

  StructBuilder asStruct(StructSize size);
  // Interpret as a struct, or throw an exception if not a struct.

  ListBuilder asList(FieldSize elementSize);
  // Interpret as a list, or throw an exception if not a list.  elementSize cannot be
  // INLINE_COMPOSITE -- use asStructList() instead.

  ListBuilder asStructList(StructSize elementSize);
  // Interpret as a struct list, or throw an exception if not a list.

  Text::Builder asText();
  Data::Builder asData();
  // Interpret as a blob, or throw an exception if not a blob.

777 778
  StructReader asStructReader(StructSize size) const;
  ListReader asListReader(FieldSize elementSize) const;
779
  kj::Own<ClientHook> asCapability() const;
780 781 782
  Text::Reader asTextReader() const;
  Data::Reader asDataReader() const;

783 784
  void truncate(ElementCount size, bool isText);

785 786 787 788 789 790 791
private:
  static_assert(1 * POINTERS * WORDS_PER_POINTER == 1 * WORDS,
                "This struct assumes a pointer is one word.");
  word tag;
  // Contains an encoded WirePointer representing this object.  WirePointer is defined in
  // layout.c++, but fits in a word.
  //
792 793 794 795 796 797 798
  // This may be a FAR pointer.  Even in that case, `location` points to the eventual destination
  // of that far pointer.  The reason we keep the far pointer around rather than just making `tag`
  // represent the final destination is because if the eventual adopter of the pointer is not in
  // the target's segment then it may be useful to reuse the far pointer landing pad.
  //
  // If `tag` is not a far pointer, its offset is garbage; only `location` points to the actual
  // target.
799 800

  SegmentBuilder* segment;
801
  // Segment in which the object resides.
802 803

  word* location;
804 805
  // Pointer to the object, or nullptr if the pointer is null.  For capabilities, we make this
  // point at `tag` just so that it is non-null for operator==, but it is never used.
806 807 808 809 810 811 812

  inline OrphanBuilder(const void* tagPtr, SegmentBuilder* segment, word* location)
      : segment(segment), location(location) {
    memcpy(&tag, tagPtr, sizeof(tag));
  }

  inline WirePointer* tagAsPtr() { return reinterpret_cast<WirePointer*>(&tag); }
813
  inline const WirePointer* tagAsPtr() const { return reinterpret_cast<const WirePointer*>(&tag); }
814 815 816 817 818 819 820 821

  void euthanize();
  // Erase the target object, zeroing it out and possibly reclaiming the memory.  Called when
  // the OrphanBuilder is being destroyed or overwritten and it is non-null.

  friend struct WireHelpers;
};

822 823 824
// =======================================================================================
// Internal implementation details...

825 826 827 828 829 830 831 832 833 834 835
// These are defined in the source file.
template <> typename Text::Builder PointerBuilder::initBlob<Text>(ByteCount size);
template <> void PointerBuilder::setBlob<Text>(typename Text::Reader value);
template <> typename Text::Builder PointerBuilder::getBlob<Text>(const void* defaultValue, ByteCount defaultSize);
template <> typename Text::Reader PointerReader::getBlob<Text>(const void* defaultValue, ByteCount defaultSize) const;

template <> typename Data::Builder PointerBuilder::initBlob<Data>(ByteCount size);
template <> void PointerBuilder::setBlob<Data>(typename Data::Reader value);
template <> typename Data::Builder PointerBuilder::getBlob<Data>(const void* defaultValue, ByteCount defaultSize);
template <> typename Data::Reader PointerReader::getBlob<Data>(const void* defaultValue, ByteCount defaultSize) const;

Kenton Varda's avatar
Kenton Varda committed
836 837 838 839 840 841 842 843
inline PointerBuilder PointerBuilder::getRoot(SegmentBuilder* segment, word* location) {
  return PointerBuilder(segment, reinterpret_cast<WirePointer*>(location));
}

inline PointerReader PointerReader::getRootUnchecked(const word* location) {
  return PointerReader(nullptr, reinterpret_cast<const WirePointer*>(location), 0x7fffffff);
}

844 845
// -------------------------------------------------------------------

846
inline Data::Builder StructBuilder::getDataSectionAsBlob() {
847
  return Data::Builder(reinterpret_cast<byte*>(data), dataSize / BITS_PER_BYTE / BYTES);
848 849
}

850 851 852 853 854 855 856 857 858 859
template <typename T>
inline bool StructBuilder::hasDataField(ElementCount offset) {
  return getDataField<Mask<T>>(offset) != 0;
}

template <>
inline bool StructBuilder::hasDataField<Void>(ElementCount offset) {
  return false;
}

860
template <typename T>
861
inline T StructBuilder::getDataField(ElementCount offset) {
862
  return reinterpret_cast<WireValue<T>*>(data)[offset / ELEMENTS].get();
863 864 865
}

template <>
866
inline bool StructBuilder::getDataField<bool>(ElementCount offset) {
867 868 869
  // This branch should be compiled out whenever this is inlined with a constant offset.
  BitCount boffset = (offset == 0 * ELEMENTS) ?
      BitCount(bit0Offset) : offset * (1 * BITS / ELEMENTS);
870
  byte* b = reinterpret_cast<byte*>(data) + boffset / BITS_PER_BYTE;
871
  return (*reinterpret_cast<uint8_t*>(b) & (1 << (boffset % BITS_PER_BYTE / BITS))) != 0;
872 873
}

874
template <>
875
inline Void StructBuilder::getDataField<Void>(ElementCount offset) {
876
  return VOID;
877 878
}

879
template <typename T>
880
inline T StructBuilder::getDataField(ElementCount offset, Mask<T> mask) {
881
  return unmask<T>(getDataField<Mask<T> >(offset), mask);
882 883
}

884
template <typename T>
885
inline void StructBuilder::setDataField(ElementCount offset, kj::NoInfer<T> value) {
886
  reinterpret_cast<WireValue<T>*>(data)[offset / ELEMENTS].set(value);
887 888
}

889 890 891 892 893 894 895 896 897 898 899 900
#if CAPNP_CANONICALIZE_NAN
// Use mask() on floats and doubles to make sure we canonicalize NaNs.
template <>
inline void StructBuilder::setDataField<float>(ElementCount offset, float value) {
  setDataField<uint32_t>(offset, mask<float>(value, 0));
}
template <>
inline void StructBuilder::setDataField<double>(ElementCount offset, double value) {
  setDataField<uint64_t>(offset, mask<double>(value, 0));
}
#endif

901
template <>
902
inline void StructBuilder::setDataField<bool>(ElementCount offset, bool value) {
903 904 905
  // This branch should be compiled out whenever this is inlined with a constant offset.
  BitCount boffset = (offset == 0 * ELEMENTS) ?
      BitCount(bit0Offset) : offset * (1 * BITS / ELEMENTS);
906
  byte* b = reinterpret_cast<byte*>(data) + boffset / BITS_PER_BYTE;
907 908 909
  uint bitnum = boffset % BITS_PER_BYTE / BITS;
  *reinterpret_cast<uint8_t*>(b) = (*reinterpret_cast<uint8_t*>(b) & ~(1 << bitnum))
                                 | (static_cast<uint8_t>(value) << bitnum);
910 911
}

912
template <>
913
inline void StructBuilder::setDataField<Void>(ElementCount offset, Void value) {}
914

915
template <typename T>
916
inline void StructBuilder::setDataField(ElementCount offset, kj::NoInfer<T> value, Mask<T> m) {
917
  setDataField<Mask<T> >(offset, mask<T>(value, m));
918 919
}

920 921 922 923 924 925
inline PointerBuilder StructBuilder::getPointerField(WirePointerCount ptrIndex) {
  // Hacky because WirePointer is defined in the .c++ file (so is incomplete here).
  return PointerBuilder(segment, reinterpret_cast<WirePointer*>(
      reinterpret_cast<word*>(pointers) + ptrIndex * WORDS_PER_POINTER));
}

926 927
// -------------------------------------------------------------------

928
inline Data::Reader StructReader::getDataSectionAsBlob() {
929
  return Data::Reader(reinterpret_cast<const byte*>(data), dataSize / BITS_PER_BYTE / BYTES);
930 931
}

932
template <typename T>
933 934 935 936 937 938 939 940 941 942 943
inline bool StructReader::hasDataField(ElementCount offset) const {
  return getDataField<Mask<T>>(offset) != 0;
}

template <>
inline bool StructReader::hasDataField<Void>(ElementCount offset) const {
  return false;
}

template <typename T>
inline T StructReader::getDataField(ElementCount offset) const {
944
  if ((offset + 1 * ELEMENTS) * capnp::bitsPerElement<T>() <= dataSize) {
945
    return reinterpret_cast<const WireValue<T>*>(data)[offset / ELEMENTS].get();
946
  } else {
947
    return static_cast<T>(0);
948
  }
949 950 951
}

template <>
952
inline bool StructReader::getDataField<bool>(ElementCount offset) const {
953
  BitCount boffset = offset * (1 * BITS / ELEMENTS);
954 955 956 957 958
  if (boffset < dataSize) {
    // This branch should be compiled out whenever this is inlined with a constant offset.
    if (offset == 0 * ELEMENTS) {
      boffset = bit0Offset;
    }
959
    const byte* b = reinterpret_cast<const byte*>(data) + boffset / BITS_PER_BYTE;
960 961
    return (*reinterpret_cast<const uint8_t*>(b) & (1 << (boffset % BITS_PER_BYTE / BITS))) != 0;
  } else {
962
    return false;
963
  }
964 965
}

966
template <>
967
inline Void StructReader::getDataField<Void>(ElementCount offset) const {
968
  return VOID;
969 970
}

971
template <typename T>
972 973
T StructReader::getDataField(ElementCount offset, Mask<T> mask) const {
  return unmask<T>(getDataField<Mask<T> >(offset), mask);
974 975
}

976 977 978 979 980 981 982 983 984 985
inline PointerReader StructReader::getPointerField(WirePointerCount ptrIndex) const {
  if (ptrIndex < pointerCount) {
    // Hacky because WirePointer is defined in the .c++ file (so is incomplete here).
    return PointerReader(segment, reinterpret_cast<const WirePointer*>(
        reinterpret_cast<const word*>(pointers) + ptrIndex * WORDS_PER_POINTER), nestingLimit);
  } else{
    return PointerReader();
  }
}

986 987
// -------------------------------------------------------------------

988
inline ElementCount ListBuilder::size() const { return elementCount; }
989 990

template <typename T>
991
inline T ListBuilder::getDataElement(ElementCount index) {
992 993
  return reinterpret_cast<WireValue<T>*>(ptr + index * step / BITS_PER_BYTE)->get();

Kenton Varda's avatar
Kenton Varda committed
994
  // TODO(perf):  Benchmark this alternate implementation, which I suspect may make better use of
995 996 997 998
  //   the x86 SIB byte.  Also use it for all the other getData/setData implementations below, and
  //   the various non-inline methods that look up pointers.
  //   Also if using this, consider changing ptr back to void* instead of byte*.
//  return reinterpret_cast<WireValue<T>*>(ptr)[
999
//      index / ELEMENTS * (step / capnp::bitsPerElement<T>())].get();
1000 1001 1002
}

template <>
1003
inline bool ListBuilder::getDataElement<bool>(ElementCount index) {
1004
  // Ignore stepBytes for bit lists because bit lists cannot be upgraded to struct lists.
1005
  BitCount bindex = index * step;
1006
  byte* b = ptr + bindex / BITS_PER_BYTE;
1007
  return (*reinterpret_cast<uint8_t*>(b) & (1 << (bindex % BITS_PER_BYTE / BITS))) != 0;
1008 1009
}

1010
template <>
1011
inline Void ListBuilder::getDataElement<Void>(ElementCount index) {
1012
  return VOID;
1013 1014
}

1015
template <typename T>
1016
inline void ListBuilder::setDataElement(ElementCount index, kj::NoInfer<T> value) {
1017
  reinterpret_cast<WireValue<T>*>(ptr + index * step / BITS_PER_BYTE)->set(value);
1018 1019
}

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
#if CAPNP_CANONICALIZE_NAN
// Use mask() on floats and doubles to make sure we canonicalize NaNs.
template <>
inline void ListBuilder::setDataElement<float>(ElementCount index, float value) {
  setDataElement<uint32_t>(index, mask<float>(value, 0));
}
template <>
inline void ListBuilder::setDataElement<double>(ElementCount index, double value) {
  setDataElement<uint64_t>(index, mask<double>(value, 0));
}
#endif

1032
template <>
1033
inline void ListBuilder::setDataElement<bool>(ElementCount index, bool value) {
1034 1035
  // Ignore stepBytes for bit lists because bit lists cannot be upgraded to struct lists.
  BitCount bindex = index * (1 * BITS / ELEMENTS);
1036
  byte* b = ptr + bindex / BITS_PER_BYTE;
1037 1038 1039
  uint bitnum = bindex % BITS_PER_BYTE / BITS;
  *reinterpret_cast<uint8_t*>(b) = (*reinterpret_cast<uint8_t*>(b) & ~(1 << bitnum))
                                 | (static_cast<uint8_t>(value) << bitnum);
1040 1041
}

1042
template <>
1043
inline void ListBuilder::setDataElement<Void>(ElementCount index, Void value) {}
1044

1045 1046 1047 1048 1049
inline PointerBuilder ListBuilder::getPointerElement(ElementCount index) {
  return PointerBuilder(segment,
      reinterpret_cast<WirePointer*>(ptr + index * step / BITS_PER_BYTE));
}

1050 1051
// -------------------------------------------------------------------

1052
inline ElementCount ListReader::size() const { return elementCount; }
1053 1054

template <typename T>
1055
inline T ListReader::getDataElement(ElementCount index) const {
1056
  return reinterpret_cast<const WireValue<T>*>(ptr + index * step / BITS_PER_BYTE)->get();
1057 1058 1059
}

template <>
1060
inline bool ListReader::getDataElement<bool>(ElementCount index) const {
1061
  // Ignore stepBytes for bit lists because bit lists cannot be upgraded to struct lists.
1062
  BitCount bindex = index * step;
1063
  const byte* b = ptr + bindex / BITS_PER_BYTE;
1064
  return (*reinterpret_cast<const uint8_t*>(b) & (1 << (bindex % BITS_PER_BYTE / BITS))) != 0;
1065 1066
}

1067 1068
template <>
inline Void ListReader::getDataElement<Void>(ElementCount index) const {
1069
  return VOID;
1070 1071
}

1072 1073 1074 1075
inline PointerReader ListReader::getPointerElement(ElementCount index) const {
  return PointerReader(segment,
      reinterpret_cast<const WirePointer*>(ptr + index * step / BITS_PER_BYTE), nestingLimit);
}
1076

1077 1078
// -------------------------------------------------------------------

1079
inline OrphanBuilder::OrphanBuilder(OrphanBuilder&& other) noexcept
1080 1081 1082 1083 1084 1085
    : segment(other.segment), location(other.location) {
  memcpy(&tag, &other.tag, sizeof(tag));  // Needs memcpy to comply with aliasing rules.
  other.segment = nullptr;
  other.location = nullptr;
}

1086
inline OrphanBuilder::~OrphanBuilder() noexcept(false) {
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  if (segment != nullptr) euthanize();
}

inline OrphanBuilder& OrphanBuilder::operator=(OrphanBuilder&& other) {
  // With normal smart pointers, it's important to handle the case where the incoming pointer
  // is actually transitively owned by this one.  In this case, euthanize() would destroy `other`
  // before we copied it.  This isn't possible in the case of `OrphanBuilder` because it only
  // owns message objects, and `other` is not itself a message object, therefore cannot possibly
  // be transitively owned by `this`.

  if (segment != nullptr) euthanize();
  segment = other.segment;
  location = other.location;
  memcpy(&tag, &other.tag, sizeof(tag));  // Needs memcpy to comply with aliasing rules.
  other.segment = nullptr;
  other.location = nullptr;
  return *this;
}

1106
}  // namespace _ (private)
1107
}  // namespace capnp
1108

Kenton Varda's avatar
Kenton Varda committed
1109
#endif  // CAPNP_LAYOUT_H_