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

22 23
#ifndef CAPNP_ANY_H_
#define CAPNP_ANY_H_
24

25
#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS)
26 27 28
#pragma GCC system_header
#endif

29 30
#include "layout.h"
#include "pointer-helpers.h"
31
#include "orphan.h"
32
#include "list.h"
33 34 35 36 37

namespace capnp {

class StructSchema;
class ListSchema;
38
class InterfaceSchema;
39
class Orphanage;
Kenton Varda's avatar
Kenton Varda committed
40
class ClientHook;
41
class PipelineHook;
42
struct PipelineOp;
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
struct AnyPointer;

struct AnyList {
  AnyList() = delete;

  class Reader;
  class Builder;
};

struct AnyStruct {
  AnyStruct() = delete;

  class Reader;
  class Builder;
  class Pipeline;
};

template<>
struct List<AnyStruct, Kind::OTHER> {
  List() = delete;

  class Reader;
  class Builder;
};

namespace _ {  // private
template <> struct Kind_<AnyPointer> { static constexpr Kind kind = Kind::OTHER; };
template <> struct Kind_<AnyStruct> { static constexpr Kind kind = Kind::OTHER; };
template <> struct Kind_<AnyList> { static constexpr Kind kind = Kind::OTHER; };
}  // namespace _ (private)
73 74

// =======================================================================================
75
// AnyPointer!
76

77
enum class Equality {
78 79 80 81 82
  NOT_EQUAL,
  EQUAL,
  UNKNOWN_CONTAINS_CAPS
};

83
kj::StringPtr KJ_STRINGIFY(Equality res);
84

85 86
struct AnyPointer {
  // Reader/Builder for the `AnyPointer` field type, i.e. a pointer that can point to an arbitrary
87 88
  // object.

89 90
  AnyPointer() = delete;

91 92
  class Reader {
  public:
93
    typedef AnyPointer Reads;
94

95 96 97
    Reader() = default;
    inline Reader(_::PointerReader reader): reader(reader) {}

98 99
    inline MessageSize targetSize() const;
    // Get the total size of the target object and all its children.
Kenton Varda's avatar
Kenton Varda committed
100

101 102 103 104 105 106
    inline PointerType getPointerType() const;

    inline bool isNull() const { return getPointerType() == PointerType::NULL_; }
    inline bool isStruct() const { return getPointerType() == PointerType::STRUCT; }
    inline bool isList() const { return getPointerType() == PointerType::LIST; }
    inline bool isCapability() const { return getPointerType() == PointerType::CAPABILITY; }
107

108
    Equality equals(AnyPointer::Reader right);
109 110
    bool operator==(AnyPointer::Reader right);
    inline bool operator!=(AnyPointer::Reader right) {
111
      return !(*this == right);
112
    }
113 114

    template <typename T>
115 116
    inline ReaderFor<T> getAs() const;
    // Valid for T = any generated struct type, interface type, List<U>, Text, or Data.
117 118

    template <typename T>
119
    inline ReaderFor<T> getAs(StructSchema schema) const;
120 121 122
    // Only valid for T = DynamicStruct.  Requires `#include <capnp/dynamic.h>`.

    template <typename T>
123
    inline ReaderFor<T> getAs(ListSchema schema) const;
124 125
    // Only valid for T = DynamicList.  Requires `#include <capnp/dynamic.h>`.

126 127 128 129
    template <typename T>
    inline ReaderFor<T> getAs(InterfaceSchema schema) const;
    // Only valid for T = DynamicCapability.  Requires `#include <capnp/dynamic.h>`.

130
#if !CAPNP_LITE
131
    kj::Own<ClientHook> getPipelinedCap(kj::ArrayPtr<const PipelineOp> ops) const;
Kenton Varda's avatar
Kenton Varda committed
132 133
    // Used by RPC system to implement pipelining.  Applications generally shouldn't use this
    // directly.
134
#endif  // !CAPNP_LITE
Kenton Varda's avatar
Kenton Varda committed
135

136 137
  private:
    _::PointerReader reader;
138
    friend struct AnyPointer;
139
    friend class Orphanage;
140
    friend class CapReaderContext;
141
    friend struct _::PointerHelpers<AnyPointer>;
142 143 144 145
  };

  class Builder {
  public:
146
    typedef AnyPointer Builds;
147

148 149 150 151
    Builder() = delete;
    inline Builder(decltype(nullptr)) {}
    inline Builder(_::PointerBuilder builder): builder(builder) {}

152 153
    inline MessageSize targetSize() const;
    // Get the total size of the target object and all its children.
Kenton Varda's avatar
Kenton Varda committed
154

155 156 157 158 159 160
    inline PointerType getPointerType();

    inline bool isNull() { return getPointerType() == PointerType::NULL_; }
    inline bool isStruct() { return getPointerType() == PointerType::STRUCT; }
    inline bool isList() { return getPointerType() == PointerType::LIST; }
    inline bool isCapability() { return getPointerType() == PointerType::CAPABILITY; }
161

162
    inline Equality equals(AnyPointer::Reader right) {
163 164
      return asReader().equals(right);
    }
165
    inline bool operator==(AnyPointer::Reader right) {
166
      return asReader() == right;
167
    }
168
    inline bool operator!=(AnyPointer::Reader right) {
169
      return !(*this == right);
170
    }
171 172 173 174 175

    inline void clear();
    // Set to null.

