dynamic.c++ 73.3 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "dynamic.h"
Kenton Varda's avatar
Kenton Varda committed
25
#include <kj/debug.h>
Kenton Varda's avatar
Kenton Varda committed
26

27
namespace capnp {
Kenton Varda's avatar
Kenton Varda committed
28 29 30

namespace {

31 32 33 34
bool hasDiscriminantValue(const schema::Field::Reader& reader) {
  return reader.getDiscriminantValue() != schema::Field::NO_DISCRIMINANT;
}

Kenton Varda's avatar
Kenton Varda committed
35
template <typename T, typename U>
36
KJ_ALWAYS_INLINE(T bitCast(U value));
Kenton Varda's avatar
Kenton Varda committed
37 38 39 40 41 42

template <typename T, typename U>
inline T bitCast(U value) {
  static_assert(sizeof(T) == sizeof(U), "Size must match.");
  return value;
}
Kenton Varda's avatar
Kenton Varda committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
template <>
inline float bitCast<float, uint32_t>(uint32_t value) KJ_UNUSED;
template <>
inline float bitCast<float, uint32_t>(uint32_t value) {
  float result;
  memcpy(&result, &value, sizeof(value));
  return result;
}
template <>
inline double bitCast<double, uint64_t>(uint64_t value) KJ_UNUSED;
template <>
inline double bitCast<double, uint64_t>(uint64_t value) {
  double result;
  memcpy(&result, &value, sizeof(value));
  return result;
}
Kenton Varda's avatar
Kenton Varda committed
59 60 61 62 63 64 65 66 67 68 69 70 71
template <>
inline uint32_t bitCast<uint32_t, float>(float value) {
  uint32_t result;
  memcpy(&result, &value, sizeof(value));
  return result;
}
template <>
inline uint64_t bitCast<uint64_t, double>(double value) {
  uint64_t result;
  memcpy(&result, &value, sizeof(value));
  return result;
}

Kenton Varda's avatar
Kenton Varda committed
72
_::FieldSize elementSizeFor(schema::Type::Which elementType) {
Kenton Varda's avatar
Kenton Varda committed
73
  switch (elementType) {
Kenton Varda's avatar
Kenton Varda committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    case schema::Type::VOID: return _::FieldSize::VOID;
    case schema::Type::BOOL: return _::FieldSize::BIT;
    case schema::Type::INT8: return _::FieldSize::BYTE;
    case schema::Type::INT16: return _::FieldSize::TWO_BYTES;
    case schema::Type::INT32: return _::FieldSize::FOUR_BYTES;
    case schema::Type::INT64: return _::FieldSize::EIGHT_BYTES;
    case schema::Type::UINT8: return _::FieldSize::BYTE;
    case schema::Type::UINT16: return _::FieldSize::TWO_BYTES;
    case schema::Type::UINT32: return _::FieldSize::FOUR_BYTES;
    case schema::Type::UINT64: return _::FieldSize::EIGHT_BYTES;
    case schema::Type::FLOAT32: return _::FieldSize::FOUR_BYTES;
    case schema::Type::FLOAT64: return _::FieldSize::EIGHT_BYTES;

    case schema::Type::TEXT: return _::FieldSize::POINTER;
    case schema::Type::DATA: return _::FieldSize::POINTER;
    case schema::Type::LIST: return _::FieldSize::POINTER;
    case schema::Type::ENUM: return _::FieldSize::TWO_BYTES;
    case schema::Type::STRUCT: return _::FieldSize::INLINE_COMPOSITE;
    case schema::Type::INTERFACE: return _::FieldSize::POINTER;
93
    case schema::Type::ANY_POINTER: KJ_FAIL_ASSERT("List(AnyPointer) not supported."); break;
Kenton Varda's avatar
Kenton Varda committed
94
  }
95 96

  // Unknown type.  Treat it as zero-size.
97
  return _::FieldSize::VOID;
Kenton Varda's avatar
Kenton Varda committed
98 99
}

100
inline _::StructSize structSizeFromSchema(StructSchema schema) {
Kenton Varda's avatar
Kenton Varda committed
101
  auto node = schema.getProto().getStruct();
102
  return _::StructSize(
103 104
      node.getDataWordCount() * WORDS,
      node.getPointerCount() * POINTERS,
105
      static_cast<_::FieldSize>(node.getPreferredListEncoding()));
Kenton Varda's avatar
Kenton Varda committed
106 107
}

Kenton Varda's avatar
Kenton Varda committed
108 109 110 111
}  // namespace

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

112
kj::Maybe<EnumSchema::Enumerant> DynamicEnum::getEnumerant() const {
113
  auto enumerants = schema.getEnumerants();
Kenton Varda's avatar
Kenton Varda committed
114 115 116 117 118 119 120
  if (value < enumerants.size()) {
    return enumerants[value];
  } else {
    return nullptr;
  }
}

121
uint16_t DynamicEnum::asImpl(uint64_t requestedTypeId) const {
122 123
  KJ_REQUIRE(requestedTypeId == schema.getProto().getId(),
             "Type mismatch in DynamicEnum.as().") {
124
    // use it anyway
125
    break;
Kenton Varda's avatar
Kenton Varda committed
126 127 128 129 130 131
  }
  return value;
}

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

Kenton Varda's avatar
Kenton Varda committed
132 133
bool DynamicStruct::Reader::isSetInUnion(StructSchema::Field field) const {
  auto proto = field.getProto();
134
  if (hasDiscriminantValue(proto)) {
Kenton Varda's avatar
Kenton Varda committed
135 136 137
    uint16_t discrim = reader.getDataField<uint16_t>(
        schema.getProto().getStruct().getDiscriminantOffset() * ELEMENTS);
    return discrim == proto.getDiscriminantValue();
138
  } else {
Kenton Varda's avatar
Kenton Varda committed
139
    return true;
140
  }
Kenton Varda's avatar
Kenton Varda committed
141 142
}

Kenton Varda's avatar
Kenton Varda committed
143 144 145 146
void DynamicStruct::Reader::verifySetInUnion(StructSchema::Field field) const {
  KJ_REQUIRE(isSetInUnion(field),
      "Tried to get() a union member which is not currently initialized.",
      field.getProto().getName(), schema.getProto().getDisplayName());
Kenton Varda's avatar
Kenton Varda committed
147 148
}

Kenton Varda's avatar
Kenton Varda committed
149 150
bool DynamicStruct::Builder::isSetInUnion(StructSchema::Field field) {
  auto proto = field.getProto();
151
  if (hasDiscriminantValue(proto)) {
Kenton Varda's avatar
Kenton Varda committed
152 153 154
    uint16_t discrim = builder.getDataField<uint16_t>(
        schema.getProto().getStruct().getDiscriminantOffset() * ELEMENTS);
    return discrim == proto.getDiscriminantValue();
155
  } else {
Kenton Varda's avatar
Kenton Varda committed
156
    return true;
157
  }
Kenton Varda's avatar
Kenton Varda committed
158 159
}

Kenton Varda's avatar
Kenton Varda committed
160 161 162 163
void DynamicStruct::Builder::verifySetInUnion(StructSchema::Field field) {
  KJ_REQUIRE(isSetInUnion(field),
      "Tried to get() a union member which is not currently initialized.",
      field.getProto().getName(), schema.getProto().getDisplayName());
164 165
}

Kenton Varda's avatar
Kenton Varda committed
166
void DynamicStruct::Builder::setInUnion(StructSchema::Field field) {
167
  // If a union member, set the discriminant to match.
Kenton Varda's avatar
Kenton Varda committed
168
  auto proto = field.getProto();
169
  if (hasDiscriminantValue(proto)) {
170
    builder.setDataField<uint16_t>(
Kenton Varda's avatar
Kenton Varda committed
171 172
        schema.getProto().getStruct().getDiscriminantOffset() * ELEMENTS,
        proto.getDiscriminantValue());
Kenton Varda's avatar
Kenton Varda committed
173
  }
174
}
Kenton Varda's avatar
Kenton Varda committed
175

Kenton Varda's avatar
Kenton Varda committed
176 177 178
DynamicValue::Reader DynamicStruct::Reader::get(StructSchema::Field field) const {
  KJ_REQUIRE(field.getContainingStruct() == schema, "`field` is not a field of this struct.");
  verifySetInUnion(field);
Kenton Varda's avatar
Kenton Varda committed
179

Kenton Varda's avatar
Kenton Varda committed
180 181
  auto proto = field.getProto();
  switch (proto.which()) {
182 183 184 185
    case schema::Field::SLOT: {
      auto slot = proto.getSlot();
      auto type = slot.getType();
      auto dval = slot.getDefaultValue();
186 187

      switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
188
        case schema::Type::VOID:
189
          return reader.getDataField<Void>(slot.getOffset() * ELEMENTS);
Kenton Varda's avatar
Kenton Varda committed
190 191

#define HANDLE_TYPE(discrim, titleCase, type) \
Kenton Varda's avatar
Kenton Varda committed
192
        case schema::Type::discrim: \
193
          return reader.getDataField<type>( \
194
              slot.getOffset() * ELEMENTS, \
195
              bitCast<_::Mask<type>>(dval.get##titleCase()));
196 197 198 199 200 201 202 203 204 205 206 207

        HANDLE_TYPE(BOOL, Bool, bool)
        HANDLE_TYPE(INT8, Int8, int8_t)
        HANDLE_TYPE(INT16, Int16, int16_t)
        HANDLE_TYPE(INT32, Int32, int32_t)
        HANDLE_TYPE(INT64, Int64, int64_t)
        HANDLE_TYPE(UINT8, Uint8, uint8_t)
        HANDLE_TYPE(UINT16, Uint16, uint16_t)
        HANDLE_TYPE(UINT32, Uint32, uint32_t)
        HANDLE_TYPE(UINT64, Uint64, uint64_t)
        HANDLE_TYPE(FLOAT32, Float32, float)
        HANDLE_TYPE(FLOAT64, Float64, double)
Kenton Varda's avatar
Kenton Varda committed
208 209 210

#undef HANDLE_TYPE

Kenton Varda's avatar
Kenton Varda committed
211
        case schema::Type::ENUM: {
212
          uint16_t typedDval;
Kenton Varda's avatar
Kenton Varda committed
213
          typedDval = dval.getEnum();
214
          return DynamicEnum(
215
              field.getContainingStruct().getDependency(type.getEnum().getTypeId()).asEnum(),
216
              reader.getDataField<uint16_t>(slot.getOffset() * ELEMENTS, typedDval));
217 218
        }

Kenton Varda's avatar
Kenton Varda committed
219
        case schema::Type::TEXT: {
Kenton Varda's avatar
Kenton Varda committed
220
          Text::Reader typedDval = dval.getText();
221 222
          return reader.getPointerField(slot.getOffset() * POINTERS)
                       .getBlob<Text>(typedDval.begin(), typedDval.size() * BYTES);
223 224
        }

Kenton Varda's avatar
Kenton Varda committed
225
        case schema::Type::DATA: {
Kenton Varda's avatar
Kenton Varda committed
226
          Data::Reader typedDval = dval.getData();
227 228
          return reader.getPointerField(slot.getOffset() * POINTERS)
                       .getBlob<Data>(typedDval.begin(), typedDval.size() * BYTES);
229 230
        }

Kenton Varda's avatar
Kenton Varda committed
231
        case schema::Type::LIST: {
232
          auto elementType = type.getList().getElementType();
233
          return DynamicList::Reader(
Kenton Varda's avatar
Kenton Varda committed
234
              ListSchema::of(elementType, field.getContainingStruct()),
235 236
              reader.getPointerField(slot.getOffset() * POINTERS)
                    .getList(elementSizeFor(elementType.which()),
237
                             dval.getList().getAs<_::UncheckedMessage>()));
238 239
        }

240
        case schema::Type::STRUCT:
241
          return DynamicStruct::Reader(
242
              field.getContainingStruct().getDependency(type.getStruct().getTypeId()).asStruct(),
243
              reader.getPointerField(slot.getOffset() * POINTERS)
244
                    .getStruct(dval.getStruct().getAs<_::UncheckedMessage>()));
245

246 247
        case schema::Type::ANY_POINTER:
          return AnyPointer::Reader(reader.getPointerField(slot.getOffset() * POINTERS));
248

Kenton Varda's avatar
Kenton Varda committed
249
        case schema::Type::INTERFACE:
250 251 252 253
          return DynamicCapability::Client(
              field.getContainingStruct().getDependency(
                  type.getInterface().getTypeId()).asInterface(),
              reader.getPointerField(slot.getOffset() * POINTERS).getCapability());
254
      }
Kenton Varda's avatar
Kenton Varda committed
255

Kenton Varda's avatar
Kenton Varda committed
256
      KJ_UNREACHABLE;
Kenton Varda's avatar
Kenton Varda committed
257
    }
Kenton Varda's avatar
Kenton Varda committed
258

Kenton Varda's avatar
Kenton Varda committed
259
    case schema::Field::GROUP:
260 261
      return DynamicStruct::Reader(
          schema.getDependency(proto.getGroup().getTypeId()).asStruct(), reader);
Kenton Varda's avatar
Kenton Varda committed
262 263
  }

Kenton Varda's avatar
Kenton Varda committed
264
  KJ_UNREACHABLE;
Kenton Varda's avatar
Kenton Varda committed
265 266
}

Kenton Varda's avatar
Kenton Varda committed
267 268 269
DynamicValue::Builder DynamicStruct::Builder::get(StructSchema::Field field) {
  KJ_REQUIRE(field.getContainingStruct() == schema, "`field` is not a field of this struct.");
  verifySetInUnion(field);
Kenton Varda's avatar
Kenton Varda committed
270

Kenton Varda's avatar
Kenton Varda committed
271 272
  auto proto = field.getProto();
  switch (proto.which()) {
273 274 275 276
    case schema::Field::SLOT: {
      auto slot = proto.getSlot();
      auto type = slot.getType();
      auto dval = slot.getDefaultValue();
277 278

      switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
279
        case schema::Type::VOID:
280
          return builder.getDataField<Void>(slot.getOffset() * ELEMENTS);
Kenton Varda's avatar
Kenton Varda committed
281 282

#define HANDLE_TYPE(discrim, titleCase, type) \
Kenton Varda's avatar
Kenton Varda committed
283
        case schema::Type::discrim: \
Kenton Varda's avatar
Kenton Varda committed
284
          return builder.getDataField<type>( \
285
              slot.getOffset() * ELEMENTS, \
Kenton Varda's avatar
Kenton Varda committed
286
              bitCast<_::Mask<type>>(dval.get##titleCase()));
287 288 289 290 291 292 293 294 295 296 297 298

        HANDLE_TYPE(BOOL, Bool, bool)
        HANDLE_TYPE(INT8, Int8, int8_t)
        HANDLE_TYPE(INT16, Int16, int16_t)
        HANDLE_TYPE(INT32, Int32, int32_t)
        HANDLE_TYPE(INT64, Int64, int64_t)
        HANDLE_TYPE(UINT8, Uint8, uint8_t)
        HANDLE_TYPE(UINT16, Uint16, uint16_t)
        HANDLE_TYPE(UINT32, Uint32, uint32_t)
        HANDLE_TYPE(UINT64, Uint64, uint64_t)
        HANDLE_TYPE(FLOAT32, Float32, float)
        HANDLE_TYPE(FLOAT64, Float64, double)
Kenton Varda's avatar
Kenton Varda committed
299 300 301

#undef HANDLE_TYPE

Kenton Varda's avatar
Kenton Varda committed
302
        case schema::Type::ENUM: {
303
          uint16_t typedDval;
Kenton Varda's avatar
Kenton Varda committed
304 305
          typedDval = dval.getEnum();
          return DynamicEnum(
306
              field.getContainingStruct().getDependency(type.getEnum().getTypeId()).asEnum(),
307
              builder.getDataField<uint16_t>(slot.getOffset() * ELEMENTS, typedDval));
308 309
        }

Kenton Varda's avatar
Kenton Varda committed
310
        case schema::Type::TEXT: {
Kenton Varda's avatar
Kenton Varda committed
311
          Text::Reader typedDval = dval.getText();
312 313
          return builder.getPointerField(slot.getOffset() * POINTERS)
                        .getBlob<Text>(typedDval.begin(), typedDval.size() * BYTES);
314 315
        }

Kenton Varda's avatar
Kenton Varda committed
316
        case schema::Type::DATA: {
Kenton Varda's avatar
Kenton Varda committed
317
          Data::Reader typedDval = dval.getData();
318 319
          return builder.getPointerField(slot.getOffset() * POINTERS)
                        .getBlob<Data>(typedDval.begin(), typedDval.size() * BYTES);
320 321
        }

Kenton Varda's avatar
Kenton Varda committed
322
        case schema::Type::LIST: {
323 324
          ListSchema listType = ListSchema::of(type.getList().getElementType(),
                                               field.getContainingStruct());
Kenton Varda's avatar
Kenton Varda committed
325
          if (listType.whichElementType() == schema::Type::STRUCT) {
Kenton Varda's avatar
Kenton Varda committed
326
            return DynamicList::Builder(listType,
327 328
                builder.getPointerField(slot.getOffset() * POINTERS)
                       .getStructList(structSizeFromSchema(listType.getStructElementType()),
329
                                      dval.getList().getAs<_::UncheckedMessage>()));
330
          } else {
Kenton Varda's avatar
Kenton Varda committed
331
            return DynamicList::Builder(listType,
332 333
                builder.getPointerField(slot.getOffset() * POINTERS)
                       .getList(elementSizeFor(listType.whichElementType()),
334
                                dval.getList().getAs<_::UncheckedMessage>()));
335 336
          }
        }
337

Kenton Varda's avatar
Kenton Varda committed
338
        case schema::Type::STRUCT: {
339
          auto structSchema =
340
              field.getContainingStruct().getDependency(type.getStruct().getTypeId()).asStruct();
Kenton Varda's avatar
Kenton Varda committed
341
          return DynamicStruct::Builder(structSchema,
342 343
              builder.getPointerField(slot.getOffset() * POINTERS)
                     .getStruct(structSizeFromSchema(structSchema),
344
                                dval.getStruct().getAs<_::UncheckedMessage>()));
345 346
        }

347 348
        case schema::Type::ANY_POINTER:
          return AnyPointer::Builder(builder.getPointerField(slot.getOffset() * POINTERS));
349

Kenton Varda's avatar
Kenton Varda committed
350
        case schema::Type::INTERFACE:
351 352 353 354
          return DynamicCapability::Client(
              field.getContainingStruct().getDependency(
                  type.getInterface().getTypeId()).asInterface(),
              builder.getPointerField(slot.getOffset() * POINTERS).getCapability());
355
      }
Kenton Varda's avatar
Kenton Varda committed
356

Kenton Varda's avatar
Kenton Varda committed
357
      KJ_UNREACHABLE;
Kenton Varda's avatar
Kenton Varda committed
358
    }
Kenton Varda's avatar
Kenton Varda committed
359

Kenton Varda's avatar
Kenton Varda committed
360
    case schema::Field::GROUP:
361 362
      return DynamicStruct::Builder(
          schema.getDependency(proto.getGroup().getTypeId()).asStruct(), builder);
Kenton Varda's avatar
Kenton Varda committed
363 364
  }

Kenton Varda's avatar
Kenton Varda committed
365
  KJ_UNREACHABLE;
Kenton Varda's avatar
Kenton Varda committed
366
}
Kenton Varda's avatar
Kenton Varda committed
367

368
DynamicValue::Pipeline DynamicStruct::Pipeline::get(StructSchema::Field field) {
369 370 371
  KJ_REQUIRE(field.getContainingStruct() == schema, "`field` is not a field of this struct.");

  auto proto = field.getProto();
372
  KJ_REQUIRE(!hasDiscriminantValue(proto), "Can't pipeline on union members.");
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

  switch (proto.which()) {
    case schema::Field::SLOT: {
      auto slot = proto.getSlot();
      auto type = slot.getType();

      switch (type.which()) {
        case schema::Type::STRUCT:
          return DynamicStruct::Pipeline(
              field.getContainingStruct().getDependency(type.getStruct().getTypeId()).asStruct(),
              typeless.getPointerField(slot.getOffset()));

        case schema::Type::INTERFACE:
          return DynamicCapability::Client(
              field.getContainingStruct().getDependency(
                  type.getInterface().getTypeId()).asInterface(),
              typeless.getPointerField(slot.getOffset()).asCap());

        default:
          KJ_FAIL_REQUIRE("Can only pipeline on struct and interface fields.");
      }

      KJ_UNREACHABLE;
    }

    case schema::Field::GROUP:
      return DynamicStruct::Pipeline(
          schema.getDependency(proto.getGroup().getTypeId()).asStruct(), typeless.noop());
  }

  KJ_UNREACHABLE;
}

Kenton Varda's avatar
Kenton Varda committed
406 407 408 409
bool DynamicStruct::Reader::has(StructSchema::Field field) const {
  KJ_REQUIRE(field.getContainingStruct() == schema, "`field` is not a field of this struct.");

  auto proto = field.getProto();
410
  if (hasDiscriminantValue(proto)) {
Kenton Varda's avatar
Kenton Varda committed
411 412 413 414 415 416
    uint16_t discrim = reader.getDataField<uint16_t>(
        schema.getProto().getStruct().getDiscriminantOffset() * ELEMENTS);
    if (discrim != proto.getDiscriminantValue()) {
      // Field is not active in the union.
      return false;
    }
417
  }
Kenton Varda's avatar
Kenton Varda committed
418 419

  switch (proto.which()) {
420
    case schema::Field::SLOT:
Kenton Varda's avatar
Kenton Varda committed
421 422 423
      // Continue to below.
      break;

424 425
    case schema::Field::GROUP:
      return true;
Kenton Varda's avatar
Kenton Varda committed
426 427
  }

428 429
  auto slot = proto.getSlot();
  auto type = slot.getType();
Kenton Varda's avatar
Kenton Varda committed
430 431

  switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
432
    case schema::Type::VOID:
433 434 435 436 437 438 439 440 441 442 443 444 445 446
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::ENUM:
      // Primitive types are always present.
      return true;
Kenton Varda's avatar
Kenton Varda committed
447

Kenton Varda's avatar
Kenton Varda committed
448 449 450 451
    case schema::Type::TEXT:
    case schema::Type::DATA:
    case schema::Type::LIST:
    case schema::Type::STRUCT:
452
    case schema::Type::ANY_POINTER:
Kenton Varda's avatar
Kenton Varda committed
453
    case schema::Type::INTERFACE:
454
      return !reader.getPointerField(slot.getOffset() * POINTERS).isNull();
Kenton Varda's avatar
Kenton Varda committed
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
  }

  // Unknown type.  As far as we know, it isn't set.
  return false;
}

kj::Maybe<StructSchema::Field> DynamicStruct::Reader::which() const {
  auto structProto = schema.getProto().getStruct();
  if (structProto.getDiscriminantCount() == 0) {
    return nullptr;
  }

  uint16_t discrim = reader.getDataField<uint16_t>(structProto.getDiscriminantOffset() * ELEMENTS);
  return schema.getFieldByDiscriminant(discrim);
}

kj::Maybe<StructSchema::Field> DynamicStruct::Builder::which() {
  auto structProto = schema.getProto().getStruct();
  if (structProto.getDiscriminantCount() == 0) {
    return nullptr;
  }

  uint16_t discrim = builder.getDataField<uint16_t>(structProto.getDiscriminantOffset() * ELEMENTS);
  return schema.getFieldByDiscriminant(discrim);
}

void DynamicStruct::Builder::set(StructSchema::Field field, const DynamicValue::Reader& value) {
  KJ_REQUIRE(field.getContainingStruct() == schema, "`field` is not a field of this struct.");
  setInUnion(field);

  auto proto = field.getProto();
  switch (proto.which()) {
487 488 489 490
    case schema::Field::SLOT: {
      auto slot = proto.getSlot();
      auto type = slot.getType();
      auto dval = slot.getDefaultValue();
Kenton Varda's avatar
Kenton Varda committed
491

492
      switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
493
        case schema::Type::VOID:
494
          builder.setDataField<Void>(slot.getOffset() * ELEMENTS, value.as<Void>());
495
          return;
Kenton Varda's avatar
Kenton Varda committed
496

497
#define HANDLE_TYPE(discrim, titleCase, type) \
Kenton Varda's avatar
Kenton Varda committed
498
        case schema::Type::discrim: \
499
          builder.setDataField<type>( \
500
              slot.getOffset() * ELEMENTS, value.as<type>(), \
Kenton Varda's avatar
Kenton Varda committed
501
              bitCast<_::Mask<type> >(dval.get##titleCase())); \
502 503 504 505 506 507 508 509 510 511 512 513 514
          return;

        HANDLE_TYPE(BOOL, Bool, bool)
        HANDLE_TYPE(INT8, Int8, int8_t)
        HANDLE_TYPE(INT16, Int16, int16_t)
        HANDLE_TYPE(INT32, Int32, int32_t)
        HANDLE_TYPE(INT64, Int64, int64_t)
        HANDLE_TYPE(UINT8, Uint8, uint8_t)
        HANDLE_TYPE(UINT16, Uint16, uint16_t)
        HANDLE_TYPE(UINT32, Uint32, uint32_t)
        HANDLE_TYPE(UINT64, Uint64, uint64_t)
        HANDLE_TYPE(FLOAT32, Float32, float)
        HANDLE_TYPE(FLOAT64, Float64, double)
Kenton Varda's avatar
Kenton Varda committed
515 516 517

#undef HANDLE_TYPE

Kenton Varda's avatar
Kenton Varda committed
518
        case schema::Type::ENUM: {
519
          uint16_t rawValue;
520 521
          auto enumSchema = field.getContainingStruct()
              .getDependency(type.getEnum().getTypeId()).asEnum();
522 523 524 525 526
          if (value.getType() == DynamicValue::TEXT) {
            // Convert from text.
            rawValue = enumSchema.getEnumerantByName(value.as<Text>()).getOrdinal();
          } else {
            DynamicEnum enumValue = value.as<DynamicEnum>();
527
            KJ_REQUIRE(enumValue.getSchema() == enumSchema, "Value type mismatch.") {
528 529 530 531
              return;
            }
            rawValue = enumValue.getRaw();
          }
532
          builder.setDataField<uint16_t>(slot.getOffset() * ELEMENTS, rawValue,
Kenton Varda's avatar
Kenton Varda committed
533
                                         dval.getEnum());
534
          return;
535
        }
536

Kenton Varda's avatar
Kenton Varda committed
537
        case schema::Type::TEXT:
538
          builder.getPointerField(slot.getOffset() * POINTERS).setBlob<Text>(value.as<Text>());
539 540
          return;

Kenton Varda's avatar
Kenton Varda committed
541
        case schema::Type::DATA:
542
          builder.getPointerField(slot.getOffset() * POINTERS).setBlob<Data>(value.as<Data>());
543 544
          return;

545 546 547 548 549 550
        case schema::Type::LIST: {
          ListSchema listType = ListSchema::of(type.getList().getElementType(), schema);
          auto listValue = value.as<DynamicList>();
          KJ_REQUIRE(listValue.getSchema() == listType, "Value type mismatch.") {
            return;
          }
551
          builder.getPointerField(slot.getOffset() * POINTERS).setList(listValue.reader);
552
          return;
553
        }
554

555 556 557 558 559 560
        case schema::Type::STRUCT: {
          auto structType = schema.getDependency(type.getStruct().getTypeId()).asStruct();
          auto structValue = value.as<DynamicStruct>();
          KJ_REQUIRE(structValue.getSchema() == structType, "Value type mismatch.") {
            return;
          }
561
          builder.getPointerField(slot.getOffset() * POINTERS).setStruct(structValue.reader);
562
          return;
563
        }
564

565 566 567
        case schema::Type::ANY_POINTER:
          AnyPointer::Builder(builder.getPointerField(slot.getOffset() * POINTERS))
                 .set(value.as<AnyPointer>());
568 569
          return;

Kenton Varda's avatar
Kenton Varda committed
570
        case schema::Type::INTERFACE:
571 572 573 574 575 576 577
          auto interfaceType = schema.getDependency(type.getInterface().getTypeId()).asInterface();
          auto capability = value.as<DynamicCapability>();
          KJ_REQUIRE(capability.getSchema().extends(interfaceType), "Value type mismatch.") {
            return;
          }
          builder.getPointerField(slot.getOffset() * POINTERS).setCapability(
              kj::mv(capability.hook));
578 579
          return;
      }
Kenton Varda's avatar
Kenton Varda committed
580

Kenton Varda's avatar
Kenton Varda committed
581 582 583
      KJ_UNREACHABLE;
    }

Kenton Varda's avatar
Kenton Varda committed
584
    case schema::Field::GROUP: {
Kenton Varda's avatar
Kenton Varda committed
585 586 587 588 589 590 591 592 593 594 595
      auto src = value.as<DynamicStruct>();
      auto dst = init(field).as<DynamicStruct>();

      KJ_IF_MAYBE(unionField, src.which()) {
        dst.set(*unionField, src.get(*unionField));
      }

      for (auto field: src.schema.getNonUnionFields()) {
        if (src.has(field)) {
          dst.set(field, src.get(field));
        }
596
      }
Kenton Varda's avatar
Kenton Varda committed
597
    }
598
  }
Kenton Varda's avatar
Kenton Varda committed
599

Kenton Varda's avatar
Kenton Varda committed
600
  KJ_UNREACHABLE;
601
}
Kenton Varda's avatar
Kenton Varda committed
602

Kenton Varda's avatar
Kenton Varda committed
603 604 605 606 607 608 609
DynamicValue::Builder DynamicStruct::Builder::init(StructSchema::Field field) {
  KJ_REQUIRE(field.getContainingStruct() == schema, "`field` is not a field of this struct.");
  setInUnion(field);

  auto proto = field.getProto();

  switch (proto.which()) {
610 611 612
    case schema::Field::SLOT: {
      auto slot = proto.getSlot();
      auto type = slot.getType();
613 614 615 616 617 618 619
      switch (type.which()) {
        case schema::Type::STRUCT: {
          auto subSchema = schema.getDependency(type.getStruct().getTypeId()).asStruct();
          return DynamicStruct::Builder(subSchema,
              builder.getPointerField(slot.getOffset() * POINTERS)
                     .initStruct(structSizeFromSchema(subSchema)));
        }
620
        case schema::Type::ANY_POINTER: {
621 622
          auto pointer = builder.getPointerField(slot.getOffset() * POINTERS);
          pointer.clear();
623
          return AnyPointer::Builder(pointer);
624 625 626 627
        }
        default:
          KJ_FAIL_REQUIRE("init() without a size is only valid for struct and object fields.");
      }
Kenton Varda's avatar
Kenton Varda committed
628 629
    }

Kenton Varda's avatar
Kenton Varda committed
630
    case schema::Field::GROUP: {
Kenton Varda's avatar
Kenton Varda committed
631
      clear(field);
632 633
      return DynamicStruct::Builder(
          schema.getDependency(proto.getGroup().getTypeId()).asStruct(), builder);
Kenton Varda's avatar
Kenton Varda committed
634 635 636 637 638
    }
  }

  KJ_UNREACHABLE;
}
Kenton Varda's avatar
Kenton Varda committed
639

Kenton Varda's avatar
Kenton Varda committed
640 641 642 643 644 645 646
DynamicValue::Builder DynamicStruct::Builder::init(StructSchema::Field field, uint size) {
  KJ_REQUIRE(field.getContainingStruct() == schema, "`field` is not a field of this struct.");
  setInUnion(field);

  auto proto = field.getProto();

  switch (proto.which()) {
647 648 649
    case schema::Field::SLOT: {
      auto slot = proto.getSlot();
      auto type = slot.getType();
650
      switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
651
        case schema::Type::LIST: {
652
          auto listType = ListSchema::of(type.getList().getElementType(), schema);
Kenton Varda's avatar
Kenton Varda committed
653
          if (listType.whichElementType() == schema::Type::STRUCT) {
Kenton Varda's avatar
Kenton Varda committed
654
            return DynamicList::Builder(listType,
655 656 657
                builder.getPointerField(slot.getOffset() * POINTERS)
                       .initStructList(size * ELEMENTS,
                                       structSizeFromSchema(listType.getStructElementType())));
Kenton Varda's avatar
Kenton Varda committed
658 659
          } else {
            return DynamicList::Builder(listType,
660 661
                builder.getPointerField(slot.getOffset() * POINTERS)
                       .initList(elementSizeFor(listType.whichElementType()), size * ELEMENTS));
Kenton Varda's avatar
Kenton Varda committed
662 663
          }
        }
Kenton Varda's avatar
Kenton Varda committed
664
        case schema::Type::TEXT:
665 666
          return builder.getPointerField(slot.getOffset() * POINTERS)
                        .initBlob<Text>(size * BYTES);
Kenton Varda's avatar
Kenton Varda committed
667
        case schema::Type::DATA:
668 669
          return builder.getPointerField(slot.getOffset() * POINTERS)
                        .initBlob<Data>(size * BYTES);
670
        default:
671
          KJ_FAIL_REQUIRE(
Kenton Varda's avatar
Kenton Varda committed
672
              "init() with size is only valid for list, text, or data fields.", (uint)type.which());
673 674
          break;
      }
675
    }
Kenton Varda's avatar
Kenton Varda committed
676

Kenton Varda's avatar
Kenton Varda committed
677
    case schema::Field::GROUP:
Kenton Varda's avatar
Kenton Varda committed
678
      KJ_FAIL_REQUIRE("init() with size is only valid for list, text, or data fields.");
Kenton Varda's avatar
Kenton Varda committed
679 680
  }

Kenton Varda's avatar
Kenton Varda committed
681
  KJ_UNREACHABLE;
Kenton Varda's avatar
Kenton Varda committed
682 683
}

684 685 686 687 688 689
void DynamicStruct::Builder::adopt(StructSchema::Field field, Orphan<DynamicValue>&& orphan) {
  KJ_REQUIRE(field.getContainingStruct() == schema, "`field` is not a field of this struct.");
  setInUnion(field);

  auto proto = field.getProto();
  switch (proto.which()) {
690 691 692
    case schema::Field::SLOT: {
      auto slot = proto.getSlot();
      auto type = slot.getType();
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711

      switch (type.which()) {
        case schema::Type::VOID:
        case schema::Type::BOOL:
        case schema::Type::INT8:
        case schema::Type::INT16:
        case schema::Type::INT32:
        case schema::Type::INT64:
        case schema::Type::UINT8:
        case schema::Type::UINT16:
        case schema::Type::UINT32:
        case schema::Type::UINT64:
        case schema::Type::FLOAT32:
        case schema::Type::FLOAT64:
        case schema::Type::ENUM:
          set(field, orphan.getReader());
          return;

        case schema::Type::TEXT:
712
          KJ_REQUIRE(orphan.getType() == DynamicValue::TEXT, "Value type mismatch.");
713 714 715
          break;

        case schema::Type::DATA:
716
          KJ_REQUIRE(orphan.getType() == DynamicValue::DATA, "Value type mismatch.");
717 718 719
          break;

        case schema::Type::LIST: {
720
          ListSchema listType = ListSchema::of(type.getList().getElementType(), schema);
721
          KJ_REQUIRE(orphan.getType() == DynamicValue::LIST && orphan.listSchema == listType,
722 723 724
                     "Value type mismatch.") {
            return;
          }
725 726 727 728
          break;
        }

        case schema::Type::STRUCT: {
729
          auto structType = schema.getDependency(type.getStruct().getTypeId()).asStruct();
730
          KJ_REQUIRE(orphan.getType() == DynamicValue::STRUCT && orphan.structSchema == structType,
731 732 733
                     "Value type mismatch.") {
            return;
          }
734 735 736
          break;
        }

737
        case schema::Type::ANY_POINTER:
738 739
          KJ_REQUIRE(orphan.getType() == DynamicValue::STRUCT ||
                     orphan.getType() == DynamicValue::LIST ||
740
                     orphan.getType() == DynamicValue::ANY_POINTER,
741 742 743
                     "Value type mismatch.") {
            return;
          }
744 745 746
          break;

        case schema::Type::INTERFACE:
747 748 749 750 751 752
          auto interfaceType = schema.getDependency(type.getInterface().getTypeId()).asInterface();
          KJ_REQUIRE(orphan.getType() == DynamicValue::CAPABILITY &&
                     orphan.interfaceSchema.extends(interfaceType),
                     "Value type mismatch.") {
            return;
          }
753 754 755
          break;
      }

756
      builder.getPointerField(slot.getOffset() * POINTERS).adopt(kj::mv(orphan.builder));
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
      return;
    }

    case schema::Field::GROUP:
      // Have to transfer fields.
      auto src = orphan.get().as<DynamicStruct>();
      auto dst = init(field).as<DynamicStruct>();

      KJ_REQUIRE(orphan.getType() == DynamicValue::STRUCT && orphan.structSchema == dst.getSchema(),
                 "Value type mismatch.");

      KJ_IF_MAYBE(unionField, src.which()) {
        dst.adopt(*unionField, src.disown(*unionField));
      }

      for (auto field: src.schema.getNonUnionFields()) {
        if (src.has(field)) {
          dst.adopt(field, src.disown(field));
        }
      }

      return;
  }

  KJ_UNREACHABLE;
}

Orphan<DynamicValue> DynamicStruct::Builder::disown(StructSchema::Field field) {
  // We end up calling get(field) below, so we don't need to validate `field` here.

  auto proto = field.getProto();
  switch (proto.which()) {
789 790
    case schema::Field::SLOT: {
      auto slot = proto.getSlot();
791

792
      switch (slot.getType().which()) {
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
        case schema::Type::VOID:
        case schema::Type::BOOL:
        case schema::Type::INT8:
        case schema::Type::INT16:
        case schema::Type::INT32:
        case schema::Type::INT64:
        case schema::Type::UINT8:
        case schema::Type::UINT16:
        case schema::Type::UINT32:
        case schema::Type::UINT64:
        case schema::Type::FLOAT32:
        case schema::Type::FLOAT64:
        case schema::Type::ENUM: {
          auto result = Orphan<DynamicValue>(get(field), _::OrphanBuilder());
          clear(field);
          return kj::mv(result);
        }

        case schema::Type::TEXT:
        case schema::Type::DATA:
        case schema::Type::LIST:
        case schema::Type::STRUCT:
815
        case schema::Type::ANY_POINTER:
816 817
        case schema::Type::INTERFACE: {
          auto value = get(field);
818 819
          return Orphan<DynamicValue>(
              value, builder.getPointerField(slot.getOffset() * POINTERS).disown());
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
        }
      }
      KJ_UNREACHABLE;
    }

    case schema::Field::GROUP: {
      // We have to allocate new space for the group, unfortunately.
      auto src = get(field).as<DynamicStruct>();

      Orphan<DynamicStruct> result =
          Orphanage::getForMessageContaining(*this).newOrphan(src.getSchema());
      auto dst = result.get();

      KJ_IF_MAYBE(unionField, src.which()) {
        dst.adopt(*unionField, src.disown(*unionField));
      }

      // We need to explicitly reset the union to its default field.
      KJ_IF_MAYBE(unionField, src.schema.getFieldByDiscriminant(0)) {
        src.clear(*unionField);
      }

      for (auto field: src.schema.getNonUnionFields()) {
        if (src.has(field)) {
          dst.adopt(field, src.disown(field));
        }
      }

      return kj::mv(result);
    }
  }

  KJ_UNREACHABLE;
}
Kenton Varda's avatar
Kenton Varda committed
854 855 856 857 858 859 860

void DynamicStruct::Builder::clear(StructSchema::Field field) {
  KJ_REQUIRE(field.getContainingStruct() == schema, "`field` is not a field of this struct.");
  setInUnion(field);

  auto proto = field.getProto();
  switch (proto.which()) {
861 862 863
    case schema::Field::SLOT: {
      auto slot = proto.getSlot();
      auto type = slot.getType();
Kenton Varda's avatar
Kenton Varda committed
864 865

      switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
866
        case schema::Type::VOID:
867
          builder.setDataField<Void>(slot.getOffset() * ELEMENTS, VOID);
Kenton Varda's avatar
Kenton Varda committed
868 869 870
          return;

#define HANDLE_TYPE(discrim, type) \
Kenton Varda's avatar
Kenton Varda committed
871
        case schema::Type::discrim: \
872
          builder.setDataField<type>(slot.getOffset() * ELEMENTS, 0); \
Kenton Varda's avatar
Kenton Varda committed
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
          return;

        HANDLE_TYPE(BOOL, bool)
        HANDLE_TYPE(INT8, uint8_t)
        HANDLE_TYPE(INT16, uint16_t)
        HANDLE_TYPE(INT32, uint32_t)
        HANDLE_TYPE(INT64, uint64_t)
        HANDLE_TYPE(UINT8, uint8_t)
        HANDLE_TYPE(UINT16, uint16_t)
        HANDLE_TYPE(UINT32, uint32_t)
        HANDLE_TYPE(UINT64, uint64_t)
        HANDLE_TYPE(FLOAT32, uint32_t)
        HANDLE_TYPE(FLOAT64, uint64_t)
        HANDLE_TYPE(ENUM, uint16_t)

#undef HANDLE_TYPE

Kenton Varda's avatar
Kenton Varda committed
890 891 892 893
        case schema::Type::TEXT:
        case schema::Type::DATA:
        case schema::Type::LIST:
        case schema::Type::STRUCT:
894
        case schema::Type::ANY_POINTER:
Kenton Varda's avatar
Kenton Varda committed
895
        case schema::Type::INTERFACE:
896
          builder.getPointerField(slot.getOffset() * POINTERS).clear();
Kenton Varda's avatar
Kenton Varda committed
897 898 899 900 901 902
          return;
      }

      KJ_UNREACHABLE;
    }

Kenton Varda's avatar
Kenton Varda committed
903
    case schema::Field::GROUP: {
904 905
      DynamicStruct::Builder group(
          schema.getDependency(proto.getGroup().getTypeId()).asStruct(), builder);
906 907 908

      // We clear the union field with discriminant 0 rather than the one that is set because
      // we want the union to end up with its default field active.
Kenton Varda's avatar
Kenton Varda committed
909 910 911
      KJ_IF_MAYBE(unionField, group.schema.getFieldByDiscriminant(0)) {
        group.clear(*unionField);
      }
912

Kenton Varda's avatar
Kenton Varda committed
913 914 915
      for (auto subField: group.schema.getNonUnionFields()) {
        group.clear(subField);
      }
916
      return;
Kenton Varda's avatar
Kenton Varda committed
917 918
    }
  }
919

Kenton Varda's avatar
Kenton Varda committed
920 921 922 923 924 925 926 927 928
  KJ_UNREACHABLE;
}

DynamicValue::Reader DynamicStruct::Reader::get(kj::StringPtr name) const {
  return get(schema.getFieldByName(name));
}
DynamicValue::Builder DynamicStruct::Builder::get(kj::StringPtr name) {
  return get(schema.getFieldByName(name));
}
929
DynamicValue::Pipeline DynamicStruct::Pipeline::get(kj::StringPtr name) {
930 931
  return get(schema.getFieldByName(name));
}
Kenton Varda's avatar
Kenton Varda committed
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
bool DynamicStruct::Reader::has(kj::StringPtr name) const {
  return has(schema.getFieldByName(name));
}
bool DynamicStruct::Builder::has(kj::StringPtr name) {
  return has(schema.getFieldByName(name));
}
void DynamicStruct::Builder::set(kj::StringPtr name, const DynamicValue::Reader& value) {
  set(schema.getFieldByName(name), value);
}
void DynamicStruct::Builder::set(kj::StringPtr name,
                                 std::initializer_list<DynamicValue::Reader> value) {
  auto list = init(name, value.size()).as<DynamicList>();
  uint i = 0;
  for (auto element: value) {
    list.set(i++, element);
  }
}
DynamicValue::Builder DynamicStruct::Builder::init(kj::StringPtr name) {
  return init(schema.getFieldByName(name));
}
DynamicValue::Builder DynamicStruct::Builder::init(kj::StringPtr name, uint size) {
  return init(schema.getFieldByName(name), size);
}
955 956 957 958 959 960
void DynamicStruct::Builder::adopt(kj::StringPtr name, Orphan<DynamicValue>&& orphan) {
  adopt(schema.getFieldByName(name), kj::mv(orphan));
}
Orphan<DynamicValue> DynamicStruct::Builder::disown(kj::StringPtr name) {
  return disown(schema.getFieldByName(name));
}
Kenton Varda's avatar
Kenton Varda committed
961
void DynamicStruct::Builder::clear(kj::StringPtr name) {
962
  clear(schema.getFieldByName(name));
Kenton Varda's avatar
Kenton Varda committed
963
}
Kenton Varda's avatar
Kenton Varda committed
964 965 966

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

967
DynamicValue::Reader DynamicList::Reader::operator[](uint index) const {
968
  KJ_REQUIRE(index < size(), "List index out-of-bounds.");
Kenton Varda's avatar
Kenton Varda committed
969

970
  switch (schema.whichElementType()) {
Kenton Varda's avatar
Kenton Varda committed
971
#define HANDLE_TYPE(name, discrim, typeName) \
Kenton Varda's avatar
Kenton Varda committed
972
    case schema::Type::discrim: \
973
      return reader.getDataElement<typeName>(index * ELEMENTS);
974 975 976 977 978 979 980 981 982 983 984 985 986

    HANDLE_TYPE(void, VOID, Void)
    HANDLE_TYPE(bool, BOOL, bool)
    HANDLE_TYPE(int8, INT8, int8_t)
    HANDLE_TYPE(int16, INT16, int16_t)
    HANDLE_TYPE(int32, INT32, int32_t)
    HANDLE_TYPE(int64, INT64, int64_t)
    HANDLE_TYPE(uint8, UINT8, uint8_t)
    HANDLE_TYPE(uint16, UINT16, uint16_t)
    HANDLE_TYPE(uint32, UINT32, uint32_t)
    HANDLE_TYPE(uint64, UINT64, uint64_t)
    HANDLE_TYPE(float32, FLOAT32, float)
    HANDLE_TYPE(float64, FLOAT64, double)
Kenton Varda's avatar
Kenton Varda committed
987 988
#undef HANDLE_TYPE

Kenton Varda's avatar
Kenton Varda committed
989
    case schema::Type::TEXT:
990
      return reader.getPointerElement(index * ELEMENTS).getBlob<Text>(nullptr, 0 * BYTES);
Kenton Varda's avatar
Kenton Varda committed
991
    case schema::Type::DATA:
992
      return reader.getPointerElement(index * ELEMENTS).getBlob<Data>(nullptr, 0 * BYTES);
Kenton Varda's avatar
Kenton Varda committed
993

Kenton Varda's avatar
Kenton Varda committed
994
    case schema::Type::LIST: {
995
      auto elementType = schema.getListElementType();
996 997 998
      return DynamicList::Reader(elementType,
          reader.getPointerElement(index * ELEMENTS)
                .getList(elementSizeFor(elementType.whichElementType()), nullptr));
999
    }
Kenton Varda's avatar
Kenton Varda committed
1000

Kenton Varda's avatar
Kenton Varda committed
1001
    case schema::Type::STRUCT:
1002 1003
      return DynamicStruct::Reader(schema.getStructElementType(),
                                   reader.getStructElement(index * ELEMENTS));
Kenton Varda's avatar
Kenton Varda committed
1004

Kenton Varda's avatar
Kenton Varda committed
1005
    case schema::Type::ENUM:
1006 1007
      return DynamicEnum(schema.getEnumElementType(),
                         reader.getDataElement<uint16_t>(index * ELEMENTS));
Kenton Varda's avatar
Kenton Varda committed
1008

1009 1010
    case schema::Type::ANY_POINTER:
      return AnyPointer::Reader(reader.getPointerElement(index * ELEMENTS));
Kenton Varda's avatar
Kenton Varda committed
1011

Kenton Varda's avatar
Kenton Varda committed
1012
    case schema::Type::INTERFACE:
1013 1014
      return DynamicCapability::Client(schema.getInterfaceElementType(),
                                       reader.getPointerElement(index * ELEMENTS).getCapability());
Kenton Varda's avatar
Kenton Varda committed
1015
  }
1016

1017
  return nullptr;
Kenton Varda's avatar
Kenton Varda committed
1018 1019
}

1020
DynamicValue::Builder DynamicList::Builder::operator[](uint index) {
1021
  KJ_REQUIRE(index < size(), "List index out-of-bounds.");
Kenton Varda's avatar
Kenton Varda committed
1022

1023
  switch (schema.whichElementType()) {
Kenton Varda's avatar
Kenton Varda committed
1024
#define HANDLE_TYPE(name, discrim, typeName) \
Kenton Varda's avatar
Kenton Varda committed
1025
    case schema::Type::discrim: \
1026
      return builder.getDataElement<typeName>(index * ELEMENTS);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039

    HANDLE_TYPE(void, VOID, Void)
    HANDLE_TYPE(bool, BOOL, bool)
    HANDLE_TYPE(int8, INT8, int8_t)
    HANDLE_TYPE(int16, INT16, int16_t)
    HANDLE_TYPE(int32, INT32, int32_t)
    HANDLE_TYPE(int64, INT64, int64_t)
    HANDLE_TYPE(uint8, UINT8, uint8_t)
    HANDLE_TYPE(uint16, UINT16, uint16_t)
    HANDLE_TYPE(uint32, UINT32, uint32_t)
    HANDLE_TYPE(uint64, UINT64, uint64_t)
    HANDLE_TYPE(float32, FLOAT32, float)
    HANDLE_TYPE(float64, FLOAT64, double)
Kenton Varda's avatar
Kenton Varda committed
1040 1041
#undef HANDLE_TYPE

Kenton Varda's avatar
Kenton Varda committed
1042
    case schema::Type::TEXT:
1043
      return builder.getPointerElement(index * ELEMENTS).getBlob<Text>(nullptr, 0 * BYTES);
Kenton Varda's avatar
Kenton Varda committed
1044
    case schema::Type::DATA:
1045
      return builder.getPointerElement(index * ELEMENTS).getBlob<Data>(nullptr, 0 * BYTES);
Kenton Varda's avatar
Kenton Varda committed
1046

Kenton Varda's avatar
Kenton Varda committed
1047
    case schema::Type::LIST: {
1048
      ListSchema elementType = schema.getListElementType();
Kenton Varda's avatar
Kenton Varda committed
1049
      if (elementType.whichElementType() == schema::Type::STRUCT) {
1050
        return DynamicList::Builder(elementType,
1051 1052 1053
            builder.getPointerElement(index * ELEMENTS)
                   .getStructList(structSizeFromSchema(elementType.getStructElementType()),
                                  nullptr));
1054
      } else {
1055
        return DynamicList::Builder(elementType,
1056 1057
            builder.getPointerElement(index * ELEMENTS)
                   .getList(elementSizeFor(elementType.whichElementType()), nullptr));
1058 1059
      }
    }
Kenton Varda's avatar
Kenton Varda committed
1060

Kenton Varda's avatar
Kenton Varda committed
1061
    case schema::Type::STRUCT:
1062 1063
      return DynamicStruct::Builder(schema.getStructElementType(),
                                    builder.getStructElement(index * ELEMENTS));
Kenton Varda's avatar
Kenton Varda committed
1064

Kenton Varda's avatar
Kenton Varda committed
1065
    case schema::Type::ENUM:
1066 1067
      return DynamicEnum(schema.getEnumElementType(),
                         builder.getDataElement<uint16_t>(index * ELEMENTS));
Kenton Varda's avatar
Kenton Varda committed
1068

1069 1070
    case schema::Type::ANY_POINTER:
      KJ_FAIL_ASSERT("List(AnyPointer) not supported.");
1071
      return nullptr;
Kenton Varda's avatar
Kenton Varda committed
1072

Kenton Varda's avatar
Kenton Varda committed
1073
    case schema::Type::INTERFACE:
1074 1075
      return DynamicCapability::Client(schema.getInterfaceElementType(),
                                       builder.getPointerElement(index * ELEMENTS).getCapability());
Kenton Varda's avatar
Kenton Varda committed
1076
  }
1077

1078
  return nullptr;
Kenton Varda's avatar
Kenton Varda committed
1079 1080
}

1081
void DynamicList::Builder::set(uint index, const DynamicValue::Reader& value) {
1082
  KJ_REQUIRE(index < size(), "List index out-of-bounds.") {
1083 1084
    return;
  }
Kenton Varda's avatar
Kenton Varda committed
1085

1086
  switch (schema.whichElementType()) {
Kenton Varda's avatar
Kenton Varda committed
1087
#define HANDLE_TYPE(name, discrim, typeName) \
Kenton Varda's avatar
Kenton Varda committed
1088
    case schema::Type::discrim: \
1089
      builder.setDataElement<typeName>(index * ELEMENTS, value.as<typeName>()); \
1090
      return;
Kenton Varda's avatar
Kenton Varda committed
1091

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    HANDLE_TYPE(void, VOID, Void)
    HANDLE_TYPE(bool, BOOL, bool)
    HANDLE_TYPE(int8, INT8, int8_t)
    HANDLE_TYPE(int16, INT16, int16_t)
    HANDLE_TYPE(int32, INT32, int32_t)
    HANDLE_TYPE(int64, INT64, int64_t)
    HANDLE_TYPE(uint8, UINT8, uint8_t)
    HANDLE_TYPE(uint16, UINT16, uint16_t)
    HANDLE_TYPE(uint32, UINT32, uint32_t)
    HANDLE_TYPE(uint64, UINT64, uint64_t)
    HANDLE_TYPE(float32, FLOAT32, float)
    HANDLE_TYPE(float64, FLOAT64, double)
Kenton Varda's avatar
Kenton Varda committed
1104 1105
#undef HANDLE_TYPE

Kenton Varda's avatar
Kenton Varda committed
1106
    case schema::Type::TEXT:
1107
      builder.getPointerElement(index * ELEMENTS).setBlob<Text>(value.as<Text>());
1108
      return;
Kenton Varda's avatar
Kenton Varda committed
1109
    case schema::Type::DATA:
1110
      builder.getPointerElement(index * ELEMENTS).setBlob<Data>(value.as<Data>());
1111
      return;
Kenton Varda's avatar
Kenton Varda committed
1112

Kenton Varda's avatar
Kenton Varda committed
1113
    case schema::Type::LIST: {
1114 1115 1116 1117
      auto listValue = value.as<DynamicList>();
      KJ_REQUIRE(listValue.getSchema() == schema.getListElementType(), "Value type mismatch.") {
        return;
      }
1118
      builder.getPointerElement(index * ELEMENTS).setList(listValue.reader);
1119
      return;
1120
    }
Kenton Varda's avatar
Kenton Varda committed
1121

1122
    case schema::Type::STRUCT: {
1123 1124 1125 1126 1127
      auto structValue = value.as<DynamicStruct>();
      KJ_REQUIRE(structValue.getSchema() == schema.getStructElementType(), "Value type mismatch.") {
        return;
      }
      builder.getStructElement(index * ELEMENTS).copyContentFrom(structValue.reader);
1128 1129
      return;
    }
Kenton Varda's avatar
Kenton Varda committed
1130

Kenton Varda's avatar
Kenton Varda committed
1131
    case schema::Type::ENUM: {
1132 1133 1134 1135 1136 1137
      uint16_t rawValue;
      if (value.getType() == DynamicValue::TEXT) {
        // Convert from text.
        rawValue = schema.getEnumElementType().getEnumerantByName(value.as<Text>()).getOrdinal();
      } else {
        DynamicEnum enumValue = value.as<DynamicEnum>();
1138 1139
        KJ_REQUIRE(schema.getEnumElementType() == enumValue.getSchema(),
                   "Type mismatch when using DynamicList::Builder::set().") {
1140 1141 1142
          return;
        }
        rawValue = enumValue.getRaw();
1143
      }
1144
      builder.setDataElement<uint16_t>(index * ELEMENTS, rawValue);
1145
      return;
1146
    }
Kenton Varda's avatar
Kenton Varda committed
1147

1148 1149
    case schema::Type::ANY_POINTER:
      KJ_FAIL_ASSERT("List(AnyPointer) not supported.") {
1150 1151
        return;
      }
Kenton Varda's avatar
Kenton Varda committed
1152

1153 1154 1155 1156
    case schema::Type::INTERFACE: {
      auto capValue = value.as<DynamicCapability>();
      KJ_REQUIRE(capValue.getSchema().extends(schema.getInterfaceElementType()),
                 "Value type mismatch.") {
1157 1158
        return;
      }
1159 1160 1161
      builder.getPointerElement(index * ELEMENTS).setCapability(kj::mv(capValue.hook));
      return;
    }
Kenton Varda's avatar
Kenton Varda committed
1162
  }
1163

1164 1165 1166
  KJ_FAIL_REQUIRE("can't set element of unknown type", (uint)schema.whichElementType()) {
    return;
  }
Kenton Varda's avatar
Kenton Varda committed
1167 1168 1169
}

DynamicValue::Builder DynamicList::Builder::init(uint index, uint size) {
1170
  KJ_REQUIRE(index < this->size(), "List index out-of-bounds.");
Kenton Varda's avatar
Kenton Varda committed
1171

1172
  switch (schema.whichElementType()) {
Kenton Varda's avatar
Kenton Varda committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    case schema::Type::VOID:
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::ENUM:
    case schema::Type::STRUCT:
    case schema::Type::INTERFACE:
1188
      KJ_FAIL_REQUIRE("Expected a list or blob.");
1189
      return nullptr;
1190

Kenton Varda's avatar
Kenton Varda committed
1191
    case schema::Type::TEXT:
1192
      return builder.getPointerElement(index * ELEMENTS).initBlob<Text>(size * BYTES);
1193

Kenton Varda's avatar
Kenton Varda committed
1194
    case schema::Type::DATA:
1195
      return builder.getPointerElement(index * ELEMENTS).initBlob<Data>(size * BYTES);
1196

Kenton Varda's avatar
Kenton Varda committed
1197
    case schema::Type::LIST: {
1198 1199
      auto elementType = schema.getListElementType();

Kenton Varda's avatar
Kenton Varda committed
1200
      if (elementType.whichElementType() == schema::Type::STRUCT) {
1201 1202 1203 1204
        return DynamicList::Builder(elementType,
            builder.getPointerElement(index * ELEMENTS)
                   .initStructList(size * ELEMENTS,
                                   structSizeFromSchema(elementType.getStructElementType())));
1205
      } else {
1206 1207 1208
        return DynamicList::Builder(elementType,
            builder.getPointerElement(index * ELEMENTS)
                   .initList(elementSizeFor(elementType.whichElementType()), size * ELEMENTS));
Kenton Varda's avatar
Kenton Varda committed
1209 1210 1211
      }
    }

1212 1213
    case schema::Type::ANY_POINTER: {
      KJ_FAIL_ASSERT("List(AnyPointer) not supported.");
1214
      return nullptr;
Kenton Varda's avatar
Kenton Varda committed
1215 1216
    }
  }
1217

1218
  return nullptr;
Kenton Varda's avatar
Kenton Varda committed
1219 1220
}

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
void DynamicList::Builder::adopt(uint index, Orphan<DynamicValue>&& orphan) {
  switch (schema.whichElementType()) {
    case schema::Type::VOID:
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::ENUM:
      set(index, orphan.getReader());
      return;

    case schema::Type::TEXT:
      KJ_REQUIRE(orphan.getType() == DynamicValue::TEXT, "Value type mismatch.");
1241
      builder.getPointerElement(index * ELEMENTS).adopt(kj::mv(orphan.builder));
1242 1243 1244 1245
      return;

    case schema::Type::DATA:
      KJ_REQUIRE(orphan.getType() == DynamicValue::DATA, "Value type mismatch.");
1246
      builder.getPointerElement(index * ELEMENTS).adopt(kj::mv(orphan.builder));
1247 1248 1249 1250 1251 1252
      return;

    case schema::Type::LIST: {
      ListSchema elementType = schema.getListElementType();
      KJ_REQUIRE(orphan.getType() == DynamicValue::LIST && orphan.listSchema == elementType,
                 "Value type mismatch.");
1253
      builder.getPointerElement(index * ELEMENTS).adopt(kj::mv(orphan.builder));
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
      return;
    }

    case schema::Type::STRUCT: {
      auto elementType = schema.getStructElementType();
      KJ_REQUIRE(orphan.getType() == DynamicValue::STRUCT && orphan.structSchema == elementType,
                 "Value type mismatch.");
      builder.getStructElement(index * ELEMENTS).transferContentFrom(
          orphan.builder.asStruct(structSizeFromSchema(elementType)));
      return;
    }

1266 1267
    case schema::Type::ANY_POINTER:
      KJ_FAIL_ASSERT("List(AnyPointer) not supported.");
1268

1269 1270 1271 1272 1273 1274 1275 1276
    case schema::Type::INTERFACE: {
      auto elementType = schema.getInterfaceElementType();
      KJ_REQUIRE(orphan.getType() == DynamicValue::CAPABILITY &&
                 orphan.interfaceSchema.extends(elementType),
                 "Value type mismatch.");
      builder.getPointerElement(index * ELEMENTS).adopt(kj::mv(orphan.builder));
      return;
    }
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
  }

  KJ_UNREACHABLE;
}

Orphan<DynamicValue> DynamicList::Builder::disown(uint index) {
  switch (schema.whichElementType()) {
    case schema::Type::VOID:
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::ENUM: {
      auto result = Orphan<DynamicValue>(operator[](index), _::OrphanBuilder());
      switch (elementSizeFor(schema.whichElementType())) {
        case _::FieldSize::VOID: break;
        case _::FieldSize::BIT: builder.setDataElement<bool>(index * ELEMENTS, false); break;
        case _::FieldSize::BYTE: builder.setDataElement<uint8_t>(index * ELEMENTS, 0); break;
        case _::FieldSize::TWO_BYTES: builder.setDataElement<uint16_t>(index * ELEMENTS, 0); break;
        case _::FieldSize::FOUR_BYTES: builder.setDataElement<uint32_t>(index * ELEMENTS, 0); break;
        case _::FieldSize::EIGHT_BYTES: builder.setDataElement<uint64_t>(index * ELEMENTS, 0);break;

        case _::FieldSize::POINTER:
        case _::FieldSize::INLINE_COMPOSITE:
          KJ_UNREACHABLE;
      }
      return kj::mv(result);
    }

    case schema::Type::TEXT:
    case schema::Type::DATA:
    case schema::Type::LIST:
1316
    case schema::Type::ANY_POINTER:
1317 1318
    case schema::Type::INTERFACE: {
      auto value = operator[](index);
1319
      return Orphan<DynamicValue>(value, builder.getPointerElement(index * ELEMENTS).disown());
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
    }

    case schema::Type::STRUCT: {
      // We have to make a copy.
      Orphan<DynamicStruct> result =
          Orphanage::getForMessageContaining(*this).newOrphan(schema.getStructElementType());
      auto element = builder.getStructElement(index * ELEMENTS);
      result.get().builder.transferContentFrom(element);
      element.clearAll();
      return kj::mv(result);
    }
  }
  KJ_UNREACHABLE;
}

1335
void DynamicList::Builder::copyFrom(std::initializer_list<DynamicValue::Reader> value) {
1336
  KJ_REQUIRE(value.size() == size(), "DynamicList::copyFrom() argument had different size.");
1337 1338 1339 1340 1341 1342
  uint i = 0;
  for (auto element: value) {
    set(i++, element);
  }
}

1343
DynamicList::Reader DynamicList::Builder::asReader() const {
1344
  return DynamicList::Reader(schema, builder.asReader());
Kenton Varda's avatar
Kenton Varda committed
1345 1346
}

Kenton Varda's avatar
Kenton Varda committed
1347 1348
// =======================================================================================

Kenton Varda's avatar
Kenton Varda committed
1349
DynamicValue::Reader::Reader(ConstSchema constant): type(VOID) {
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
  auto typeSchema = constant.getProto().getConst().getType();
  auto value = constant.getProto().getConst().getValue();
  switch (typeSchema.which()) {
    case schema::Type::VOID: *this = capnp::VOID; break;
    case schema::Type::BOOL: *this = value.getBool(); break;
    case schema::Type::INT8: *this = value.getInt8(); break;
    case schema::Type::INT16: *this = value.getInt16(); break;
    case schema::Type::INT32: *this = value.getInt32(); break;
    case schema::Type::INT64: *this = value.getInt64(); break;
    case schema::Type::UINT8: *this = value.getUint8(); break;
    case schema::Type::UINT16: *this = value.getUint16(); break;
    case schema::Type::UINT32: *this = value.getUint32(); break;
    case schema::Type::UINT64: *this = value.getUint64(); break;
    case schema::Type::FLOAT32: *this = value.getFloat32(); break;
    case schema::Type::FLOAT64: *this = value.getFloat64(); break;
    case schema::Type::TEXT: *this = value.getText(); break;
    case schema::Type::DATA: *this = value.getData(); break;

    case schema::Type::ENUM:
1369 1370
      *this = DynamicEnum(constant.getDependency(
          typeSchema.getEnum().getTypeId()).asEnum(), value.getEnum());
1371 1372 1373
      break;

    case schema::Type::STRUCT:
1374
      *this = value.getStruct().getAs<DynamicStruct>(
1375
          constant.getDependency(typeSchema.getStruct().getTypeId()).asStruct());
1376 1377 1378
      break;

    case schema::Type::LIST:
1379
      *this = value.getList().getAs<DynamicList>(
1380
          ListSchema::of(typeSchema.getList().getElementType(), constant));
1381 1382
      break;

1383 1384
    case schema::Type::ANY_POINTER:
      *this = value.getAnyPointer();
1385 1386 1387 1388 1389 1390 1391
      break;

    case schema::Type::INTERFACE:
      KJ_FAIL_ASSERT("Constants can't have interface type.");
  }
}

1392
DynamicValue::Reader::Reader(const Reader& other) {
Kenton Varda's avatar
Kenton Varda committed
1393
  switch (other.type) {
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    case UNKNOWN:
    case VOID:
    case BOOL:
    case INT:
    case UINT:
    case FLOAT:
    case TEXT:
    case DATA:
    case LIST:
    case ENUM:
    case STRUCT:
1405
    case ANY_POINTER:
1406 1407 1408 1409 1410 1411
      static_assert(kj::canMemcpy<Text::Reader>() &&
                    kj::canMemcpy<Data::Reader>() &&
                    kj::canMemcpy<DynamicList::Reader>() &&
                    kj::canMemcpy<DynamicEnum>() &&
                    kj::canMemcpy<DynamicStruct::Reader>() &&
                    kj::canMemcpy<AnyPointer::Reader>(),
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
                    "Assumptions here don't hold.");
      break;

    case CAPABILITY:
      type = CAPABILITY;
      kj::ctor(capabilityValue, other.capabilityValue);
      return;
  }

  memcpy(this, &other, sizeof(*this));
}
Kenton Varda's avatar
Kenton Varda committed
1423 1424
DynamicValue::Reader::Reader(Reader&& other) noexcept {
  switch (other.type) {
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    case UNKNOWN:
    case VOID:
    case BOOL:
    case INT:
    case UINT:
    case FLOAT:
    case TEXT:
    case DATA:
    case LIST:
    case ENUM:
    case STRUCT:
1436
    case ANY_POINTER:
1437 1438 1439 1440 1441 1442
      static_assert(kj::canMemcpy<Text::Reader>() &&
                    kj::canMemcpy<Data::Reader>() &&
                    kj::canMemcpy<DynamicList::Reader>() &&
                    kj::canMemcpy<DynamicEnum>() &&
                    kj::canMemcpy<DynamicStruct::Reader>() &&
                    kj::canMemcpy<AnyPointer::Reader>(),
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
                    "Assumptions here don't hold.");
      break;

    case CAPABILITY:
      type = CAPABILITY;
      kj::ctor(capabilityValue, kj::mv(other.capabilityValue));
      return;
  }

  memcpy(this, &other, sizeof(*this));
}
Kenton Varda's avatar
Kenton Varda committed
1454
DynamicValue::Reader::~Reader() noexcept(false) {
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
  if (type == CAPABILITY) {
    kj::dtor(capabilityValue);
  }
}

DynamicValue::Reader& DynamicValue::Reader::operator=(const Reader& other) {
  if (type == CAPABILITY) {
    kj::dtor(capabilityValue);
  }
  kj::ctor(*this, other);
  return *this;
}
DynamicValue::Reader& DynamicValue::Reader::operator=(Reader&& other) {
  if (type == CAPABILITY) {
    kj::dtor(capabilityValue);
  }
  kj::ctor(*this, kj::mv(other));
  return *this;
}

DynamicValue::Builder::Builder(Builder& other) {
Kenton Varda's avatar
Kenton Varda committed
1476
  switch (other.type) {
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
    case UNKNOWN:
    case VOID:
    case BOOL:
    case INT:
    case UINT:
    case FLOAT:
    case TEXT:
    case DATA:
    case LIST:
    case ENUM:
    case STRUCT:
1488
    case ANY_POINTER:
1489
      // Unfortunately canMemcpy() doesn't work on these types due to the use of
1490 1491 1492 1493 1494 1495 1496
      // DisallowConstCopy, but __has_trivial_destructor should detect if any of these types
      // become non-trivial.
      static_assert(__has_trivial_destructor(Text::Builder) &&
                    __has_trivial_destructor(Data::Builder) &&
                    __has_trivial_destructor(DynamicList::Builder) &&
                    __has_trivial_destructor(DynamicEnum) &&
                    __has_trivial_destructor(DynamicStruct::Builder) &&
1497
                    __has_trivial_destructor(AnyPointer::Builder),
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
                    "Assumptions here don't hold.");
      break;

    case CAPABILITY:
      type = CAPABILITY;
      kj::ctor(capabilityValue, other.capabilityValue);
      return;
  }

  memcpy(this, &other, sizeof(*this));
}
Kenton Varda's avatar
Kenton Varda committed
1509 1510
DynamicValue::Builder::Builder(Builder&& other) noexcept {
  switch (other.type) {
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
    case UNKNOWN:
    case VOID:
    case BOOL:
    case INT:
    case UINT:
    case FLOAT:
    case TEXT:
    case DATA:
    case LIST:
    case ENUM:
    case STRUCT:
1522
    case ANY_POINTER:
1523 1524 1525 1526 1527 1528 1529 1530
      // Unfortunately __has_trivial_copy doesn't work on these types due to the use of
      // DisallowConstCopy, but __has_trivial_destructor should detect if any of these types
      // become non-trivial.
      static_assert(__has_trivial_destructor(Text::Builder) &&
                    __has_trivial_destructor(Data::Builder) &&
                    __has_trivial_destructor(DynamicList::Builder) &&
                    __has_trivial_destructor(DynamicEnum) &&
                    __has_trivial_destructor(DynamicStruct::Builder) &&
1531
                    __has_trivial_destructor(AnyPointer::Builder),
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
                    "Assumptions here don't hold.");
      break;

    case CAPABILITY:
      type = CAPABILITY;
      kj::ctor(capabilityValue, kj::mv(other.capabilityValue));
      return;
  }

  memcpy(this, &other, sizeof(*this));
}
Kenton Varda's avatar
Kenton Varda committed
1543
DynamicValue::Builder::~Builder() noexcept(false) {
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
  if (type == CAPABILITY) {
    kj::dtor(capabilityValue);
  }
}

DynamicValue::Builder& DynamicValue::Builder::operator=(Builder& other) {
  if (type == CAPABILITY) {
    kj::dtor(capabilityValue);
  }
  kj::ctor(*this, other);
  return *this;
}
DynamicValue::Builder& DynamicValue::Builder::operator=(Builder&& other) {
  if (type == CAPABILITY) {
    kj::dtor(capabilityValue);
  }
  kj::ctor(*this, kj::mv(other));
  return *this;
}

1564
DynamicValue::Reader DynamicValue::Builder::asReader() const {
Kenton Varda's avatar
Kenton Varda committed
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
  switch (type) {
    case UNKNOWN: return Reader();
    case VOID: return Reader(voidValue);
    case BOOL: return Reader(boolValue);
    case INT: return Reader(intValue);
    case UINT: return Reader(uintValue);
    case FLOAT: return Reader(floatValue);
    case TEXT: return Reader(textValue.asReader());
    case DATA: return Reader(dataValue.asReader());
    case LIST: return Reader(listValue.asReader());
    case ENUM: return Reader(enumValue);
    case STRUCT: return Reader(structValue.asReader());
1577
    case CAPABILITY: return Reader(capabilityValue);
1578
    case ANY_POINTER: return Reader(anyPointerValue.asReader());
Kenton Varda's avatar
Kenton Varda committed
1579
  }
1580
  KJ_FAIL_ASSERT("Missing switch case.");
Kenton Varda's avatar
Kenton Varda committed
1581 1582 1583
  return Reader();
}

1584
DynamicValue::Pipeline::Pipeline(Pipeline&& other) noexcept: type(other.type) {
1585 1586 1587 1588 1589
  switch (type) {
    case UNKNOWN: break;
    case STRUCT: kj::ctor(structValue, kj::mv(other.structValue)); break;
    case CAPABILITY: kj::ctor(capabilityValue, kj::mv(other.capabilityValue)); break;
    default:
1590 1591
      KJ_LOG(ERROR, "Unexpected pipeline type.", (uint)type);
      type = UNKNOWN;
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
      break;
  }
}
DynamicValue::Pipeline& DynamicValue::Pipeline::operator=(Pipeline&& other) {
  kj::dtor(*this);
  kj::ctor(*this, kj::mv(other));
  return *this;
}
DynamicValue::Pipeline::~Pipeline() noexcept(false) {
  switch (type) {
    case UNKNOWN: break;
    case STRUCT: kj::dtor(structValue); break;
    case CAPABILITY: kj::dtor(capabilityValue); break;
    default:
      KJ_FAIL_ASSERT("Unexpected pipeline type.", (uint)type) { type = UNKNOWN; break; }
      break;
  }
}

1611 1612 1613 1614
namespace {

template <typename T>
T signedToUnsigned(long long value) {
1615
  KJ_REQUIRE(value >= 0 && T(value) == value, "Value out-of-range for requested type.", value) {
1616
    // Use it anyway.
1617
    break;
1618 1619 1620 1621 1622 1623
  }
  return value;
}

template <>
uint64_t signedToUnsigned<uint64_t>(long long value) {
1624
  KJ_REQUIRE(value >= 0, "Value out-of-range for requested type.", value) {
1625
    // Use it anyway.
1626
    break;
1627 1628 1629 1630 1631 1632
  }
  return value;
}

template <typename T>
T unsignedToSigned(unsigned long long value) {
1633 1634
  KJ_REQUIRE(T(value) >= 0 && (unsigned long long)T(value) == value,
             "Value out-of-range for requested type.", value) {
1635
    // Use it anyway.
1636
    break;
1637 1638 1639 1640 1641 1642
  }
  return value;
}

template <>
int64_t unsignedToSigned<int64_t>(unsigned long long value) {
1643
  KJ_REQUIRE(int64_t(value) >= 0, "Value out-of-range for requested type.", value) {
1644
    // Use it anyway.
1645
    break;
1646 1647 1648 1649 1650 1651
  }
  return value;
}

template <typename T, typename U>
T checkRoundTrip(U value) {
1652
  KJ_REQUIRE(T(value) == value, "Value out-of-range for requested type.", value) {
1653
    // Use it anyway.
1654
    break;
1655 1656 1657 1658 1659 1660 1661
  }
  return value;
}

}  // namespace

#define HANDLE_NUMERIC_TYPE(typeName, ifInt, ifUint, ifFloat) \
1662
typeName DynamicValue::Reader::AsImpl<typeName>::apply(const Reader& reader) { \
1663 1664 1665 1666 1667 1668 1669 1670
  switch (reader.type) { \
    case INT: \
      return ifInt<typeName>(reader.intValue); \
    case UINT: \
      return ifUint<typeName>(reader.uintValue); \
    case FLOAT: \
      return ifFloat<typeName>(reader.floatValue); \
    default: \
Kenton Varda's avatar
Kenton Varda committed
1671
      KJ_FAIL_REQUIRE("Value type mismatch.") { \
1672
        return 0; \
1673
      } \
1674 1675
  } \
} \
1676
typeName DynamicValue::Builder::AsImpl<typeName>::apply(Builder& builder) { \
1677 1678 1679 1680 1681 1682 1683 1684
  switch (builder.type) { \
    case INT: \
      return ifInt<typeName>(builder.intValue); \
    case UINT: \
      return ifUint<typeName>(builder.uintValue); \
    case FLOAT: \
      return ifFloat<typeName>(builder.floatValue); \
    default: \
Kenton Varda's avatar
Kenton Varda committed
1685
      KJ_FAIL_REQUIRE("Value type mismatch.") { \
1686
        return 0; \
1687
      } \
1688 1689 1690 1691 1692 1693
  } \
}

HANDLE_NUMERIC_TYPE(int8_t, checkRoundTrip, unsignedToSigned, checkRoundTrip)
HANDLE_NUMERIC_TYPE(int16_t, checkRoundTrip, unsignedToSigned, checkRoundTrip)
HANDLE_NUMERIC_TYPE(int32_t, checkRoundTrip, unsignedToSigned, checkRoundTrip)
1694
HANDLE_NUMERIC_TYPE(int64_t, kj::implicitCast, unsignedToSigned, checkRoundTrip)
1695 1696 1697
HANDLE_NUMERIC_TYPE(uint8_t, signedToUnsigned, checkRoundTrip, checkRoundTrip)
HANDLE_NUMERIC_TYPE(uint16_t, signedToUnsigned, checkRoundTrip, checkRoundTrip)
HANDLE_NUMERIC_TYPE(uint32_t, signedToUnsigned, checkRoundTrip, checkRoundTrip)
1698 1699 1700
HANDLE_NUMERIC_TYPE(uint64_t, signedToUnsigned, kj::implicitCast, checkRoundTrip)
HANDLE_NUMERIC_TYPE(float, kj::implicitCast, kj::implicitCast, kj::implicitCast)
HANDLE_NUMERIC_TYPE(double, kj::implicitCast, kj::implicitCast, kj::implicitCast)
1701 1702 1703

#undef HANDLE_NUMERIC_TYPE

Kenton Varda's avatar
Kenton Varda committed
1704
#define HANDLE_TYPE(name, discrim, typeName) \
1705
ReaderFor<typeName> DynamicValue::Reader::AsImpl<typeName>::apply(const Reader& reader) { \
Kenton Varda's avatar
Kenton Varda committed
1706
  KJ_REQUIRE(reader.type == discrim, "Value type mismatch.") { \
1707 1708
    return ReaderFor<typeName>(); \
  } \
Kenton Varda's avatar
Kenton Varda committed
1709 1710
  return reader.name##Value; \
} \
1711
BuilderFor<typeName> DynamicValue::Builder::AsImpl<typeName>::apply(Builder& builder) { \
1712
  KJ_REQUIRE(builder.type == discrim, "Value type mismatch."); \
Kenton Varda's avatar
Kenton Varda committed
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
  return builder.name##Value; \
}

//HANDLE_TYPE(void, VOID, Void)
HANDLE_TYPE(bool, BOOL, bool)

HANDLE_TYPE(text, TEXT, Text)
HANDLE_TYPE(list, LIST, DynamicList)
HANDLE_TYPE(struct, STRUCT, DynamicStruct)
HANDLE_TYPE(enum, ENUM, DynamicEnum)
1723
HANDLE_TYPE(anyPointer, ANY_POINTER, AnyPointer)
Kenton Varda's avatar
Kenton Varda committed
1724 1725 1726

#undef HANDLE_TYPE

1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
PipelineFor<DynamicStruct> DynamicValue::Pipeline::AsImpl<DynamicStruct>::apply(
    Pipeline& pipeline) {
  KJ_REQUIRE(pipeline.type == STRUCT, "Pipeline type mismatch.");
  return kj::mv(pipeline.structValue);
}

ReaderFor<DynamicCapability> DynamicValue::Reader::AsImpl<DynamicCapability>::apply(
    const Reader& reader) {
  KJ_REQUIRE(reader.type == CAPABILITY, "Value type mismatch.") {
    return DynamicCapability::Client();
  }
  return reader.capabilityValue;
}
BuilderFor<DynamicCapability> DynamicValue::Builder::AsImpl<DynamicCapability>::apply(
    Builder& builder) {
  KJ_REQUIRE(builder.type == CAPABILITY, "Value type mismatch.") {
    return DynamicCapability::Client();
  }
  return builder.capabilityValue;
}
PipelineFor<DynamicCapability> DynamicValue::Pipeline::AsImpl<DynamicCapability>::apply(
    Pipeline& pipeline) {
  KJ_REQUIRE(pipeline.type == CAPABILITY, "Pipeline type mismatch.") {
    return DynamicCapability::Client();
  }
  return kj::mv(pipeline.capabilityValue);
}

1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
Data::Reader DynamicValue::Reader::AsImpl<Data>::apply(const Reader& reader) {
  if (reader.type == TEXT) {
    // Coerce text to data.
    return Data::Reader(reinterpret_cast<const byte*>(reader.textValue.begin()),
                        reader.textValue.size());
  }
  KJ_REQUIRE(reader.type == DATA, "Value type mismatch.") {
    return Data::Reader();
  }
  return reader.dataValue;
}
Data::Builder DynamicValue::Builder::AsImpl<Data>::apply(Builder& builder) {
  if (builder.type == TEXT) {
    // Coerce text to data.
    return Data::Builder(reinterpret_cast<byte*>(builder.textValue.begin()),
                         builder.textValue.size());
  }
  KJ_REQUIRE(builder.type == DATA, "Value type mismatch.") {
    return BuilderFor<Data>();
  }
  return builder.dataValue;
}

Kenton Varda's avatar
Kenton Varda committed
1778
// As in the header, HANDLE_TYPE(void, VOID, Void) crashes GCC 4.7.
1779
Void DynamicValue::Reader::AsImpl<Void>::apply(const Reader& reader) {
Kenton Varda's avatar
Kenton Varda committed
1780
  KJ_REQUIRE(reader.type == VOID, "Value type mismatch.") {
Kenton Varda's avatar
Kenton Varda committed
1781 1782 1783 1784
    return Void();
  }
  return reader.voidValue;
}
1785
Void DynamicValue::Builder::AsImpl<Void>::apply(Builder& builder) {
Kenton Varda's avatar
Kenton Varda committed
1786
  KJ_REQUIRE(builder.type == VOID, "Value type mismatch.") {
Kenton Varda's avatar
Kenton Varda committed
1787 1788 1789 1790 1791
    return Void();
  }
  return builder.voidValue;
}

Kenton Varda's avatar
Kenton Varda committed
1792 1793
// =======================================================================================

1794
namespace _ {  // private
Kenton Varda's avatar
Kenton Varda committed
1795

1796
DynamicStruct::Reader PointerHelpers<DynamicStruct, Kind::UNKNOWN>::getDynamic(
1797
    PointerReader reader, StructSchema schema) {
1798 1799
  KJ_REQUIRE(!schema.getProto().getStruct().getIsGroup(),
             "Cannot form pointer to group type.");
1800
  return DynamicStruct::Reader(schema, reader.getStruct(nullptr));
Kenton Varda's avatar
Kenton Varda committed
1801
}
1802
DynamicStruct::Builder PointerHelpers<DynamicStruct, Kind::UNKNOWN>::getDynamic(
1803
    PointerBuilder builder, StructSchema schema) {
1804 1805
  KJ_REQUIRE(!schema.getProto().getStruct().getIsGroup(),
             "Cannot form pointer to group type.");
1806
  return DynamicStruct::Builder(schema, builder.getStruct(
1807
      structSizeFromSchema(schema), nullptr));
Kenton Varda's avatar
Kenton Varda committed
1808 1809
}
void PointerHelpers<DynamicStruct, Kind::UNKNOWN>::set(
1810
    PointerBuilder builder, const DynamicStruct::Reader& value) {
1811 1812
  KJ_REQUIRE(!value.schema.getProto().getStruct().getIsGroup(),
             "Cannot form pointer to group type.");
1813
  builder.setStruct(value.reader);
Kenton Varda's avatar
Kenton Varda committed
1814 1815
}
DynamicStruct::Builder PointerHelpers<DynamicStruct, Kind::UNKNOWN>::init(
1816
    PointerBuilder builder, StructSchema schema) {
1817 1818
  KJ_REQUIRE(!schema.getProto().getStruct().getIsGroup(),
             "Cannot form pointer to group type.");
1819
  return DynamicStruct::Builder(schema,
1820
      builder.initStruct(structSizeFromSchema(schema)));
Kenton Varda's avatar
Kenton Varda committed
1821 1822
}

1823
DynamicList::Reader PointerHelpers<DynamicList, Kind::UNKNOWN>::getDynamic(
1824
    PointerReader reader, ListSchema schema) {
1825
  return DynamicList::Reader(schema,
1826
      reader.getList(elementSizeFor(schema.whichElementType()), nullptr));
Kenton Varda's avatar
Kenton Varda committed
1827
}
1828
DynamicList::Builder PointerHelpers<DynamicList, Kind::UNKNOWN>::getDynamic(
1829
    PointerBuilder builder, ListSchema schema) {
Kenton Varda's avatar
Kenton Varda committed
1830
  if (schema.whichElementType() == schema::Type::STRUCT) {
1831
    return DynamicList::Builder(schema,
1832
        builder.getStructList(
1833 1834 1835 1836
            structSizeFromSchema(schema.getStructElementType()),
            nullptr));
  } else {
    return DynamicList::Builder(schema,
1837
        builder.getList(elementSizeFor(schema.whichElementType()), nullptr));
1838
  }
Kenton Varda's avatar
Kenton Varda committed
1839 1840
}
void PointerHelpers<DynamicList, Kind::UNKNOWN>::set(
1841 1842
    PointerBuilder builder, const DynamicList::Reader& value) {
  builder.setList(value.reader);
Kenton Varda's avatar
Kenton Varda committed
1843 1844
}
DynamicList::Builder PointerHelpers<DynamicList, Kind::UNKNOWN>::init(
1845
    PointerBuilder builder, ListSchema schema, uint size) {
Kenton Varda's avatar
Kenton Varda committed
1846
  if (schema.whichElementType() == schema::Type::STRUCT) {
1847
    return DynamicList::Builder(schema,
1848
        builder.initStructList(size * ELEMENTS,
1849
            structSizeFromSchema(schema.getStructElementType())));
Kenton Varda's avatar
Kenton Varda committed
1850
  } else {
1851
    return DynamicList::Builder(schema,
1852
        builder.initList(elementSizeFor(schema.whichElementType()), size * ELEMENTS));
Kenton Varda's avatar
Kenton Varda committed
1853 1854 1855
  }
}

1856 1857 1858 1859 1860 1861 1862 1863 1864
DynamicCapability::Client PointerHelpers<DynamicCapability, Kind::UNKNOWN>::getDynamic(
    PointerReader reader, InterfaceSchema schema) {
  return DynamicCapability::Client(schema, reader.getCapability());
}
DynamicCapability::Client PointerHelpers<DynamicCapability, Kind::UNKNOWN>::getDynamic(
    PointerBuilder builder, InterfaceSchema schema) {
  return DynamicCapability::Client(schema, builder.getCapability());
}
void PointerHelpers<DynamicCapability, Kind::UNKNOWN>::set(
1865
    PointerBuilder builder, DynamicCapability::Client& value) {
1866 1867 1868 1869 1870 1871 1872
  builder.setCapability(value.hook->addRef());
}
void PointerHelpers<DynamicCapability, Kind::UNKNOWN>::set(
    PointerBuilder builder, DynamicCapability::Client&& value) {
  builder.setCapability(kj::mv(value.hook));
}

1873
}  // namespace _ (private)
Kenton Varda's avatar
Kenton Varda committed
1874

1875
template <>
1876
void AnyPointer::Builder::adopt<DynamicValue>(Orphan<DynamicValue>&& orphan) {
1877 1878 1879 1880 1881 1882 1883 1884
  switch (orphan.getType()) {
    case DynamicValue::UNKNOWN:
    case DynamicValue::VOID:
    case DynamicValue::BOOL:
    case DynamicValue::INT:
    case DynamicValue::UINT:
    case DynamicValue::FLOAT:
    case DynamicValue::ENUM:
1885
      KJ_FAIL_REQUIRE("AnyPointer cannot adopt primitive (non-object) value.");
1886 1887 1888 1889 1890

    case DynamicValue::STRUCT:
    case DynamicValue::LIST:
    case DynamicValue::TEXT:
    case DynamicValue::DATA:
1891
    case DynamicValue::CAPABILITY:
1892
    case DynamicValue::ANY_POINTER:
1893 1894 1895 1896 1897
      builder.adopt(kj::mv(orphan.builder));
      break;
  }
}

1898
template <>
1899
DynamicStruct::Builder Orphan<AnyPointer>::getAs<DynamicStruct>(StructSchema schema) {
1900 1901 1902
  return DynamicStruct::Builder(schema, builder.asStruct(structSizeFromSchema(schema)));
}
template <>
1903
DynamicStruct::Reader Orphan<AnyPointer>::getAsReader<DynamicStruct>(StructSchema schema) const {
1904 1905 1906
  return DynamicStruct::Reader(schema, builder.asStructReader(structSizeFromSchema(schema)));
}
template <>
1907
Orphan<DynamicStruct> Orphan<AnyPointer>::releaseAs<DynamicStruct>(StructSchema schema) {
1908 1909 1910 1911
  return Orphan<DynamicStruct>(schema, kj::mv(builder));
}

template <>
1912
DynamicList::Builder Orphan<AnyPointer>::getAs<DynamicList>(ListSchema schema) {
1913 1914 1915 1916 1917 1918 1919 1920
  if (schema.whichElementType() == schema::Type::STRUCT) {
    return DynamicList::Builder(schema, builder.asStructList(
        structSizeFromSchema(schema.getStructElementType())));
  } else {
    return DynamicList::Builder(schema, builder.asList(elementSizeFor(schema.whichElementType())));
  }
}
template <>
1921
DynamicList::Reader Orphan<AnyPointer>::getAsReader<DynamicList>(ListSchema schema) const {
1922 1923 1924 1925
  return DynamicList::Reader(schema, builder.asListReader(
      elementSizeFor(schema.whichElementType())));
}
template <>
1926
Orphan<DynamicList> Orphan<AnyPointer>::releaseAs<DynamicList>(ListSchema schema) {
1927 1928 1929
  return Orphan<DynamicList>(schema, kj::mv(builder));
}

1930
template <>
1931
DynamicCapability::Client Orphan<AnyPointer>::getAs<DynamicCapability>(InterfaceSchema schema) {
1932 1933 1934
  return DynamicCapability::Client(schema, builder.asCapability());
}
template <>
1935
DynamicCapability::Client Orphan<AnyPointer>::getAsReader<DynamicCapability>(
1936 1937 1938 1939
    InterfaceSchema schema) const {
  return DynamicCapability::Client(schema, builder.asCapability());
}
template <>
1940
Orphan<DynamicCapability> Orphan<AnyPointer>::releaseAs<DynamicCapability>(
1941 1942 1943 1944
    InterfaceSchema schema) {
  return Orphan<DynamicCapability>(schema, kj::mv(builder));
}

1945 1946
// -------------------------------------------------------------------

1947
Orphan<DynamicStruct> Orphanage::newOrphan(StructSchema schema) const {
1948 1949 1950 1951
  return Orphan<DynamicStruct>(
      schema, _::OrphanBuilder::initStruct(arena, structSizeFromSchema(schema)));
}

1952
Orphan<DynamicList> Orphanage::newOrphan(ListSchema schema, uint size) const {
Kenton Varda's avatar
Kenton Varda committed
1953
  if (schema.whichElementType() == schema::Type::STRUCT) {
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
    return Orphan<DynamicList>(schema, _::OrphanBuilder::initStructList(
        arena, size * ELEMENTS, structSizeFromSchema(schema.getStructElementType())));
  } else {
    return Orphan<DynamicList>(schema, _::OrphanBuilder::initList(
        arena, size * ELEMENTS, elementSizeFor(schema.whichElementType())));
  }
}

DynamicStruct::Builder Orphan<DynamicStruct>::get() {
  return DynamicStruct::Builder(schema, builder.asStruct(structSizeFromSchema(schema)));
}

1966 1967 1968 1969
DynamicStruct::Reader Orphan<DynamicStruct>::getReader() const {
  return DynamicStruct::Reader(schema, builder.asStructReader(structSizeFromSchema(schema)));
}

1970
DynamicList::Builder Orphan<DynamicList>::get() {
Kenton Varda's avatar
Kenton Varda committed
1971
  if (schema.whichElementType() == schema::Type::STRUCT) {
1972 1973 1974 1975 1976 1977 1978 1979
    return DynamicList::Builder(
        schema, builder.asStructList(structSizeFromSchema(schema.getStructElementType())));
  } else {
    return DynamicList::Builder(
        schema, builder.asList(elementSizeFor(schema.whichElementType())));
  }
}

1980 1981 1982 1983 1984
DynamicList::Reader Orphan<DynamicList>::getReader() const {
  return DynamicList::Reader(
      schema, builder.asListReader(elementSizeFor(schema.whichElementType())));
}

1985 1986 1987 1988 1989 1990 1991 1992
DynamicCapability::Client Orphan<DynamicCapability>::get() {
  return DynamicCapability::Client(schema, builder.asCapability());
}

DynamicCapability::Client Orphan<DynamicCapability>::getReader() const {
  return DynamicCapability::Client(schema, builder.asCapability());
}

1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
Orphan<DynamicValue>::Orphan(DynamicValue::Builder value, _::OrphanBuilder&& builder)
    : type(value.getType()), builder(kj::mv(builder)) {
  switch (type) {
    case DynamicValue::UNKNOWN: break;
    case DynamicValue::VOID: voidValue = value.voidValue; break;
    case DynamicValue::BOOL: boolValue = value.boolValue; break;
    case DynamicValue::INT: intValue = value.intValue; break;
    case DynamicValue::UINT: uintValue = value.uintValue; break;
    case DynamicValue::FLOAT: floatValue = value.floatValue; break;
    case DynamicValue::ENUM: enumValue = value.enumValue; break;

    case DynamicValue::TEXT: break;
    case DynamicValue::DATA: break;
    case DynamicValue::LIST: listSchema = value.listValue.getSchema(); break;
    case DynamicValue::STRUCT: structSchema = value.structValue.getSchema(); break;
2008
    case DynamicValue::CAPABILITY: interfaceSchema = value.capabilityValue.getSchema(); break;
2009
    case DynamicValue::ANY_POINTER: break;
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
  }
}

DynamicValue::Builder Orphan<DynamicValue>::get() {
  switch (type) {
    case DynamicValue::UNKNOWN: return nullptr;
    case DynamicValue::VOID: return voidValue;
    case DynamicValue::BOOL: return boolValue;
    case DynamicValue::INT: return intValue;
    case DynamicValue::UINT: return uintValue;
    case DynamicValue::FLOAT: return floatValue;
    case DynamicValue::ENUM: return enumValue;

    case DynamicValue::TEXT: return builder.asText();
    case DynamicValue::DATA: return builder.asData();
    case DynamicValue::LIST:
      if (listSchema.whichElementType() == schema::Type::STRUCT) {
        return DynamicList::Builder(listSchema,
            builder.asStructList(structSizeFromSchema(listSchema.getStructElementType())));
      } else {
        return DynamicList::Builder(listSchema,
            builder.asList(elementSizeFor(listSchema.whichElementType())));
      }
    case DynamicValue::STRUCT:
      return DynamicStruct::Builder(structSchema,
          builder.asStruct(structSizeFromSchema(structSchema)));
2036 2037
    case DynamicValue::CAPABILITY:
      return DynamicCapability::Client(interfaceSchema, builder.asCapability());
2038 2039 2040
    case DynamicValue::ANY_POINTER:
      KJ_FAIL_REQUIRE("Can't get() an AnyPointer orphan; there is no underlying pointer to "
                      "wrap in an AnyPointer::Builder.");
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
  }
  KJ_UNREACHABLE;
}
DynamicValue::Reader Orphan<DynamicValue>::getReader() const {
  switch (type) {
    case DynamicValue::UNKNOWN: return nullptr;
    case DynamicValue::VOID: return voidValue;
    case DynamicValue::BOOL: return boolValue;
    case DynamicValue::INT: return intValue;
    case DynamicValue::UINT: return uintValue;
    case DynamicValue::FLOAT: return floatValue;
    case DynamicValue::ENUM: return enumValue;

    case DynamicValue::TEXT: return builder.asTextReader();
    case DynamicValue::DATA: return builder.asDataReader();
    case DynamicValue::LIST:
      return DynamicList::Reader(listSchema,
          builder.asListReader(elementSizeFor(listSchema.whichElementType())));
    case DynamicValue::STRUCT:
      return DynamicStruct::Reader(structSchema,
          builder.asStructReader(structSizeFromSchema(structSchema)));
2062 2063
    case DynamicValue::CAPABILITY:
      return DynamicCapability::Client(interfaceSchema, builder.asCapability());
2064 2065 2066
    case DynamicValue::ANY_POINTER:
      KJ_FAIL_ASSERT("Can't get() an AnyPointer orphan; there is no underlying pointer to "
                     "wrap in an AnyPointer::Builder.");
2067 2068 2069 2070
  }
  KJ_UNREACHABLE;
}

2071
template <>
2072 2073
Orphan<AnyPointer> Orphan<DynamicValue>::releaseAs<AnyPointer>() {
  KJ_REQUIRE(type == DynamicValue::ANY_POINTER, "Value type mismatch.");
2074
  type = DynamicValue::UNKNOWN;
2075
  return Orphan<AnyPointer>(kj::mv(builder));
2076
}
2077 2078 2079
template <>
Orphan<DynamicStruct> Orphan<DynamicValue>::releaseAs<DynamicStruct>() {
  KJ_REQUIRE(type == DynamicValue::STRUCT, "Value type mismatch.");
2080
  type = DynamicValue::UNKNOWN;
2081 2082 2083 2084 2085
  return Orphan<DynamicStruct>(structSchema, kj::mv(builder));
}
template <>
Orphan<DynamicList> Orphan<DynamicValue>::releaseAs<DynamicList>() {
  KJ_REQUIRE(type == DynamicValue::LIST, "Value type mismatch.");
2086
  type = DynamicValue::UNKNOWN;
2087 2088 2089
  return Orphan<DynamicList>(listSchema, kj::mv(builder));
}

2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
template <>
Orphan<DynamicValue> Orphanage::newOrphanCopy<DynamicValue::Reader>(
    const DynamicValue::Reader& copyFrom) const {
  switch (copyFrom.getType()) {
    case DynamicValue::UNKNOWN: return nullptr;
    case DynamicValue::VOID: return copyFrom.voidValue;
    case DynamicValue::BOOL: return copyFrom.boolValue;
    case DynamicValue::INT: return copyFrom.intValue;
    case DynamicValue::UINT: return copyFrom.uintValue;
    case DynamicValue::FLOAT: return copyFrom.floatValue;
    case DynamicValue::ENUM: return copyFrom.enumValue;

    case DynamicValue::TEXT: return newOrphanCopy(copyFrom.textValue);
    case DynamicValue::DATA: return newOrphanCopy(copyFrom.dataValue);
    case DynamicValue::LIST: return newOrphanCopy(copyFrom.listValue);
    case DynamicValue::STRUCT: return newOrphanCopy(copyFrom.structValue);
2106
    case DynamicValue::CAPABILITY: return newOrphanCopy(copyFrom.capabilityValue);
2107
    case DynamicValue::ANY_POINTER: return newOrphanCopy(copyFrom.anyPointerValue);
2108 2109 2110 2111
  }
  KJ_UNREACHABLE;
}

2112
}  // namespace capnp