json.h 21.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// 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.

22
#pragma once
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

#include <capnp/schema.h>
#include <capnp/dynamic.h>
#include <capnp/compat/json.capnp.h>

namespace capnp {

class JsonCodec {
  // Flexible class for encoding Cap'n Proto types as JSON, and decoding JSON back to Cap'n Proto.
  //
  // Typical usage:
  //
  //     JsonCodec json;
  //
  //     // encode
  //     kj::String encoded = json.encode(someStructReader);
  //
  //     // decode
  //     json.decode(encoded, someStructBuilder);
  //
  // Advanced users can do fancy things like override the way certain types or fields are
  // represented in JSON by registering handlers. See the unit test for an example.
  //
  // Notes:
  // - When encoding, all primitive fields are always encoded, even if default-valued. Pointer
  //   fields are only encoded if they are non-null.
  // - 64-bit integers are encoded as strings, since JSON "numbers" are double-precision floating
Kamal Marhubi's avatar
Kamal Marhubi committed
50
  //   points which cannot store a 64-bit integer without losing data.
51 52
  // - NaNs and infinite floating point numbers are not allowed by the JSON spec, and so are encoded
  //   as null. This matches the behavior of `JSON.stringify` in at least Firefox and Chrome.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
  // - Data is encoded as an array of numbers in the range [0,255]. You probably want to register
  //   a handler that does something better, like maybe base64 encoding, but there are a zillion
  //   different ways people do this.
  // - Encoding/decoding capabilities and AnyPointers requires registering a Handler, since there's
  //   no obvious default behavior.
  // - When decoding, unrecognized field names are ignored. Note: This means that JSON is NOT a
  //   good format for receiving input from a human. Consider `capnp eval` or the SchemaParser
  //   library for human input.

public:
  JsonCodec();
  ~JsonCodec() noexcept(false);

  // ---------------------------------------------------------------------------
  // standard API

  void setPrettyPrint(bool enabled);
  // Enable to insert newlines, indentation, and other extra spacing into the output. The default
  // is to use minimal whitespace.

73 74 75 76
  void setMaxNestingDepth(size_t maxNestingDepth);
  // Set maximum nesting depth when decoding JSON to prevent highly nested input from overflowing
  // the call stack. The default is 64.

77
  template <typename T>
78
  kj::String encode(T&& value) const;
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  // Encode any Cap'n Proto value to JSON, including primitives and
  // Dynamic{Enum,Struct,List,Capability}, but not DynamicValue (see below).

  kj::String encode(DynamicValue::Reader value, Type type) const;
  // Encode a DynamicValue to JSON. `type` is needed because `DynamicValue` itself does
  // not distinguish between e.g. int32 and int64, which in JSON are handled differently. Most
  // of the time, though, you can use the single-argument templated version of `encode()` instead.

  void decode(kj::ArrayPtr<const char> input, DynamicStruct::Builder output) const;
  // Decode JSON text directly into a struct builder. This only works for structs since lists
  // need to be allocated with the correct size in advance.
  //
  // (Remember that any Cap'n Proto struct reader type can be implicitly cast to
  // DynamicStruct::Reader.)

  template <typename T>
  Orphan<T> decode(kj::ArrayPtr<const char> input, Orphanage orphanage) const;
  // Decode JSON text to any Cap'n Proto object (pointer value), allocated using the given
  // orphanage. T must be specified explicitly and cannot be dynamic, e.g.:
  //
  //     Orphan<MyType> orphan = json.decode<MyType>(text, orphanage);

  template <typename T>
  ReaderFor<T> decode(kj::ArrayPtr<const char> input) const;
  // Decode JSON text into a primitive or capability value. T must be specified explicitly and
  // cannot be dynamic, e.g.:
  //
  //     uint32_t n = json.decode<uint32_t>(text);

  Orphan<DynamicValue> decode(kj::ArrayPtr<const char> input, Type type, Orphanage orphanage) const;
  Orphan<DynamicList> decode(
      kj::ArrayPtr<const char> input, ListSchema type, Orphanage orphanage) const;
  Orphan<DynamicStruct> decode(
      kj::ArrayPtr<const char> input, StructSchema type, Orphanage orphanage) const;
  DynamicCapability::Client decode(kj::ArrayPtr<const char> input, InterfaceSchema type) const;
  DynamicEnum decode(kj::ArrayPtr<const char> input, EnumSchema type) const;
  // Decode to a dynamic value, specifying the type schema.