    template <typename T>
176
    inline BuilderFor<T> getAs();
177 178 179
    // Valid for T = any generated struct type, List<U>, Text, or Data.

    template <typename T>
180
    inline BuilderFor<T> getAs(StructSchema schema);
181 182 183
    // Only valid for T = DynamicStruct.  Requires `#include <capnp/dynamic.h>`.

    template <typename T>
184
    inline BuilderFor<T> getAs(ListSchema schema);
185 186 187
    // Only valid for T = DynamicList.  Requires `#include <capnp/dynamic.h>`.

    template <typename T>
188 189 190 191 192
    inline BuilderFor<T> getAs(InterfaceSchema schema);
    // Only valid for T = DynamicCapability.  Requires `#include <capnp/dynamic.h>`.

    template <typename T>
    inline BuilderFor<T> initAs();
193 194 195
    // Valid for T = any generated struct type.

    template <typename T>
196
    inline BuilderFor<T> initAs(uint elementCount);
197 198 199
    // Valid for T = List<U>, Text, or Data.

    template <typename T>
200
    inline BuilderFor<T> initAs(StructSchema schema);
201 202 203
    // Only valid for T = DynamicStruct.  Requires `#include <capnp/dynamic.h>`.

    template <typename T>
204
    inline BuilderFor<T> initAs(ListSchema schema, uint elementCount);
205 206
    // Only valid for T = DynamicList.  Requires `#include <capnp/dynamic.h>`.

207
    inline AnyList::Builder initAsAnyList(ElementSize elementSize, uint elementCount);
208 209
    // Note: Does not accept INLINE_COMPOSITE for elementSize.

210
    inline List<AnyStruct>::Builder initAsListOfAnyStruct(
211
        uint16_t dataWordCount, uint16_t pointerCount, uint elementCount);
212

213
    inline AnyStruct::Builder initAsAnyStruct(uint16_t dataWordCount, uint16_t pointerCount);
214

215
    template <typename T>
216
    inline void setAs(ReaderFor<T> value);
217 218 219 220 221 222 223
    // Valid for ReaderType = T::Reader for T = any generated struct type, List<U>, Text, Data,
    // DynamicStruct, or DynamicList (the dynamic types require `#include <capnp/dynamic.h>`).

    template <typename T>
    inline void setAs(std::initializer_list<ReaderFor<ListElementType<T>>> list);
    // Valid for T = List<?>.

Matthew Maurer's avatar
Matthew Maurer committed
224 225 226
    template <typename T>
    inline void setCanonicalAs(ReaderFor<T> value);

227
    inline void set(Reader value) { builder.copyFrom(value.reader); }
228
    // Set to a copy of another AnyPointer.
229

Matthew Maurer's avatar
Matthew Maurer committed
230 231
    inline void setCanonical(Reader value) { builder.copyFrom(value.reader, true); }

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    template <typename T>
    inline void adopt(Orphan<T>&& orphan);
    // Valid for T = any generated struct type, List<U>, Text, Data, DynamicList, DynamicStruct,
    // or DynamicValue (the dynamic types require `#include <capnp/dynamic.h>`).

    template <typename T>
    inline Orphan<T> disownAs();
    // Valid for T = any generated struct type, List<U>, Text, Data.

    template <typename T>
    inline Orphan<T> disownAs(StructSchema schema);
    // Only valid for T = DynamicStruct.  Requires `#include <capnp/dynamic.h>`.

    template <typename T>
    inline Orphan<T> disownAs(ListSchema schema);
    // Only valid for T = DynamicList.  Requires `#include <capnp/dynamic.h>`.

249 250 251 252
    template <typename T>
    inline Orphan<T> disownAs(InterfaceSchema schema);
    // Only valid for T = DynamicCapability.  Requires `#include <capnp/dynamic.h>`.

253
    inline Orphan<AnyPointer> disown();
254 255 256 257 258
    // Disown without a type.

    inline Reader asReader() const { return Reader(builder.asReader()); }
    inline operator Reader() const { return Reader(builder.asReader()); }

259 260
  private:
    _::PointerBuilder builder;
261
    friend class Orphanage;
262
    friend class CapBuilderContext;
263
    friend struct _::PointerHelpers<AnyPointer>;
264
  };
265

266
#if !CAPNP_LITE
267 268
  class Pipeline {
  public:
269 270
    typedef AnyPointer Pipelines;

271
    inline Pipeline(decltype(nullptr)) {}
272
    inline explicit Pipeline(kj::Own<PipelineHook>&& hook): hook(kj::mv(hook)) {}
273

274
    Pipeline noop();
275 276
    // Just make a copy.

277
    Pipeline getPointerField(uint16_t pointerIndex);
278 279 280
    // Deprecated. In the future, we should use .asAnyStruct.getPointerField.

    inline AnyStruct::Pipeline asAnyStruct();
281

282
    kj::Own<ClientHook> asCap();
283 284
    // Expect that the result is a capability and construct a pipelined version of it now.

285
    inline kj::Own<PipelineHook> releasePipelineHook() { return kj::mv(hook); }
Kenton Varda's avatar
Kenton Varda committed
286 287
    // For use by RPC implementations.

288 289 290
    template <typename T, typename = kj::EnableIf<CAPNP_KIND(FromClient<T>) == Kind::INTERFACE>>
    inline operator T() { return T(asCap()); }

291
  private:
292
    kj::Own<PipelineHook> hook;
293 294
    kj::Array<PipelineOp> ops;

295
    inline Pipeline(kj::Own<PipelineHook>&& hook, kj::Array<PipelineOp>&& ops)
296
        : hook(kj::mv(hook)), ops(kj::mv(ops)) {}
297 298

