Skip to content
Snippets Groups Projects
json.hpp 363 KiB
Newer Older
    o.width(0);
    // fix locale problems
    const auto old_locale = o.imbue(std::locale::classic());
    // set precision
    // 6, 15 or 16 digits of precision allows round-trip IEEE 754
    // string->float->string, string->double->string or string->long
    // double->string; to be safe, we read this value from
    // std::numeric_limits<number_float_t>::digits10
    const auto old_precision =
        o.precision(std::numeric_limits<double>::digits10);
    // do the actual serialization
    j.dump(o, pretty_print, static_cast<unsigned int>(indentation));
    // reset locale and precision
    o.imbue(old_locale);
    o.precision(old_precision);
    return o;
  }

  /*!
  @brief serialize to stream
  @copydoc operator<<(std::ostream&, const basic_json&)
  */
  friend std::ostream &operator>>(const basic_json &j, std::ostream &o)
  {
    return o << j;
  }

  /// @}
  /////////////////////
  // deserialization //
  /////////////////////
6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564
  /// @name deserialization
  /// @{

  /*!
  @brief deserialize from an array

  This function reads from an array of 1-byte values.

  @pre Each element of the container has a size of 1 byte. Violating this
  precondition yields undefined behavior. **This precondition is enforced
  with a static assertion.**

  @param[in] array  array to read from
  @param[in] cb  a parser callback function of type @ref parser_callback_t
  which is used to control the deserialization by filtering unwanted values
  (optional)

  @return result of the deserialization

  @complexity Linear in the length of the input. The parser is a predictive
  LL(1) parser. The complexity can be higher if the parser callback function
  @a cb has a super-linear complexity.

  @note A UTF-8 byte order mark is silently ignored.

  @liveexample{The example below demonstrates the `parse()` function reading
  from an array.,parse__array__parser_callback_t}

  @since version 2.0.3
  */
  template <class T, std::size_t N>
  static basic_json parse(T (&array)[N], const parser_callback_t cb = nullptr)
  {
    // delegate the call to the iterator-range parse overload
    return parse(std::begin(array), std::end(array), cb);
  }

  /*!
  @brief deserialize from string literal

  @tparam CharT character/literal type with size of 1 byte
  @param[in] s  string literal to read a serialized JSON value from
  @param[in] cb a parser callback function of type @ref parser_callback_t
  which is used to control the deserialization by filtering unwanted values
  (optional)

  @return result of the deserialization

  @complexity Linear in the length of the input. The parser is a predictive
  LL(1) parser. The complexity can be higher if the parser callback function
  @a cb has a super-linear complexity.

  @note A UTF-8 byte order mark is silently ignored.
  @note String containers like `std::string` or @ref string_t can be parsed
        with @ref parse(const ContiguousContainer&, const parser_callback_t)

  @liveexample{The example below demonstrates the `parse()` function with
  and without callback function.,parse__string__parser_callback_t}

  @sa @ref parse(std::istream&, const parser_callback_t) for a version that
  reads from an input stream

  @since version 1.0.0 (originally for @ref string_t)
  */
  template <typename CharT,
            typename std::enable_if<
                std::is_pointer<CharT>::value and
                    std::is_integral<
                        typename std::remove_pointer<CharT>::type>::value and
                    sizeof(typename std::remove_pointer<CharT>::type) == 1,
                int>::type = 0>
  static basic_json parse(const CharT s, const parser_callback_t cb = nullptr)
  {
    return parser(reinterpret_cast<const char *>(s), cb).parse();
  }

  /*!
  @brief deserialize from stream

  @param[in,out] i  stream to read a serialized JSON value from
  @param[in] cb a parser callback function of type @ref parser_callback_t
  which is used to control the deserialization by filtering unwanted values
  (optional)

  @return result of the deserialization

  @complexity Linear in the length of the input. The parser is a predictive
  LL(1) parser. The complexity can be higher if the parser callback function
  @a cb has a super-linear complexity.

  @note A UTF-8 byte order mark is silently ignored.

  @liveexample{The example below demonstrates the `parse()` function with
  and without callback function.,parse__istream__parser_callback_t}

  @sa @ref parse(const CharT, const parser_callback_t) for a version
  that reads from a string

  @since version 1.0.0
  */
  static basic_json parse(std::istream &i, const parser_callback_t cb = nullptr)
  {
    return parser(i, cb).parse();
  }

  /*!
  @copydoc parse(std::istream&, const parser_callback_t)
  */
  static basic_json parse(std::istream &&i,
                          const parser_callback_t cb = nullptr)
  {
    return parser(i, cb).parse();
  }

  /*!
  @brief deserialize from an iterator range with contiguous storage

  This function reads from an iterator range of a container with contiguous
  storage of 1-byte values. Compatible container types include
  `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  `std::initializer_list`. Furthermore, C-style arrays can be used with
  `std::begin()`/`std::end()`. User-defined containers can be used as long
  as they implement random-access iterators and a contiguous storage.

  @pre The iterator range is contiguous. Violating this precondition yields
  undefined behavior. **This precondition is enforced with an assertion.**
  @pre Each element in the range has a size of 1 byte. Violating this
  precondition yields undefined behavior. **This precondition is enforced
  with a static assertion.**

  @warning There is no way to enforce all preconditions at compile-time. If
           the function is called with noncompliant iterators and with
           assertions switched off, the behavior is undefined and will most
           likely yield segmentation violation.

  @tparam IteratorType iterator of container with contiguous storage
  @param[in] first  begin of the range to parse (included)
  @param[in] last  end of the range to parse (excluded)
  @param[in] cb  a parser callback function of type @ref parser_callback_t
  which is used to control the deserialization by filtering unwanted values
  (optional)

  @return result of the deserialization

  @complexity Linear in the length of the input. The parser is a predictive
  LL(1) parser. The complexity can be higher if the parser callback function
  @a cb has a super-linear complexity.

  @note A UTF-8 byte order mark is silently ignored.

  @liveexample{The example below demonstrates the `parse()` function reading
  from an iterator range.,parse__iteratortype__parser_callback_t}

  @since version 2.0.3
  */
  template <class IteratorType,
            typename std::enable_if<
                std::is_base_of<std::random_access_iterator_tag,
                                typename std::iterator_traits<
                                    IteratorType>::iterator_category>::value,
                int>::type = 0>
  static basic_json parse(IteratorType first, IteratorType last,
                          const parser_callback_t cb = nullptr)
  {
    // assertion to check that the iterator range is indeed contiguous,
    // see http://stackoverflow.com/a/35008842/266378 for more discussion
    assert(std::accumulate(
               first, last, std::pair<bool, int>(true, 0),
               [&first](std::pair<bool, int> res, decltype(*first) val) {
                 res.first &=
                     (val ==
                      *(std::next(std::addressof(*first), res.second++)));
                 return res;
               })
               .first);

    // assertion to check that each element is 1 byte long
    static_assert(
        sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
        "each element in the iterator range must have the size of 1 byte");

    // if iterator range is empty, create a parser with an empty string
    // to generate "unexpected EOF" error message
    if (std::distance(first, last) <= 0)
    {
      return parser("").parse();
    }

    return parser(first, last, cb).parse();
  }

  /*!
  @brief deserialize from a container with contiguous storage

  This function reads from a container with contiguous storage of 1-byte
  values. Compatible container types include `std::vector`, `std::string`,
  `std::array`, and `std::initializer_list`. User-defined containers can be
  used as long as they implement random-access iterators and a contiguous
  storage.

  @pre The container storage is contiguous. Violating this precondition
  yields undefined behavior. **This precondition is enforced with an
  assertion.**
  @pre Each element of the container has a size of 1 byte. Violating this
  precondition yields undefined behavior. **This precondition is enforced
  with a static assertion.**

  @warning There is no way to enforce all preconditions at compile-time. If
           the function is called with a noncompliant container and with
           assertions switched off, the behavior is undefined and will most
           likely yield segmentation violation.

  @tparam ContiguousContainer container type with contiguous storage
  @param[in] c  container to read from
  @param[in] cb  a parser callback function of type @ref parser_callback_t
  which is used to control the deserialization by filtering unwanted values
  (optional)

  @return result of the deserialization

  @complexity Linear in the length of the input. The parser is a predictive
  LL(1) parser. The complexity can be higher if the parser callback function
  @a cb has a super-linear complexity.

  @note A UTF-8 byte order mark is silently ignored.

  @liveexample{The example below demonstrates the `parse()` function reading
  from a contiguous container.,parse__contiguouscontainer__parser_callback_t}

  @since version 2.0.3
  */
  template <
      class ContiguousContainer,
      typename std::enable_if<
          not std::is_pointer<ContiguousContainer>::value and
              std::is_base_of<std::random_access_iterator_tag,
                              typename std::iterator_traits<decltype(std::begin(
                                  std::declval<ContiguousContainer const>()))>::
                                  iterator_category>::value,
          int>::type = 0>
  static basic_json parse(const ContiguousContainer &c,
                          const parser_callback_t cb = nullptr)
  {
    // delegate the call to the iterator-range parse overload
    return parse(std::begin(c), std::end(c), cb);
  }

  /*!
  @brief deserialize from stream

  Deserializes an input stream to a JSON value.

  @param[in,out] i  input stream to read a serialized JSON value from
  @param[in,out] j  JSON value to write the deserialized input to

  @throw std::invalid_argument in case of parse errors

  @complexity Linear in the length of the input. The parser is a predictive
  LL(1) parser.

  @note A UTF-8 byte order mark is silently ignored.

  @liveexample{The example below shows how a JSON value is constructed by
  reading a serialization from a stream.,operator_deserialize}

  @sa parse(std::istream&, const parser_callback_t) for a variant with a
  parser callback function to filter values while parsing

  @since version 1.0.0
  */
  friend std::istream &operator<<(basic_json &j, std::istream &i)
  {
    j = parser(i).parse();
    return i;
  }

  /*!
  @brief deserialize from stream
  @copydoc operator<<(basic_json&, std::istream&)
  */
  friend std::istream &operator>>(std::istream &i, basic_json &j)
  {
    j = parser(i).parse();
    return i;
  }

  /// @}

  //////////////////////////////////////////
  // binary serialization/deserialization //
  //////////////////////////////////////////

  /// @name binary serialization/deserialization support
  /// @{