  // ---------------------------------------------------------------------------
  // layered API
  //
  // You can separate text <-> JsonValue from JsonValue <-> T. These are particularly useful
  // for calling from Handler implementations.

  kj::String encodeRaw(JsonValue::Reader value) const;
  void decodeRaw(kj::ArrayPtr<const char> input, JsonValue::Builder output) const;
  // Translate JsonValue <-> text.

  template <typename T>
128
  void encode(T&& value, JsonValue::Builder output) const;
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
  void encode(DynamicValue::Reader input, Type type, JsonValue::Builder output) const;
  void decode(JsonValue::Reader input, DynamicStruct::Builder output) const;
  template <typename T>
  Orphan<T> decode(JsonValue::Reader input, Orphanage orphanage) const;
  template <typename T>
  ReaderFor<T> decode(JsonValue::Reader input) const;

  Orphan<DynamicValue> decode(JsonValue::Reader input, Type type, Orphanage orphanage) const;
  Orphan<DynamicList> decode(JsonValue::Reader input, ListSchema type, Orphanage orphanage) const;
  Orphan<DynamicStruct> decode(
      JsonValue::Reader input, StructSchema type, Orphanage orphanage) const;
  DynamicCapability::Client decode(JsonValue::Reader input, InterfaceSchema type) const;
  DynamicEnum decode(JsonValue::Reader input, EnumSchema type) const;

  // ---------------------------------------------------------------------------
  // specializing particular types

  template <typename T, Style s = style<T>()>
  class Handler;
  // Implement this interface to specify a special encoding for a particular type or field.
  //
  // The templates are a bit ugly, but subclasses of this type essentially implement two methods,
  // one to encode values of this type and one to decode values of this type. `encode()` is simple:
  //
  //   void encode(const JsonCodec& codec, ReaderFor<T> input, JsonValue::Builder output) const;
  //
  // `decode()` is a bit trickier. When T is a struct (including DynamicStruct), it is:
  //
  //   void decode(const JsonCodec& codec, JsonValue::Reader input, BuilderFor<T> output) const;
  //
  // However, when T is a primitive, decode() is:
  //
  //   T decode(const JsonCodec& codec, JsonValue::Reader input) const;
  //
  // Or when T is any non-struct object (list, blob), decode() is:
  //
  //   Orphan<T> decode(const JsonCodec& codec, JsonValue::Reader input, Orphanage orphanage) const;
  //
  // Or when T is an interface:
  //
  //   T::Client decode(const JsonCodec& codec, JsonValue::Reader input) const;
  //
  // Additionally, when T is a struct you can *optionally* also implement the orphan-returning form
  // of decode(), but it will only be called when the struct would be allocated as an individual
  // object, not as part of a list. This allows you to return "nullptr" in these cases to say that
  // the pointer value should be null. This does not apply to list elements because struct list
  // elements cannot ever be null (since Cap'n Proto encodes struct lists as a flat list rather
  // than list-of-pointers).

  template <typename T>
  void addTypeHandler(Handler<T>& handler);
  void addTypeHandler(Type type, Handler<DynamicValue>& handler);
  void addTypeHandler(EnumSchema type, Handler<DynamicEnum>& handler);
  void addTypeHandler(StructSchema type, Handler<DynamicStruct>& handler);
  void addTypeHandler(ListSchema type, Handler<DynamicList>& handler);
  void addTypeHandler(InterfaceSchema type, Handler<DynamicCapability>& handler);
  // Arrange that whenever the type T appears in the message, your handler will be used to
  // encode/decode it.
  //
  // Note that if you register a handler for a capability type, it will also apply to subtypes.
  // Thus Handler<Capability> handles all capabilities.

  template <typename T>
  void addFieldHandler(StructSchema::Field field, Handler<T>& handler);
  // Matches only the specific field. T can be a dynamic type. T must match the field's type.

195 196 197 198 199 200 201 202 203 204 205 206 207 208
  // ---------------------------------------------------------------------------
  // Hack to support string literal parameters