    friend class LocalClient;
299
    friend class PipelineHook;
300
    friend class AnyStruct::Pipeline;
301
  };
302
#endif  // !CAPNP_LITE
303 304
};

305
template <>
306
class Orphan<AnyPointer> {
307 308 309 310 311 312
  // An orphaned object of unknown type.

public:
  Orphan() = default;
  KJ_DISALLOW_COPY(Orphan);
  Orphan(Orphan&&) = default;
313 314 315
  inline Orphan(_::OrphanBuilder&& builder)
      : builder(kj::mv(builder)) {}

316 317
  Orphan& operator=(Orphan&&) = default;

318 319 320
  template <typename T>
  inline Orphan(Orphan<T>&& other): builder(kj::mv(other.builder)) {}
  template <typename T>
321
  inline Orphan& operator=(Orphan<T>&& other) { builder = kj::mv(other.builder); return *this; }
322 323
  // Cast from typed orphan.

324
  // It's not possible to get an AnyPointer::{Reader,Builder} directly since there is no
325
  // underlying pointer (the pointer would normally live in the parent, but this object is
326
  // orphaned).  It is possible, however, to request typed readers/builders.
327 328

  template <typename T>
329
  inline BuilderFor<T> getAs();
330
  template <typename T>
331
  inline BuilderFor<T> getAs(StructSchema schema);
332
  template <typename T>
333
  inline BuilderFor<T> getAs(ListSchema schema);
334
  template <typename T>
335
  inline typename T::Client getAs(InterfaceSchema schema);
336
  template <typename T>
337
  inline ReaderFor<T> getAsReader() const;
338
  template <typename T>
339 340 341 342 343
  inline ReaderFor<T> getAsReader(StructSchema schema) const;
  template <typename T>
  inline ReaderFor<T> getAsReader(ListSchema schema) const;
  template <typename T>
  inline typename T::Client getAsReader(InterfaceSchema schema) const;
344 345 346 347 348 349 350

  template <typename T>
  inline Orphan<T> releaseAs();
  template <typename T>
  inline Orphan<T> releaseAs(StructSchema schema);
  template <typename T>
  inline Orphan<T> releaseAs(ListSchema schema);
351 352
  template <typename T>
  inline Orphan<T> releaseAs(InterfaceSchema schema);
353 354 355 356 357 358 359 360 361 362 363 364 365
  // Down-cast the orphan to a specific type.

  inline bool operator==(decltype(nullptr)) const { return builder == nullptr; }
  inline bool operator!=(decltype(nullptr)) const { return builder != nullptr; }

private:
  _::OrphanBuilder builder;

  template <typename, Kind>
  friend struct _::PointerHelpers;
  friend class Orphanage;
  template <typename U>
  friend class Orphan;
366
  friend class AnyPointer::Builder;
367 368
};

369 370 371 372 373
template <Kind k> struct AnyTypeFor_;
template <> struct AnyTypeFor_<Kind::STRUCT> { typedef AnyStruct Type; };
template <> struct AnyTypeFor_<Kind::LIST> { typedef AnyList Type; };

template <typename T>
Kenton Varda's avatar
Kenton Varda committed
374
using AnyTypeFor = typename AnyTypeFor_<CAPNP_KIND(T)>::Type;
375 376 377

template <typename T>
inline ReaderFor<AnyTypeFor<FromReader<T>>> toAny(T&& value) {
378
  return ReaderFor<AnyTypeFor<FromReader<T>>>(
379 380 381 382
      _::PointerHelpers<FromReader<T>>::getInternalReader(value));
}
template <typename T>
inline BuilderFor<AnyTypeFor<FromBuilder<T>>> toAny(T&& value) {
383
  return BuilderFor<AnyTypeFor<FromBuilder<T>>>(
384 385 386 387 388
      _::PointerHelpers<FromBuilder<T>>::getInternalBuilder(kj::mv(value)));
}

template <>
struct List<AnyPointer, Kind::OTHER> {
389 390 391
  // Note: This cannot be used for a list of structs, since such lists are not encoded as pointer
  //   lists! Use List<AnyStruct>.

392 393 394 395 396 397
  List() = delete;

  class Reader {
  public:
    typedef List<AnyPointer> Reads;

398
    inline Reader(): reader(ElementSize::POINTER) {}
399 400
    inline explicit Reader(_::ListReader reader): reader(reader) {}

401
    inline uint size() const { return unbound(reader.size() / ELEMENTS); }
402
    inline AnyPointer::Reader operator[](uint index) const {
403
      KJ_IREQUIRE(index < size());
404
      return AnyPointer::Reader(reader.getPointerElement(bounded(index) * ELEMENTS));
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    }

    typedef _::IndexingIterator<const Reader, typename AnyPointer::Reader> Iterator;
    inline Iterator begin() const { return Iterator(this, 0); }
    inline Iterator end() const { return Iterator(this, size()); }

  private:
    _::ListReader reader;
    template <typename U, Kind K>
    friend struct _::PointerHelpers;
    template <typename U, Kind K>
    friend struct List;
    friend class Orphanage;
    template <typename U, Kind K>
    friend struct ToDynamic_;
  };

  class Builder {
  public:
    typedef List<AnyPointer> Builds;