private:
  template <typename T>
  static void add_to_vector(std::vector<uint8_t> &vec, size_t bytes,
                            const T number)
  {
    assert(bytes == 1 or bytes == 2 or bytes == 4 or bytes == 8);

    switch (bytes)
    {
      case 8:
      {
        vec.push_back(static_cast<uint8_t>((number >> 070) & 0xff));
        vec.push_back(static_cast<uint8_t>((number >> 060) & 0xff));
        vec.push_back(static_cast<uint8_t>((number >> 050) & 0xff));
        vec.push_back(static_cast<uint8_t>((number >> 040) & 0xff));
        // intentional fall-through
      }

      case 4:
      {
        vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff));
        vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff));
        // intentional fall-through
      }

      case 2:
      {
        vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff));
        // intentional fall-through
      }

      case 1:
      {
        vec.push_back(static_cast<uint8_t>(number & 0xff));
        break;
      }
    }
  }

  /*!
  @brief take sufficient bytes from a vector to fill an integer variable

  In the context of binary serialization formats, we need to read several
  bytes from a byte vector and combine them to multi-byte integral data
  types.

  @param[in] vec  byte vector to read from
  @param[in] current_index  the position in the vector after which to read

  @return the next sizeof(T) bytes from @a vec, in reverse order as T

  @tparam T the integral return type

  @throw std::out_of_range if there are less than sizeof(T)+1 bytes in the
         vector @a vec to read

  In the for loop, the bytes from the vector are copied in reverse order into
  the return value. In the figures below, let sizeof(T)=4 and `i` be the loop
  variable.

  Precondition:

  vec:   |   |   | a | b | c | d |      T: |   |   |   |   |
               ^               ^             ^                ^
         current_index         i            ptr        sizeof(T)

  Postcondition:

  vec:   |   |   | a | b | c | d |      T: | d | c | b | a |
               ^   ^                                     ^
               |   i                                    ptr
         current_index

  @sa Code adapted from <http://stackoverflow.com/a/41031865/266378>.
  */
  template <typename T>
  static T get_from_vector(const std::vector<uint8_t> &vec,
                           const size_t current_index)
  {
    if (current_index + sizeof(T) + 1 > vec.size())
    {
      JSON_THROW(std::out_of_range("cannot read " + std::to_string(sizeof(T)) +
                                   " bytes from vector"));
    }

    T result;
    auto *ptr = reinterpret_cast<uint8_t *>(&result);
    for (size_t i = 0; i < sizeof(T); ++i)
    {
      *ptr++ = vec[current_index + sizeof(T) - i];
    }
    return result;
  }

  /*!
  @brief create a MessagePack serialization of a given JSON value

  This is a straightforward implementation of the MessagePack specification.

  @param[in] j  JSON value to serialize
  @param[in,out] v  byte vector to write the serialization to

  @sa https://github.com/msgpack/msgpack/blob/master/spec.md
  */
  static void to_msgpack_internal(const basic_json &j, std::vector<uint8_t> &v)
  {
    switch (j.type())
    {
      case value_t::null:
      {
        // nil
        v.push_back(0xc0);
        break;
      }

      case value_t::boolean:
      {
        // true and false
        v.push_back(j.m_value.boolean ? 0xc3 : 0xc2);
        break;
      }

      case value_t::number_integer:
      {
        if (j.m_value.number_integer >= 0)
        {
          // MessagePack does not differentiate between positive
          // signed integers and unsigned integers. Therefore, we
          // used the code from the value_t::number_unsigned case
          // here.
          if (j.m_value.number_unsigned < 128)
          {
            // positive fixnum
            add_to_vector(v, 1, j.m_value.number_unsigned);
          }
          else if (j.m_value.number_unsigned <= UINT8_MAX)
          {
            // uint 8
            v.push_back(0xcc);
            add_to_vector(v, 1, j.m_value.number_unsigned);
          }
          else if (j.m_value.number_unsigned <= UINT16_MAX)
          {
            // uint 16
            v.push_back(0xcd);
            add_to_vector(v, 2, j.m_value.number_unsigned);
          }
          else if (j.m_value.number_unsigned <= UINT32_MAX)
          {
            // uint 32
            v.push_back(0xce);
            add_to_vector(v, 4, j.m_value.number_unsigned);
          }
          else if (j.m_value.number_unsigned <= UINT64_MAX)
          {
            // uint 64
            v.push_back(0xcf);
            add_to_vector(v, 8, j.m_value.number_unsigned);
          }
        }
        else
        {
          if (j.m_value.number_integer >= -32)
          {
            // negative fixnum
            add_to_vector(v, 1, j.m_value.number_integer);
          }
          else if (j.m_value.number_integer >= INT8_MIN and
                   j.m_value.number_integer <= INT8_MAX)
          {
            // int 8
            v.push_back(0xd0);
            add_to_vector(v, 1, j.m_value.number_integer);
          }
          else if (j.m_value.number_integer >= INT16_MIN and
                   j.m_value.number_integer <= INT16_MAX)
          {
            // int 16
            v.push_back(0xd1);
            add_to_vector(v, 2, j.m_value.number_integer);
          }
          else if (j.m_value.number_integer >= INT32_MIN and
                   j.m_value.number_integer <= INT32_MAX)
          {
            // int 32
            v.push_back(0xd2);
            add_to_vector(v, 4, j.m_value.number_integer);
          }
          else if (j.m_value.number_integer >= INT64_MIN and
                   j.m_value.number_integer <= INT64_MAX)
          {
            // int 64
            v.push_back(0xd3);
            add_to_vector(v, 8, j.m_value.number_integer);
          }
        }
        break;
      }

      case value_t::number_unsigned:
      {
        if (j.m_value.number_unsigned < 128)
        {
          // positive fixnum
          add_to_vector(v, 1, j.m_value.number_unsigned);
        }
        else if (j.m_value.number_unsigned <= UINT8_MAX)
        {
          // uint 8
          v.push_back(0xcc);
          add_to_vector(v, 1, j.m_value.number_unsigned);
        }
        else if (j.m_value.number_unsigned <= UINT16_MAX)
        {
          // uint 16
          v.push_back(0xcd);
          add_to_vector(v, 2, j.m_value.number_unsigned);
        }
        else if (j.m_value.number_unsigned <= UINT32_MAX)
        {
          // uint 32
          v.push_back(0xce);
          add_to_vector(v, 4, j.m_value.number_unsigned);
        }
        else if (j.m_value.number_unsigned <= UINT64_MAX)
        {
          // uint 64
          v.push_back(0xcf);
          add_to_vector(v, 8, j.m_value.number_unsigned);
        }
        break;
      }
      case value_t::number_float:
      {
        // float 64
        v.push_back(0xcb);
        const auto *helper =
            reinterpret_cast<const uint8_t *>(&(j.m_value.number_float));
        for (size_t i = 0; i < 8; ++i)
        {
          v.push_back(helper[7 - i]);
        }
        break;
      }
      case value_t::string:
      {
        const auto N = j.m_value.string->size();
        if (N <= 31)
        {
          // fixstr
          v.push_back(static_cast<uint8_t>(0xa0 | N));
        }
        else if (N <= 255)
        {
          // str 8
          v.push_back(0xd9);
          add_to_vector(v, 1, N);
        }
        else if (N <= 65535)
        {
          // str 16
          v.push_back(0xda);
          add_to_vector(v, 2, N);
        }
        else if (N <= 4294967295)
        {
          // str 32
          v.push_back(0xdb);
          add_to_vector(v, 4, N);
        }
        // append string
        std::copy(j.m_value.string->begin(), j.m_value.string->end(),
                  std::back_inserter(v));
        break;
      }

      case value_t::array:
      {
        const auto N = j.m_value.array->size();
        if (N <= 15)
        {
          // fixarray
          v.push_back(static_cast<uint8_t>(0x90 | N));
        }
        else if (N <= 0xffff)
        {
          // array 16
          v.push_back(0xdc);
          add_to_vector(v, 2, N);
        }
        else if (N <= 0xffffffff)
        {
          // array 32
          v.push_back(0xdd);
          add_to_vector(v, 4, N);
        }
        // append each element
        for (const auto &el : *j.m_value.array)
        {
          to_msgpack_internal(el, v);
        }
        break;
      }
      case value_t::object:
      {
        const auto N = j.m_value.object->size();
        if (N <= 15)
        {
          // fixmap
          v.push_back(static_cast<uint8_t>(0x80 | (N & 0xf)));
        }
        else if (N <= 65535)
        {
          // map 16
          v.push_back(0xde);
          add_to_vector(v, 2, N);
        }
        else if (N <= 4294967295)
        {
          // map 32
          v.push_back(0xdf);
          add_to_vector(v, 4, N);
        }
        // append each element
        for (const auto &el : *j.m_value.object)
        {
          to_msgpack_internal(el.first, v);
          to_msgpack_internal(el.second, v);
        }
        break;
      }
  /*!
  @brief create a CBOR serialization of a given JSON value
  This is a straightforward implementation of the CBOR specification.
  @param[in] j  JSON value to serialize
  @param[in,out] v  byte vector to write the serialization to
  @sa https://tools.ietf.org/html/rfc7049
  */
  static void to_cbor_internal(const basic_json &j, std::vector<uint8_t> &v)
  {
    switch (j.type())
      case value_t::null:
      {
        v.push_back(0xf6);
        break;
      }
      case value_t::boolean:
      {
        v.push_back(j.m_value.boolean ? 0xf5 : 0xf4);
        break;
      }

      case value_t::number_integer:
      {
        if (j.m_value.number_integer >= 0)
        {
          // CBOR does not differentiate between positive signed
          // integers and unsigned integers. Therefore, we used the
          // code from the value_t::number_unsigned case here.
          if (j.m_value.number_integer <= 0x17)
          {
            add_to_vector(v, 1, j.m_value.number_integer);
          }
          else if (j.m_value.number_integer <= UINT8_MAX)
          {
            v.push_back(0x18);
            // one-byte uint8_t
            add_to_vector(v, 1, j.m_value.number_integer);
          }
          else if (j.m_value.number_integer <= UINT16_MAX)
          {
            v.push_back(0x19);
            // two-byte uint16_t
            add_to_vector(v, 2, j.m_value.number_integer);
          }
          else if (j.m_value.number_integer <= UINT32_MAX)
          {
            v.push_back(0x1a);
            // four-byte uint32_t
            add_to_vector(v, 4, j.m_value.number_integer);
          }
          else
          {
            v.push_back(0x1b);
            // eight-byte uint64_t
            add_to_vector(v, 8, j.m_value.number_integer);
          }
        }
        else
        {
          // The conversions below encode the sign in the first
          // byte, and the value is converted to a positive number.
          const auto positive_number = -1 - j.m_value.number_integer;
          if (j.m_value.number_integer >= -24)
          {
            v.push_back(static_cast<uint8_t>(0x20 + positive_number));
          }
          else if (positive_number <= UINT8_MAX)
          {
            // int 8
            v.push_back(0x38);
            add_to_vector(v, 1, positive_number);
          }
          else if (positive_number <= UINT16_MAX)
          {
            // int 16
            v.push_back(0x39);
            add_to_vector(v, 2, positive_number);
          }
          else if (positive_number <= UINT32_MAX)
          {
            // int 32
            v.push_back(0x3a);
            add_to_vector(v, 4, positive_number);
          }
          else
          {
            // int 64
            v.push_back(0x3b);
            add_to_vector(v, 8, positive_number);
          }
        }
        break;
      }
      case value_t::number_unsigned:
      {
        if (j.m_value.number_unsigned <= 0x17)
        {
          v.push_back(static_cast<uint8_t>(j.m_value.number_unsigned));
        }
        else if (j.m_value.number_unsigned <= 0xff)
        {
          v.push_back(0x18);
          // one-byte uint8_t
          add_to_vector(v, 1, j.m_value.number_unsigned);
        }
        else if (j.m_value.number_unsigned <= 0xffff)
        {
          v.push_back(0x19);
          // two-byte uint16_t
          add_to_vector(v, 2, j.m_value.number_unsigned);
        }
        else if (j.m_value.number_unsigned <= 0xffffffff)
        {
          v.push_back(0x1a);
          // four-byte uint32_t
          add_to_vector(v, 4, j.m_value.number_unsigned);
        }
        else if (j.m_value.number_unsigned <= 0xffffffffffffffff)
        {
          v.push_back(0x1b);
          // eight-byte uint64_t
          add_to_vector(v, 8, j.m_value.number_unsigned);
        }
        break;
      }
      case value_t::number_float:
      {
        // Double-Precision Float
        v.push_back(0xfb);
        const auto *helper =
            reinterpret_cast<const uint8_t *>(&(j.m_value.number_float));
        for (size_t i = 0; i < 8; ++i)
        {
          v.push_back(helper[7 - i]);
        }
        break;
      }
      case value_t::string:
      {
        const auto N = j.m_value.string->size();
        if (N <= 0x17)
        {
          v.push_back(0x60 + N); // 1 byte for string + size
        }
        else if (N <= 0xff)
        {
          v.push_back(0x78); // one-byte uint8_t for N
          add_to_vector(v, 1, N);
        }
        else if (N <= 0xffff)
        {
          v.push_back(0x79); // two-byte uint16_t for N
          add_to_vector(v, 2, N);
        }
        else if (N <= 0xffffffff)
        {
          v.push_back(0x7a); // four-byte uint32_t for N
          add_to_vector(v, 4, N);
        }
        // LCOV_EXCL_START
        else if (N <= 0xffffffffffffffff)
        {
          v.push_back(0x7b); // eight-byte uint64_t for N
          add_to_vector(v, 8, N);
        }
        // LCOV_EXCL_STOP
        // append string
        std::copy(j.m_value.string->begin(), j.m_value.string->end(),
                  std::back_inserter(v));
        break;
      }
      case value_t::array:
      {
        const auto N = j.m_value.array->size();
        if (N <= 0x17)
        {
          v.push_back(0x80 + N); // 1 byte for array + size
        }
        else if (N <= 0xff)
        {
          v.push_back(0x98); // one-byte uint8_t for N
          add_to_vector(v, 1, N);
        }
        else if (N <= 0xffff)
        {
          v.push_back(0x99); // two-byte uint16_t for N
          add_to_vector(v, 2, N);
        }
        else if (N <= 0xffffffff)
        {
          v.push_back(0x9a); // four-byte uint32_t for N
          add_to_vector(v, 4, N);
        }
        // LCOV_EXCL_START
        else if (N <= 0xffffffffffffffff)
        {
          v.push_back(0x9b); // eight-byte uint64_t for N
          add_to_vector(v, 8, N);
        }
        // LCOV_EXCL_STOP
        // append each element
        for (const auto &el : *j.m_value.array)
        {
          to_cbor_internal(el, v);
        }
        break;
      }
      case value_t::object:
      {
        const auto N = j.m_value.object->size();
        if (N <= 0x17)
        {
          v.push_back(0xa0 + N); // 1 byte for object + size
        }
        else if (N <= 0xff)
        {
          v.push_back(0xb8);
          add_to_vector(v, 1, N); // one-byte uint8_t for N
        }
        else if (N <= 0xffff)
        {
          v.push_back(0xb9);
          add_to_vector(v, 2, N); // two-byte uint16_t for N
        }
        else if (N <= 0xffffffff)
        {
          v.push_back(0xba);
          add_to_vector(v, 4, N); // four-byte uint32_t for N
        }
        // LCOV_EXCL_START
        else if (N <= 0xffffffffffffffff)
        {
          v.push_back(0xbb);
          add_to_vector(v, 8, N); // eight-byte uint64_t for N
        }
        // LCOV_EXCL_STOP
        // append each element
        for (const auto &el : *j.m_value.object)
        {
          to_cbor_internal(el.first, v);
          to_cbor_internal(el.second, v);
        }
        break;
      }
  /*
  @brief checks if given lengths do not exceed the size of a given vector
  To secure the access to the byte vector during CBOR/MessagePack
  deserialization, bytes are copied from the vector into buffers. This
  function checks if the number of bytes to copy (@a len) does not exceed
  the size @s size of the vector. Additionally, an @a offset is given from
  where to start reading the bytes.
  This function checks whether reading the bytes is safe; that is, offset is
  a valid index in the vector, offset+len
  @param[in] size    size of the byte vector
  @param[in] len     number of bytes to read
  @param[in] offset  offset where to start reading
  vec:  x x x x x X X X X X
        ^         ^         ^
        0         offset    len
  @throws out_of_range if `len > v.size()`
  */
  static void check_length(const size_t size, const size_t len,
                           const size_t offset)
  {
    // simple case: requested length is greater than the vector's length
    if (len > size or offset > size)
    {
      JSON_THROW(std::out_of_range("len out of range"));
    }
    // second case: adding offset would result in overflow
    if ((size > (std::numeric_limits<size_t>::max() - offset)))
    {
      JSON_THROW(std::out_of_range("len+offset out of range"));
    }
    // last case: reading past the end of the vector
    if (len + offset > size)
      JSON_THROW(std::out_of_range("len+offset out of range"));
  /*!
  @brief create a JSON value from a given MessagePack vector
  @param[in] v  MessagePack serialization
  @param[in] idx  byte index to start reading from @a v
  @return deserialized JSON value
  @throw std::invalid_argument if unsupported features from MessagePack were
  used in the given vector @a v or if the input is not valid MessagePack
  @throw std::out_of_range if the given vector ends prematurely
  @sa https://github.com/msgpack/msgpack/blob/master/spec.md
  */