  template <size_t size, typename... Params>
  auto decode(const char (&input)[size], Params&&... params) const
      -> decltype(decode(kj::arrayPtr(input, size), kj::fwd<Params>(params)...)) {
    return decode(kj::arrayPtr(input, size - 1), kj::fwd<Params>(params)...);
  }
  template <size_t size, typename... Params>
  auto decodeRaw(const char (&input)[size], Params&&... params) const
      -> decltype(decodeRaw(kj::arrayPtr(input, size), kj::fwd<Params>(params)...)) {
    return decodeRaw(kj::arrayPtr(input, size - 1), kj::fwd<Params>(params)...);
  }

209 210 211 212 213 214 215 216
private:
  class HandlerBase;
  struct Impl;

  kj::Own<Impl> impl;

  void encodeField(StructSchema::Field field, DynamicValue::Reader input,
                   JsonValue::Builder output) const;
217 218
  void decodeArray(List<JsonValue>::Reader input, DynamicList::Builder output) const;
  void decodeObject(List<JsonValue::Field>::Reader input, DynamicStruct::Builder output) const;
219 220 221 222 223 224 225
  void addTypeHandlerImpl(Type type, HandlerBase& handler);
  void addFieldHandlerImpl(StructSchema::Field field, Type type, HandlerBase& handler);
};

// =======================================================================================
// inline implementation details

226 227 228
template <bool isDynamic>
struct EncodeImpl;

229
template <typename T>
230
kj::String JsonCodec::encode(T&& value) const {
231
  Type type = Type::from(value);
232
  typedef FromAny<kj::Decay<T>> Base;
233
  return encode(DynamicValue::Reader(ReaderFor<Base>(kj::fwd<T>(value))), type);
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
}

template <typename T>
inline Orphan<T> JsonCodec::decode(kj::ArrayPtr<const char> input, Orphanage orphanage) const {
  return decode(input, Type::from<T>(), orphanage).template releaseAs<T>();
}

template <typename T>
inline ReaderFor<T> JsonCodec::decode(kj::ArrayPtr<const char> input) const {
  static_assert(style<T>() == Style::PRIMITIVE || style<T>() == Style::CAPABILITY,
                "must specify an orphanage to decode an object type");
  return decode(input, Type::from<T>(), Orphanage()).getReader().template as<T>();
}

inline Orphan<DynamicList> JsonCodec::decode(
    kj::ArrayPtr<const char> input, ListSchema type, Orphanage orphanage) const {
  return decode(input, Type(type), orphanage).releaseAs<DynamicList>();
}
inline Orphan<DynamicStruct> JsonCodec::decode(
    kj::ArrayPtr<const char> input, StructSchema type, Orphanage orphanage) const {
  return decode(input, Type(type), orphanage).releaseAs<DynamicStruct>();
}
inline DynamicCapability::Client JsonCodec::decode(
    kj::ArrayPtr<const char> input, InterfaceSchema type) const {
  return decode(input, Type(type), Orphanage()).getReader().as<DynamicCapability>();
}
inline DynamicEnum JsonCodec::decode(kj::ArrayPtr<const char> input, EnumSchema type) const {
  return decode(input, Type(type), Orphanage()).getReader().as<DynamicEnum>();
}

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

template <typename T>
267
void JsonCodec::encode(T&& value, JsonValue::Builder output) const {
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
  typedef FromAny<kj::Decay<T>> Base;
  encode(DynamicValue::Reader(ReaderFor<Base>(kj::fwd<T>(value))), Type::from<Base>(), output);
}

template <typename T>
inline Orphan<T> JsonCodec::decode(JsonValue::Reader input, Orphanage orphanage) const {
  return decode(input, Type::from<T>(), orphanage).template releaseAs<T>();
}

template <typename T>
inline ReaderFor<T> JsonCodec::decode(JsonValue::Reader input) const {
  static_assert(style<T>() == Style::PRIMITIVE || style<T>() == Style::CAPABILITY,
                "must specify an orphanage to decode an object type");
  return decode(input, Type::from<T>(), Orphanage()).getReader().template as<T>();
}

inline Orphan<DynamicList> JsonCodec::decode(
    JsonValue::Reader input, ListSchema type, Orphanage orphanage) const {
  return decode(input, Type(type), orphanage).releaseAs<DynamicList>();
}
inline Orphan<DynamicStruct> JsonCodec::decode(
    JsonValue::Reader input, StructSchema type, Orphanage orphanage) const {
  return decode(input, Type(type), orphanage).releaseAs<DynamicStruct>();
}
inline DynamicCapability::Client JsonCodec::decode(
    JsonValue::Reader input, InterfaceSchema type) const {
  return decode(input, Type(type), Orphanage()).getReader().as<DynamicCapability>();
}
inline DynamicEnum JsonCodec::decode(JsonValue::Reader input, EnumSchema type) const {
  return decode(input, Type(type), Orphanage()).getReader().as<DynamicEnum>();
}

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

class JsonCodec::HandlerBase {
  // Internal helper; ignore.
public:
  virtual void encodeBase(const JsonCodec& codec, DynamicValue::Reader input,
                          JsonValue::Builder output) const = 0;
  virtual Orphan<DynamicValue> decodeBase(const JsonCodec& codec, JsonValue::Reader input,
308
                                          Type type, Orphanage orphanage) const;
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
  virtual void decodeStructBase(const JsonCodec& codec, JsonValue::Reader input,
                                DynamicStruct::Builder output) const;
};

template <typename T>
class JsonCodec::Handler<T, Style::POINTER>: private JsonCodec::HandlerBase {
public:
  virtual void encode(const JsonCodec& codec, ReaderFor<T> input,
                      JsonValue::Builder output) const = 0;
  virtual Orphan<T> decode(const JsonCodec& codec, JsonValue::Reader input,
                           Orphanage orphanage) const = 0;

private:
  void encodeBase(const JsonCodec& codec, DynamicValue::Reader input,
                  JsonValue::Builder output) const override final {
    encode(codec, input.as<T>(), output);
  }
  Orphan<DynamicValue> decodeBase(const JsonCodec& codec, JsonValue::Reader input,
327
                                  Type type, Orphanage orphanage) const override final {
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    return decode(codec, input, orphanage);
  }
  friend class JsonCodec;
};

template <typename T>
class JsonCodec::Handler<T, Style::STRUCT>: private JsonCodec::HandlerBase {
public:
  virtual void encode(const JsonCodec& codec, ReaderFor<T> input,
                      JsonValue::Builder output) const = 0;
  virtual void decode(const JsonCodec& codec, JsonValue::Reader input,
                      BuilderFor<T> output) const = 0;
  virtual Orphan<T> decode(const JsonCodec& codec, JsonValue::Reader input,
                           Orphanage orphanage) const {
    // If subclass does not override, fall back to regular version.
    auto result = orphanage.newOrphan<T>();
    decode(codec, input, result.get());
    return result;
  }

private:
  void encodeBase(const JsonCodec& codec, DynamicValue::Reader input,
                  JsonValue::Builder output) const override final {
    encode(codec, input.as<T>(), output);
  }
  Orphan<DynamicValue> decodeBase(const JsonCodec& codec, JsonValue::Reader input,
354
                                  Type type, Orphanage orphanage) const override final {
355 356 357 358
    return decode(codec, input, orphanage);
  }
  void decodeStructBase(const JsonCodec& codec, JsonValue::Reader input,
                        DynamicStruct::Builder output) const override final {
359
    decode(codec, input, output.as<T>());
360 361 362 363
  }
  friend class JsonCodec;
};

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
template <>
class JsonCodec::Handler<DynamicStruct>: private JsonCodec::HandlerBase {
  // Almost identical to Style::STRUCT except that we pass the struct type to decode().

public:
  virtual void encode(const JsonCodec& codec, DynamicStruct::Reader input,
                      JsonValue::Builder output) const = 0;
  virtual void decode(const JsonCodec& codec, JsonValue::Reader input,
                      DynamicStruct::Builder output) const = 0;
  virtual Orphan<DynamicStruct> decode(const JsonCodec& codec, JsonValue::Reader input,
                                       StructSchema type, Orphanage orphanage) const {
    // If subclass does not override, fall back to regular version.
    auto result = orphanage.newOrphan(type);
    decode(codec, input, result.get());
    return result;
  }

private:
  void encodeBase(const JsonCodec& codec, DynamicValue::Reader input,
                  JsonValue::Builder output) const override final {
    encode(codec, input.as<DynamicStruct>(), output);
  }
  Orphan<DynamicValue> decodeBase(const JsonCodec& codec, JsonValue::Reader input,
                                  Type type, Orphanage orphanage) const override final {
    return decode(codec, input, type.asStruct(), orphanage);
  }
  void decodeStructBase(const JsonCodec& codec, JsonValue::Reader input,
                        DynamicStruct::Builder output) const override final {
    decode(codec, input, output.as<DynamicStruct>());
  }
  friend class JsonCodec;
};

397 398 399 400 401 402 403 404 405 406 407 408
template <typename T>
class JsonCodec::Handler<T, Style::PRIMITIVE>: private JsonCodec::HandlerBase {
public:
  virtual void encode(const JsonCodec& codec, T input, JsonValue::Builder output) const = 0;
  virtual T decode(const JsonCodec& codec, JsonValue::Reader input) const = 0;

private:
  void encodeBase(const JsonCodec& codec, DynamicValue::Reader input,
                  JsonValue::Builder output) const override final {
    encode(codec, input.as<T>(), output);
  }
  Orphan<DynamicValue> decodeBase(const JsonCodec& codec, JsonValue::Reader input,
409
                                  Type type, Orphanage orphanage) const override final {
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    return decode(codec, input);
  }
  friend class JsonCodec;
};

template <typename T>
class JsonCodec::Handler<T, Style::CAPABILITY>: private JsonCodec::HandlerBase {
public:
  virtual void encode(const JsonCodec& codec, typename T::Client input,
                      JsonValue::Builder output) const = 0;
  virtual typename T::Client decode(const JsonCodec& codec, JsonValue::Reader input) const = 0;

private:
  void encodeBase(const JsonCodec& codec, DynamicValue::Reader input,
                  JsonValue::Builder output) const override final {
    encode(codec, input.as<T>(), output);
  }
  Orphan<DynamicValue> decodeBase(const JsonCodec& codec, JsonValue::Reader input,
428
                                  Type type, Orphanage orphanage) const override final {
429
    return orphanage.newOrphanCopy(decode(codec, input));
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
  }
  friend class JsonCodec;
};

template <typename T>
inline void JsonCodec::addTypeHandler(Handler<T>& handler) {
  addTypeHandlerImpl(Type::from<T>(), handler);
}
inline void JsonCodec::addTypeHandler(Type type, Handler<DynamicValue>& handler) {
  addTypeHandlerImpl(type, handler);
}
inline void JsonCodec::addTypeHandler(EnumSchema type, Handler<DynamicEnum>& handler) {
  addTypeHandlerImpl(type, handler);
}
inline void JsonCodec::addTypeHandler(StructSchema type, Handler<DynamicStruct>& handler) {
  addTypeHandlerImpl(type, handler);
}
inline void JsonCodec::addTypeHandler(ListSchema type, Handler<DynamicList>& handler) {
  addTypeHandlerImpl(type, handler);
}
inline void JsonCodec::addTypeHandler(InterfaceSchema type, Handler<DynamicCapability>& handler) {
  addTypeHandlerImpl(type, handler);
}

template <typename T>
inline void JsonCodec::addFieldHandler(StructSchema::Field field, Handler<T>& handler) {
  addFieldHandlerImpl(field, Type::from<T>(), handler);
}

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
template <> void JsonCodec::addTypeHandler(Handler<DynamicValue>& handler)
    KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; "
                   "try specifying a specific type schema as the first parameter");
template <> void JsonCodec::addTypeHandler(Handler<DynamicEnum>& handler)
    KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; "
                   "try specifying a specific type schema as the first parameter");
template <> void JsonCodec::addTypeHandler(Handler<DynamicStruct>& handler)
    KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; "
                   "try specifying a specific type schema as the first parameter");
template <> void JsonCodec::addTypeHandler(Handler<DynamicList>& handler)
    KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; "
                   "try specifying a specific type schema as the first parameter");
template <> void JsonCodec::addTypeHandler(Handler<DynamicCapability>& handler)
    KJ_UNAVAILABLE("JSON handlers for type sets (e.g. all structs, all lists) not implemented; "
                   "try specifying a specific type schema as the first parameter");
// TODO(someday): Implement support for registering handlers that cover thinsg like "all structs"
//   or "all lists". Currently you can only target a specific struct or list type.

477
} // namespace capnp