    Builder() = delete;
427
    inline Builder(decltype(nullptr)): builder(ElementSize::POINTER) {}
428 429
    inline explicit Builder(_::ListBuilder builder): builder(builder) {}

430 431
    inline operator Reader() const { return Reader(builder.asReader()); }
    inline Reader asReader() const { return Reader(builder.asReader()); }
432

433
    inline uint size() const { return unbound(builder.size() / ELEMENTS); }
434
    inline AnyPointer::Builder operator[](uint index) {
435
      KJ_IREQUIRE(index < size());
436
      return AnyPointer::Builder(builder.getPointerElement(bounded(index) * ELEMENTS));
437 438 439 440 441 442 443 444
    }

    typedef _::IndexingIterator<Builder, typename AnyPointer::Builder> Iterator;
    inline Iterator begin() { return Iterator(this, 0); }
    inline Iterator end() { return Iterator(this, size()); }

  private:
    _::ListBuilder builder;
445
    template <typename, Kind>
446 447
    friend struct _::PointerHelpers;
    friend class Orphanage;
448
    template <typename, Kind>
449 450 451 452 453 454
    friend struct ToDynamic_;
  };
};

class AnyStruct::Reader {
public:
Kenton Varda's avatar
Kenton Varda committed
455 456
  typedef AnyStruct Reads;

457 458 459
  Reader() = default;
  inline Reader(_::StructReader reader): _reader(reader) {}

Kenton Varda's avatar
Kenton Varda committed
460
  template <typename T, typename = kj::EnableIf<CAPNP_KIND(FromReader<T>) == Kind::STRUCT>>
461 462 463
  inline Reader(T&& value)
      : _reader(_::PointerHelpers<FromReader<T>>::getInternalReader(kj::fwd<T>(value))) {}

464
  kj::ArrayPtr<const byte> getDataSection() {
465 466 467 468 469 470
    return _reader.getDataSectionAsBlob();
  }
  List<AnyPointer>::Reader getPointerSection() {
    return List<AnyPointer>::Reader(_reader.getPointerSectionAsList());
  }

471 472 473 474
  kj::Array<word> canonicalize() {
    return _reader.canonicalize();
  }

475
  Equality equals(AnyStruct::Reader right);
476 477
  bool operator==(AnyStruct::Reader right);
  inline bool operator!=(AnyStruct::Reader right) {
478 479 480
    return !(*this == right);
  }

481
  template <typename T>
482
  ReaderFor<T> as() const {
483
    // T must be a struct type.
484 485
    return typename T::Reader(_reader);
  }
486 487
private:
  _::StructReader _reader;
488 489 490

  template <typename, Kind>
  friend struct _::PointerHelpers;
Kenton Varda's avatar
Kenton Varda committed
491
  friend class Orphanage;
492 493 494 495
};

class AnyStruct::Builder {
public:
Kenton Varda's avatar
Kenton Varda committed
496 497
  typedef AnyStruct Builds;

498 499 500
  inline Builder(decltype(nullptr)) {}
  inline Builder(_::StructBuilder builder): _builder(builder) {}

501
#if !_MSC_VER  // TODO(msvc): MSVC ICEs on this. Try restoring when compiler improves.
Kenton Varda's avatar
Kenton Varda committed
502
  template <typename T, typename = kj::EnableIf<CAPNP_KIND(FromBuilder<T>) == Kind::STRUCT>>
503 504
  inline Builder(T&& value)
      : _builder(_::PointerHelpers<FromBuilder<T>>::getInternalBuilder(kj::fwd<T>(value))) {}
505
#endif
506

507
  inline kj::ArrayPtr<byte> getDataSection() {
508 509 510 511 512 513
    return _builder.getDataSectionAsBlob();
  }
  List<AnyPointer>::Builder getPointerSection() {
    return List<AnyPointer>::Builder(_builder.getPointerSectionAsList());
  }

514
  inline Equality equals(AnyStruct::Reader right) {
515 516
    return asReader().equals(right);
  }
517
  inline bool operator==(AnyStruct::Reader right) {
518 519
    return asReader() == right;
  }
520
  inline bool operator!=(AnyStruct::Reader right) {
521 522 523
    return !(*this == right);
  }

524 525
  inline operator Reader() const { return Reader(_builder.asReader()); }
  inline Reader asReader() const { return Reader(_builder.asReader()); }
526 527 528

  template <typename T>
  BuilderFor<T> as() {
529
    // T must be a struct type.
530 531
    return typename T::Builder(_builder);
  }
532 533 534 535 536 537
private:
  _::StructBuilder _builder;
  friend class Orphanage;
  friend class CapBuilderContext;
};

Kenton Varda's avatar
Kenton Varda committed
538
#if !CAPNP_LITE
539 540
class AnyStruct::Pipeline {
public:
541 542 543 544 545 546 547 548 549 550 551 552
  inline Pipeline(decltype(nullptr)): typeless(nullptr) {}
  inline explicit Pipeline(AnyPointer::Pipeline&& typeless)
      : typeless(kj::mv(typeless)) {}

  inline AnyPointer::Pipeline getPointerField(uint16_t pointerIndex) {
    // Return a new Promise representing a sub-object of the result.  `pointerIndex` is the index
    // of the sub-object within the pointer section of the result (the result must be a struct).
    //
    // TODO(perf):  On GCC 4.8 / Clang 3.3, use rvalue qualifiers to avoid the need for copies.
    //   Also make `ops` into a Vector to optimize this.
    return typeless.getPointerField(pointerIndex);
  }
553 554

private:
555
  AnyPointer::Pipeline typeless;
556
};
Kenton Varda's avatar
Kenton Varda committed
557
#endif  // !CAPNP_LITE
558 559 560 561 562

class List<AnyStruct, Kind::OTHER>::Reader {
public:
  typedef List<AnyStruct> Reads;

563
  inline Reader(): reader(ElementSize::INLINE_COMPOSITE) {}
564 565
  inline explicit Reader(_::ListReader reader): reader(reader) {}

566
  inline uint size() const { return unbound(reader.size() / ELEMENTS); }
567
  inline AnyStruct::Reader operator[](uint index) const {
568
    KJ_IREQUIRE(index < size());
569
    return AnyStruct::Reader(reader.getStructElement(bounded(index) * ELEMENTS));
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  }

  typedef _::IndexingIterator<const Reader, typename AnyStruct::Reader> Iterator;
  inline Iterator begin() const { return Iterator(this, 0); }
  inline Iterator end() const { return Iterator(this, size()); }

private:
  _::ListReader reader;
  template <typename U, Kind K>
  friend struct _::PointerHelpers;
  template <typename U, Kind K>
  friend struct List;
  friend class Orphanage;
  template <typename U, Kind K>
  friend struct ToDynamic_;
};

class List<AnyStruct, Kind::OTHER>::Builder {
public:
  typedef List<AnyStruct> Builds;

  Builder() = delete;
592
  inline Builder(decltype(nullptr)): builder(ElementSize::INLINE_COMPOSITE) {}
593 594
  inline explicit Builder(_::ListBuilder builder): builder(builder) {}

595 596
  inline operator Reader() const { return Reader(builder.asReader()); }
  inline Reader asReader() const { return Reader(builder.asReader()); }
597

598
  inline uint size() const { return unbound(builder.size() / ELEMENTS); }
599
  inline AnyStruct::Builder operator[](uint index) {
600
    KJ_IREQUIRE(index < size());
601
    return AnyStruct::Builder(builder.getStructElement(bounded(index) * ELEMENTS));
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
  }

  typedef _::IndexingIterator<Builder, typename AnyStruct::Builder> Iterator;
  inline Iterator begin() { return Iterator(this, 0); }
  inline Iterator end() { return Iterator(this, size()); }

private:
  _::ListBuilder builder;
  template <typename U, Kind K>
  friend struct _::PointerHelpers;
  friend class Orphanage;
  template <typename U, Kind K>
  friend struct ToDynamic_;
};

class AnyList::Reader {
public:
Kenton Varda's avatar
Kenton Varda committed
619 620
  typedef AnyList Reads;

621
  inline Reader(): _reader(ElementSize::VOID) {}
622 623
  inline Reader(_::ListReader reader): _reader(reader) {}

624
#if !_MSC_VER  // TODO(msvc): MSVC ICEs on this. Try restoring when compiler improves.
Kenton Varda's avatar
Kenton Varda committed
625
  template <typename T, typename = kj::EnableIf<CAPNP_KIND(FromReader<T>) == Kind::LIST>>
626 627
  inline Reader(T&& value)
      : _reader(_::PointerHelpers<FromReader<T>>::getInternalReader(kj::fwd<T>(value))) {}
628
#endif
629

630
  inline ElementSize getElementSize() { return _reader.getElementSize(); }
631
  inline uint size() { return unbound(_reader.size() / ELEMENTS); }
632

633
  inline kj::ArrayPtr<const byte> getRawBytes() { return _reader.asRawBytes(); }
634

635
  Equality equals(AnyList::Reader right);
636 637
  bool operator==(AnyList::Reader right);
  inline bool operator!=(AnyList::Reader right) {
638 639 640
    return !(*this == right);
  }

641
  template <typename T> ReaderFor<T> as() {
642
    // T must be List<U>.
643 644 645 646
    return ReaderFor<T>(_reader);
  }
private:
  _::ListReader _reader;
647 648 649

  template <typename, Kind>
  friend struct _::PointerHelpers;
Kenton Varda's avatar
Kenton Varda committed
650
  friend class Orphanage;
651 652 653 654
};

class AnyList::Builder {
public:
Kenton Varda's avatar
Kenton Varda committed
655 656
  typedef AnyList Builds;

657
  inline Builder(decltype(nullptr)): _builder(ElementSize::VOID) {}
658 659
  inline Builder(_::ListBuilder builder): _builder(builder) {}

660
#if !_MSC_VER  // TODO(msvc): MSVC ICEs on this. Try restoring when compiler improves.
Kenton Varda's avatar
Kenton Varda committed
661
  template <typename T, typename = kj::EnableIf<CAPNP_KIND(FromBuilder<T>) == Kind::LIST>>
662 663
  inline Builder(T&& value)
      : _builder(_::PointerHelpers<FromBuilder<T>>::getInternalBuilder(kj::fwd<T>(value))) {}
664
#endif
665

666
  inline ElementSize getElementSize() { return _builder.getElementSize(); }
667
  inline uint size() { return unbound(_builder.size() / ELEMENTS); }
668

669
  Equality equals(AnyList::Reader right);
670
  inline bool operator==(AnyList::Reader right) {
671 672
    return asReader() == right;
  }
673
  inline bool operator!=(AnyList::Reader right) {
674 675 676
    return !(*this == right);
  }

677
  template <typename T> BuilderFor<T> as() {
678
    // T must be List<U>.
679 680 681 682 683 684 685 686
    return BuilderFor<T>(_builder);
  }

  inline operator Reader() const { return Reader(_builder.asReader()); }
  inline Reader asReader() const { return Reader(_builder.asReader()); }

private:
  _::ListBuilder _builder;
Kenton Varda's avatar
Kenton Varda committed
687 688

  friend class Orphanage;
689 690
};

691 692 693 694 695 696
// =======================================================================================
// Pipeline helpers
//
// These relate to capabilities, but we don't declare them in capability.h because generated code
// for structs needs to know about these, even in files that contain no interfaces.

697 698
#if !CAPNP_LITE

699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
struct PipelineOp {
  // Corresponds to rpc.capnp's PromisedAnswer.Op.

  enum Type {
    NOOP,  // for convenience

    GET_POINTER_FIELD

    // There may be other types in the future...
  };

  Type type;
  union {
    uint16_t pointerIndex;  // for GET_POINTER_FIELD
  };
};

class PipelineHook {
  // Represents a currently-running call, and implements pipelined requests on its result.

public:
720
  virtual kj::Own<PipelineHook> addRef() = 0;
721 722
  // Increment this object's reference count.

723
  virtual kj::Own<ClientHook> getPipelinedCap(kj::ArrayPtr<const PipelineOp> ops) = 0;
724 725
  // Extract a promised Capability from the results.

726
  virtual kj::Own<ClientHook> getPipelinedCap(kj::Array<PipelineOp>&& ops);
727 728 729
  // Version of getPipelinedCap() passing the array by move.  May avoid a copy in some cases.
  // Default implementation just calls the other version.

730 731 732 733 734
  template <typename Pipeline, typename = FromPipeline<Pipeline>>
  static inline kj::Own<PipelineHook> from(Pipeline&& pipeline);

private:
  template <typename T> struct FromImpl;
735 736
};

737 738
#endif  // !CAPNP_LITE

739 740 741
// =======================================================================================
// Inline implementation details

742 743
inline MessageSize AnyPointer::Reader::targetSize() const {
  return reader.targetSize().asPublic();
Kenton Varda's avatar
Kenton Varda committed
744 745
}

746 747
inline PointerType AnyPointer::Reader::getPointerType() const {
  return reader.getPointerType();
748 749 750
}

template <typename T>
751
inline ReaderFor<T> AnyPointer::Reader::getAs() const {
752 753 754
  return _::PointerHelpers<T>::get(reader);
}

755 756
inline MessageSize AnyPointer::Builder::targetSize() const {
  return asReader().targetSize();
Kenton Varda's avatar
Kenton Varda committed
757 758
}

759 760
inline PointerType AnyPointer::Builder::getPointerType() {
  return builder.getPointerType();
761 762
}

763
inline void AnyPointer::Builder::clear() {
764 765 766 767
  return builder.clear();
}

template <typename T>
768
inline BuilderFor<T> AnyPointer::Builder::getAs() {
769 770 771 772
  return _::PointerHelpers<T>::get(builder);
}

template <typename T>
773
inline BuilderFor<T> AnyPointer::Builder::initAs() {
774 775 776 777
  return _::PointerHelpers<T>::init(builder);
}

template <typename T>
778
inline BuilderFor<T> AnyPointer::Builder::initAs(uint elementCount) {
779 780 781
  return _::PointerHelpers<T>::init(builder, elementCount);
}

782 783
inline AnyList::Builder AnyPointer::Builder::initAsAnyList(
    ElementSize elementSize, uint elementCount) {
784
  return AnyList::Builder(builder.initList(elementSize, bounded(elementCount) * ELEMENTS));
785 786
}

787
inline List<AnyStruct>::Builder AnyPointer::Builder::initAsListOfAnyStruct(
788
    uint16_t dataWordCount, uint16_t pointerCount, uint elementCount) {
789 790 791
  return List<AnyStruct>::Builder(builder.initStructList(bounded(elementCount) * ELEMENTS,
      _::StructSize(bounded(dataWordCount) * WORDS,
                    bounded(pointerCount) * POINTERS)));
792
}
793

794 795
inline AnyStruct::Builder AnyPointer::Builder::initAsAnyStruct(
    uint16_t dataWordCount, uint16_t pointerCount) {
796
  return AnyStruct::Builder(builder.initStruct(
797 798
      _::StructSize(bounded(dataWordCount) * WORDS,
                    bounded(pointerCount) * POINTERS)));
799 800
}

801
template <typename T>
802
inline void AnyPointer::Builder::setAs(ReaderFor<T> value) {
803 804 805
  return _::PointerHelpers<T>::set(builder, value);
}

Matthew Maurer's avatar
Matthew Maurer committed
806 807 808 809 810
template <typename T>
inline void AnyPointer::Builder::setCanonicalAs(ReaderFor<T> value) {
  return _::PointerHelpers<T>::setCanonical(builder, value);
}

811
template <typename T>
812
inline void AnyPointer::Builder::setAs(
813 814 815 816 817
    std::initializer_list<ReaderFor<ListElementType<T>>> list) {
  return _::PointerHelpers<T>::set(builder, list);
}

template <typename T>
818
inline void AnyPointer::Builder::adopt(Orphan<T>&& orphan) {
819 820 821 822
  _::PointerHelpers<T>::adopt(builder, kj::mv(orphan));
}

template <typename T>
823
inline Orphan<T> AnyPointer::Builder::disownAs() {
824 825 826
  return _::PointerHelpers<T>::disown(builder);
}

827 828
inline Orphan<AnyPointer> AnyPointer::Builder::disown() {
  return Orphan<AnyPointer>(builder.disown());
829 830
}

831 832
template <> struct ReaderFor_ <AnyPointer, Kind::OTHER> { typedef AnyPointer::Reader Type; };
template <> struct BuilderFor_<AnyPointer, Kind::OTHER> { typedef AnyPointer::Builder Type; };
833 834
template <> struct ReaderFor_ <AnyStruct, Kind::OTHER> { typedef AnyStruct::Reader Type; };
template <> struct BuilderFor_<AnyStruct, Kind::OTHER> { typedef AnyStruct::Builder Type; };
835 836

template <>
837
struct Orphanage::GetInnerReader<AnyPointer, Kind::OTHER> {
838
  static inline _::PointerReader apply(const AnyPointer::Reader& t) {
839 840 841 842
    return t.reader;
  }
};

843
template <>
844
struct Orphanage::GetInnerBuilder<AnyPointer, Kind::OTHER> {
845
  static inline _::PointerBuilder apply(AnyPointer::Builder& t) {
846 847 848 849
    return t.builder;
  }
};

Kenton Varda's avatar
Kenton Varda committed
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
template <>
struct Orphanage::GetInnerReader<AnyStruct, Kind::OTHER> {
  static inline _::StructReader apply(const AnyStruct::Reader& t) {
    return t._reader;
  }
};

template <>
struct Orphanage::GetInnerBuilder<AnyStruct, Kind::OTHER> {
  static inline _::StructBuilder apply(AnyStruct::Builder& t) {
    return t._builder;
  }
};

template <>
struct Orphanage::GetInnerReader<AnyList, Kind::OTHER> {
  static inline _::ListReader apply(const AnyList::Reader& t) {
    return t._reader;
  }
};

template <>
struct Orphanage::GetInnerBuilder<AnyList, Kind::OTHER> {
  static inline _::ListBuilder apply(AnyList::Builder& t) {
    return t._builder;
  }
};

878
template <typename T>
879
inline BuilderFor<T> Orphan<AnyPointer>::getAs() {
880 881 882
  return _::OrphanGetImpl<T>::apply(builder);
}
template <typename T>
883
inline ReaderFor<T> Orphan<AnyPointer>::getAsReader() const {
884 885 886
  return _::OrphanGetImpl<T>::applyReader(builder);
}
template <typename T>
887
inline Orphan<T> Orphan<AnyPointer>::releaseAs() {
888 889 890
  return Orphan<T>(kj::mv(builder));
}

891
// Using AnyPointer as the template type should work...
892 893

template <>
894
inline typename AnyPointer::Reader AnyPointer::Reader::getAs<AnyPointer>() const {
895 896 897
  return *this;
}
template <>
898
inline typename AnyPointer::Builder AnyPointer::Builder::getAs<AnyPointer>() {
899 900 901
  return *this;
}
template <>
902
inline typename AnyPointer::Builder AnyPointer::Builder::initAs<AnyPointer>() {
903 904 905 906
  clear();
  return *this;
}
template <>
907
inline void AnyPointer::Builder::setAs<AnyPointer>(AnyPointer::Reader value) {
908 909 910
  return builder.copyFrom(value.reader);
}
template <>
911
inline void AnyPointer::Builder::adopt<AnyPointer>(Orphan<AnyPointer>&& orphan) {
912 913 914
  builder.adopt(kj::mv(orphan.builder));
}
template <>
915 916
inline Orphan<AnyPointer> AnyPointer::Builder::disownAs<AnyPointer>() {
  return Orphan<AnyPointer>(builder.disown());
917 918
}
template <>
919
inline Orphan<AnyPointer> Orphan<AnyPointer>::releaseAs() {
920 921 922
  return kj::mv(*this);
}

923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
namespace _ {  // private

// Specialize PointerHelpers for AnyPointer.

template <>
struct PointerHelpers<AnyPointer, Kind::OTHER> {
  static inline AnyPointer::Reader get(PointerReader reader,
                                       const void* defaultValue = nullptr,
                                       uint defaultBytes = 0) {
    return AnyPointer::Reader(reader);
  }
  static inline AnyPointer::Builder get(PointerBuilder builder,
                                        const void* defaultValue = nullptr,
                                        uint defaultBytes = 0) {
    return AnyPointer::Builder(builder);
  }
  static inline void set(PointerBuilder builder, AnyPointer::Reader value) {
    AnyPointer::Builder(builder).set(value);
  }
  static inline void adopt(PointerBuilder builder, Orphan<AnyPointer>&& value) {
    builder.adopt(kj::mv(value.builder));
  }
  static inline Orphan<AnyPointer> disown(PointerBuilder builder) {
    return Orphan<AnyPointer>(builder.disown());
  }
948 949 950 951 952 953
  static inline _::PointerReader getInternalReader(const AnyPointer::Reader& reader) {
    return reader.reader;
  }
  static inline _::PointerBuilder getInternalBuilder(AnyPointer::Builder&& builder) {
    return builder.builder;
  }
954 955
};

956 957
template <>
struct PointerHelpers<AnyStruct, Kind::OTHER> {
958
  static inline AnyStruct::Reader get(
959 960 961
      PointerReader reader, const word* defaultValue = nullptr) {
    return AnyStruct::Reader(reader.getStruct(defaultValue));
  }
962
  static inline AnyStruct::Builder get(
963 964 965
      PointerBuilder builder, const word* defaultValue = nullptr) {
    // TODO(someday): Allow specifying the size somehow?
    return AnyStruct::Builder(builder.getStruct(
966
        _::StructSize(ZERO * WORDS, ZERO * POINTERS), defaultValue));
967 968 969 970
  }
  static inline void set(PointerBuilder builder, AnyStruct::Reader value) {
    builder.setStruct(value._reader);
  }
971
  static inline AnyStruct::Builder init(
972
      PointerBuilder builder, uint16_t dataWordCount, uint16_t pointerCount) {
973
    return AnyStruct::Builder(builder.initStruct(
974 975
        StructSize(bounded(dataWordCount) * WORDS,
                   bounded(pointerCount) * POINTERS)));
976
  }
977

978 979 980 981 982 983
  static void adopt(PointerBuilder builder, Orphan<AnyStruct>&& value) {
    builder.adopt(kj::mv(value.builder));
  }
  static Orphan<AnyStruct> disown(PointerBuilder builder) {
    return Orphan<AnyStruct>(builder.disown());
  }
984 985 986 987
};

template <>
struct PointerHelpers<AnyList, Kind::OTHER> {
988
  static inline AnyList::Reader get(
989 990 991
      PointerReader reader, const word* defaultValue = nullptr) {
    return AnyList::Reader(reader.getListAnySize(defaultValue));
  }
992
  static inline AnyList::Builder get(
993 994 995 996 997 998
      PointerBuilder builder, const word* defaultValue = nullptr) {
    return AnyList::Builder(builder.getListAnySize(defaultValue));
  }
  static inline void set(PointerBuilder builder, AnyList::Reader value) {
    builder.setList(value._reader);
  }
999
  static inline AnyList::Builder init(
1000
      PointerBuilder builder, ElementSize elementSize, uint elementCount) {
1001
    return AnyList::Builder(builder.initList(
1002
        elementSize, bounded(elementCount) * ELEMENTS));
1003
  }
1004
  static inline AnyList::Builder init(
1005
      PointerBuilder builder, uint16_t dataWordCount, uint16_t pointerCount, uint elementCount) {
1006
    return AnyList::Builder(builder.initStructList(
1007 1008 1009
        bounded(elementCount) * ELEMENTS,
        StructSize(bounded(dataWordCount) * WORDS,
                   bounded(pointerCount) * POINTERS)));
1010
  }
1011

1012 1013 1014 1015 1016 1017
  static void adopt(PointerBuilder builder, Orphan<AnyList>&& value) {
    builder.adopt(kj::mv(value.builder));
  }
  static Orphan<AnyList> disown(PointerBuilder builder) {
    return Orphan<AnyList>(builder.disown());
  }
1018 1019
};

Kenton Varda's avatar
Kenton Varda committed
1020 1021 1022
template <>
struct OrphanGetImpl<AnyStruct, Kind::OTHER> {
  static inline AnyStruct::Builder apply(_::OrphanBuilder& builder) {
1023
    return AnyStruct::Builder(builder.asStruct(_::StructSize(ZERO * WORDS, ZERO * POINTERS)));
Kenton Varda's avatar
Kenton Varda committed
1024 1025
  }
  static inline AnyStruct::Reader applyReader(const _::OrphanBuilder& builder) {
1026
    return AnyStruct::Reader(builder.asStructReader(_::StructSize(ZERO * WORDS, ZERO * POINTERS)));
Kenton Varda's avatar
Kenton Varda committed
1027 1028
  }
  static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) {
1029
    builder.truncate(size, _::StructSize(ZERO * WORDS, ZERO * POINTERS));
Kenton Varda's avatar
Kenton Varda committed
1030 1031 1032
  }
};

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
template <>
struct OrphanGetImpl<AnyList, Kind::OTHER> {
  static inline AnyList::Builder apply(_::OrphanBuilder& builder) {
    return AnyList::Builder(builder.asListAnySize());
  }
  static inline AnyList::Reader applyReader(const _::OrphanBuilder& builder) {
    return AnyList::Reader(builder.asListReaderAnySize());
  }
  static inline void truncateListOf(_::OrphanBuilder& builder, ElementCount size) {
    builder.truncate(size, ElementSize::POINTER);
  }
};

1046 1047
}  // namespace _ (private)

Kenton Varda's avatar
Kenton Varda committed
1048 1049
#if !CAPNP_LITE

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
template <typename T>
struct PipelineHook::FromImpl {
  static inline kj::Own<PipelineHook> apply(typename T::Pipeline&& pipeline) {
    return from(kj::mv(pipeline._typeless));
  }
};

template <>
struct PipelineHook::FromImpl<AnyPointer> {
  static inline kj::Own<PipelineHook> apply(AnyPointer::Pipeline&& pipeline) {
    return kj::mv(pipeline.hook);
  }
};

template <typename Pipeline, typename T>
inline kj::Own<PipelineHook> PipelineHook::from(Pipeline&& pipeline) {
  return FromImpl<T>::apply(kj::fwd<Pipeline>(pipeline));
}

Kenton Varda's avatar
Kenton Varda committed
1069 1070
#endif  // !CAPNP_LITE

1071 1072
}  // namespace capnp

1073
#endif  // CAPNP_ANY_H_