Skip to content
Snippets Groups Projects
json.hpp 624 KiB
Newer Older
  • Learn to ignore specific revisions
  • 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000
                    }
    
                    bool prefix_required = true;
                    if (use_type and not j.m_value.array->empty())
                    {
                        assert(use_count);
                        const CharType first_prefix = ubjson_prefix(j.front());
                        const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
                                                             [this, first_prefix](const BasicJsonType & v)
                        {
                            return ubjson_prefix(v) == first_prefix;
                        });
    
                        if (same_prefix)
                        {
                            prefix_required = false;
                            oa->write_character(static_cast<CharType>('$'));
                            oa->write_character(first_prefix);
                        }
                    }
    
                    if (use_count)
                    {
                        oa->write_character(static_cast<CharType>('#'));
                        write_number_with_ubjson_prefix(j.m_value.array->size(), true);
                    }
    
                    for (const auto& el : *j.m_value.array)
                    {
                        write_ubjson(el, use_count, use_type, prefix_required);
                    }
    
                    if (not use_count)
                    {
                        oa->write_character(static_cast<CharType>(']'));
                    }
    
                    break;
                }
    
                case value_t::object:
                {
                    if (add_prefix)
                    {
                        oa->write_character(static_cast<CharType>('{'));
                    }
    
                    bool prefix_required = true;
                    if (use_type and not j.m_value.object->empty())
                    {
                        assert(use_count);
                        const CharType first_prefix = ubjson_prefix(j.front());
                        const bool same_prefix = std::all_of(j.begin(), j.end(),
                                                             [this, first_prefix](const BasicJsonType & v)
                        {
                            return ubjson_prefix(v) == first_prefix;
                        });
    
                        if (same_prefix)
                        {
                            prefix_required = false;
                            oa->write_character(static_cast<CharType>('$'));
                            oa->write_character(first_prefix);
                        }
                    }
    
                    if (use_count)
                    {
                        oa->write_character(static_cast<CharType>('#'));
                        write_number_with_ubjson_prefix(j.m_value.object->size(), true);
                    }
    
                    for (const auto& el : *j.m_value.object)
                    {
                        write_number_with_ubjson_prefix(el.first.size(), true);
                        oa->write_characters(
                            reinterpret_cast<const CharType*>(el.first.c_str()),
                            el.first.size());
                        write_ubjson(el.second, use_count, use_type, prefix_required);
                    }
    
                    if (not use_count)
                    {
                        oa->write_character(static_cast<CharType>('}'));
                    }
    
                    break;
                }
    
                default:
                    break;
            }
        }
    
      private:
        /*
        @brief write a number to output input
    
        @param[in] n number of type @a NumberType
        @tparam NumberType the type of the number
    
        @note This function needs to respect the system's endianess, because bytes
              in CBOR, MessagePack, and UBJSON are stored in network order (big
              endian) and therefore need reordering on little endian systems.
        */
        template<typename NumberType>
        void write_number(const NumberType n)
        {
            // step 1: write number to array of length NumberType
            std::array<CharType, sizeof(NumberType)> vec;
            std::memcpy(vec.data(), &n, sizeof(NumberType));
    
            // step 2: write array to output (with possible reordering)
            if (is_little_endian)
            {
                // reverse byte order prior to conversion if necessary
                std::reverse(vec.begin(), vec.end());
            }
    
            oa->write_characters(vec.data(), sizeof(NumberType));
        }
    
        // UBJSON: write number (floating point)
        template<typename NumberType, typename std::enable_if<
                     std::is_floating_point<NumberType>::value, int>::type = 0>
        void write_number_with_ubjson_prefix(const NumberType n,
                                             const bool add_prefix)
        {
            if (add_prefix)
            {
                oa->write_character(get_ubjson_float_prefix(n));
            }
            write_number(n);
        }
    
        // UBJSON: write number (unsigned integer)
        template<typename NumberType, typename std::enable_if<
                     std::is_unsigned<NumberType>::value, int>::type = 0>
        void write_number_with_ubjson_prefix(const NumberType n,
                                             const bool add_prefix)
        {
            if (n <= static_cast<uint64_t>((std::numeric_limits<int8_t>::max)()))
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('i'));  // int8
                }
                write_number(static_cast<uint8_t>(n));
            }
            else if (n <= (std::numeric_limits<uint8_t>::max)())
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('U'));  // uint8
                }
                write_number(static_cast<uint8_t>(n));
            }
            else if (n <= static_cast<uint64_t>((std::numeric_limits<int16_t>::max)()))
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('I'));  // int16
                }
                write_number(static_cast<int16_t>(n));
            }
            else if (n <= static_cast<uint64_t>((std::numeric_limits<int32_t>::max)()))
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('l'));  // int32
                }
                write_number(static_cast<int32_t>(n));
            }
            else if (n <= static_cast<uint64_t>((std::numeric_limits<int64_t>::max)()))
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('L'));  // int64
                }
                write_number(static_cast<int64_t>(n));
            }
            else
            {
                JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
            }
        }
    
        // UBJSON: write number (signed integer)
        template<typename NumberType, typename std::enable_if<
                     std::is_signed<NumberType>::value and
                     not std::is_floating_point<NumberType>::value, int>::type = 0>
        void write_number_with_ubjson_prefix(const NumberType n,
                                             const bool add_prefix)
        {
            if ((std::numeric_limits<int8_t>::min)() <= n and n <= (std::numeric_limits<int8_t>::max)())
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('i'));  // int8
                }
                write_number(static_cast<int8_t>(n));
            }
            else if (static_cast<int64_t>((std::numeric_limits<uint8_t>::min)()) <= n and n <= static_cast<int64_t>((std::numeric_limits<uint8_t>::max)()))
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('U'));  // uint8
                }
                write_number(static_cast<uint8_t>(n));
            }
            else if ((std::numeric_limits<int16_t>::min)() <= n and n <= (std::numeric_limits<int16_t>::max)())
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('I'));  // int16
                }
                write_number(static_cast<int16_t>(n));
            }
            else if ((std::numeric_limits<int32_t>::min)() <= n and n <= (std::numeric_limits<int32_t>::max)())
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('l'));  // int32
                }
                write_number(static_cast<int32_t>(n));
            }
            else if ((std::numeric_limits<int64_t>::min)() <= n and n <= (std::numeric_limits<int64_t>::max)())
            {
                if (add_prefix)
                {
                    oa->write_character(static_cast<CharType>('L'));  // int64
                }
                write_number(static_cast<int64_t>(n));
            }
            // LCOV_EXCL_START
            else
            {
                JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
            }
            // LCOV_EXCL_STOP
        }
    
        /*!
        @brief determine the type prefix of container values
    
        @note This function does not need to be 100% accurate when it comes to
              integer limits. In case a number exceeds the limits of int64_t,
              this will be detected by a later call to function
              write_number_with_ubjson_prefix. Therefore, we return 'L' for any
              value that does not fit the previous limits.
        */
        CharType ubjson_prefix(const BasicJsonType& j) const noexcept
        {
            switch (j.type())
            {
                case value_t::null:
                    return 'Z';
    
                case value_t::boolean:
                    return j.m_value.boolean ? 'T' : 'F';
    
                case value_t::number_integer:
                {
                    if ((std::numeric_limits<int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
                    {
                        return 'i';
                    }
                    else if ((std::numeric_limits<uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
                    {
                        return 'U';
                    }
                    else if ((std::numeric_limits<int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
                    {
                        return 'I';
                    }
                    else if ((std::numeric_limits<int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
                    {
                        return 'l';
                    }
                    else  // no check and assume int64_t (see note above)
                    {
                        return 'L';
                    }
                }
    
                case value_t::number_unsigned:
                {
                    if (j.m_value.number_unsigned <= (std::numeric_limits<int8_t>::max)())
                    {
                        return 'i';
                    }
                    else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
                    {
                        return 'U';
                    }
                    else if (j.m_value.number_unsigned <= (std::numeric_limits<int16_t>::max)())
                    {
                        return 'I';
                    }
                    else if (j.m_value.number_unsigned <= (std::numeric_limits<int32_t>::max)())
                    {
                        return 'l';
                    }
                    else  // no check and assume int64_t (see note above)
                    {
                        return 'L';
                    }
                }
    
                case value_t::number_float:
                    return get_ubjson_float_prefix(j.m_value.number_float);
    
                case value_t::string:
                    return 'S';
    
                case value_t::array:
                    return '[';
    
                case value_t::object:
                    return '{';
    
                default:  // discarded values
                    return 'N';
            }
        }
    
        static constexpr CharType get_cbor_float_prefix(float)
        {
            return static_cast<CharType>(0xFA);  // Single-Precision Float
        }
    
        static constexpr CharType get_cbor_float_prefix(double)
        {
            return static_cast<CharType>(0xFB);  // Double-Precision Float
        }
    
        static constexpr CharType get_msgpack_float_prefix(float)
        {
            return static_cast<CharType>(0xCA);  // float 32
        }
    
        static constexpr CharType get_msgpack_float_prefix(double)
        {
            return static_cast<CharType>(0xCB);  // float 64
        }
    
        static constexpr CharType get_ubjson_float_prefix(float)
        {
            return 'd';  // float 32
        }
    
        static constexpr CharType get_ubjson_float_prefix(double)
        {
            return 'D';  // float 64
        }
    
      private:
        /// whether we can assume little endianess
        const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
    
        /// the output
        output_adapter_t<CharType> oa = nullptr;
    };
    }
    }
    
    // #include <nlohmann/detail/output/serializer.hpp>
    
    
    #include <algorithm> // reverse, remove, fill, find, none_of
    #include <array> // array
    #include <cassert> // assert
    #include <ciso646> // and, or
    #include <clocale> // localeconv, lconv
    #include <cmath> // labs, isfinite, isnan, signbit
    #include <cstddef> // size_t, ptrdiff_t
    #include <cstdint> // uint8_t
    #include <cstdio> // snprintf
    #include <limits> // numeric_limits
    #include <string> // string
    #include <type_traits> // is_same
    
    // #include <nlohmann/detail/exceptions.hpp>
    
    // #include <nlohmann/detail/conversions/to_chars.hpp>
    
    
    #include <cassert> // assert
    #include <ciso646> // or, and, not
    #include <cmath>   // signbit, isfinite
    #include <cstdint> // intN_t, uintN_t
    #include <cstring> // memcpy, memmove
    
    namespace nlohmann
    {
    namespace detail
    {
    
    /*!
    @brief implements the Grisu2 algorithm for binary to decimal floating-point
    conversion.
    
    This implementation is a slightly modified version of the reference
    implementation which may be obtained from
    http://florian.loitsch.com/publications (bench.tar.gz).
    
    The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
    
    For a detailed description of the algorithm see:
    
    [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
        Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
        Language Design and Implementation, PLDI 2010
    [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
        Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
        Design and Implementation, PLDI 1996
    */
    namespace dtoa_impl
    {
    
    template <typename Target, typename Source>
    Target reinterpret_bits(const Source source)
    {
        static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
    
        Target target;
        std::memcpy(&target, &source, sizeof(Source));
        return target;
    }
    
    struct diyfp // f * 2^e
    {
        static constexpr int kPrecision = 64; // = q
    
        uint64_t f;
        int e;
    
        constexpr diyfp() noexcept : f(0), e(0) {}
        constexpr diyfp(uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
    
        /*!
        @brief returns x - y
        @pre x.e == y.e and x.f >= y.f
        */
        static diyfp sub(const diyfp& x, const diyfp& y) noexcept
        {
            assert(x.e == y.e);
            assert(x.f >= y.f);
    
            return diyfp(x.f - y.f, x.e);
        }
    
        /*!
        @brief returns x * y
        @note The result is rounded. (Only the upper q bits are returned.)
        */
        static diyfp mul(const diyfp& x, const diyfp& y) noexcept
        {
            static_assert(kPrecision == 64, "internal error");
    
            // Computes:
            //  f = round((x.f * y.f) / 2^q)
            //  e = x.e + y.e + q
    
            // Emulate the 64-bit * 64-bit multiplication:
            //
            // p = u * v
            //   = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
            //   = (u_lo v_lo         ) + 2^32 ((u_lo v_hi         ) + (u_hi v_lo         )) + 2^64 (u_hi v_hi         )
            //   = (p0                ) + 2^32 ((p1                ) + (p2                )) + 2^64 (p3                )
            //   = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3                )
            //   = (p0_lo             ) + 2^32 (p0_hi + p1_lo + p2_lo                      ) + 2^64 (p1_hi + p2_hi + p3)
            //   = (p0_lo             ) + 2^32 (Q                                          ) + 2^64 (H                 )
            //   = (p0_lo             ) + 2^32 (Q_lo + 2^32 Q_hi                           ) + 2^64 (H                 )
            //
            // (Since Q might be larger than 2^32 - 1)
            //
            //   = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
            //
            // (Q_hi + H does not overflow a 64-bit int)
            //
            //   = p_lo + 2^64 p_hi
    
            const uint64_t u_lo = x.f & 0xFFFFFFFF;
            const uint64_t u_hi = x.f >> 32;
            const uint64_t v_lo = y.f & 0xFFFFFFFF;
            const uint64_t v_hi = y.f >> 32;
    
            const uint64_t p0 = u_lo * v_lo;
            const uint64_t p1 = u_lo * v_hi;
            const uint64_t p2 = u_hi * v_lo;
            const uint64_t p3 = u_hi * v_hi;
    
            const uint64_t p0_hi = p0 >> 32;
            const uint64_t p1_lo = p1 & 0xFFFFFFFF;
            const uint64_t p1_hi = p1 >> 32;
            const uint64_t p2_lo = p2 & 0xFFFFFFFF;
            const uint64_t p2_hi = p2 >> 32;
    
            uint64_t Q = p0_hi + p1_lo + p2_lo;
    
            // The full product might now be computed as
            //
            // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
            // p_lo = p0_lo + (Q << 32)
            //
            // But in this particular case here, the full p_lo is not required.
            // Effectively we only need to add the highest bit in p_lo to p_hi (and
            // Q_hi + 1 does not overflow).
    
            Q += uint64_t{1} << (64 - 32 - 1); // round, ties up
    
            const uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32);
    
            return diyfp(h, x.e + y.e + 64);
        }
    
        /*!
        @brief normalize x such that the significand is >= 2^(q-1)
        @pre x.f != 0
        */
        static diyfp normalize(diyfp x) noexcept
        {
            assert(x.f != 0);
    
            while ((x.f >> 63) == 0)
            {
                x.f <<= 1;
                x.e--;
            }
    
            return x;
        }
    
        /*!
        @brief normalize x such that the result has the exponent E
        @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
        */
        static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
        {
            const int delta = x.e - target_exponent;
    
            assert(delta >= 0);
            assert(((x.f << delta) >> delta) == x.f);
    
            return diyfp(x.f << delta, target_exponent);
        }
    };
    
    struct boundaries
    {
        diyfp w;
        diyfp minus;
        diyfp plus;
    };
    
    /*!
    Compute the (normalized) diyfp representing the input number 'value' and its
    boundaries.
    
    @pre value must be finite and positive
    */
    template <typename FloatType>
    boundaries compute_boundaries(FloatType value)
    {
        assert(std::isfinite(value));
        assert(value > 0);
    
        // Convert the IEEE representation into a diyfp.
        //
        // If v is denormal:
        //      value = 0.F * 2^(1 - bias) = (          F) * 2^(1 - bias - (p-1))
        // If v is normalized:
        //      value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
    
        static_assert(std::numeric_limits<FloatType>::is_iec559,
                      "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
    
        constexpr int      kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
        constexpr int      kBias      = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
        constexpr int      kMinExp    = 1 - kBias;
        constexpr uint64_t kHiddenBit = uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
    
        using bits_type = typename std::conditional< kPrecision == 24, uint32_t, uint64_t >::type;
    
        const uint64_t bits = reinterpret_bits<bits_type>(value);
        const uint64_t E = bits >> (kPrecision - 1);
        const uint64_t F = bits & (kHiddenBit - 1);
    
        const bool is_denormal = (E == 0);
        const diyfp v = is_denormal
                        ? diyfp(F, kMinExp)
                        : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
    
        // Compute the boundaries m- and m+ of the floating-point value
        // v = f * 2^e.
        //
        // Determine v- and v+, the floating-point predecessor and successor if v,
        // respectively.
        //
        //      v- = v - 2^e        if f != 2^(p-1) or e == e_min                (A)
        //         = v - 2^(e-1)    if f == 2^(p-1) and e > e_min                (B)
        //
        //      v+ = v + 2^e
        //
        // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
        // between m- and m+ round to v, regardless of how the input rounding
        // algorithm breaks ties.
        //
        //      ---+-------------+-------------+-------------+-------------+---  (A)
        //         v-            m-            v             m+            v+
        //
        //      -----------------+------+------+-------------+-------------+---  (B)
        //                       v-     m-     v             m+            v+
    
        const bool lower_boundary_is_closer = (F == 0 and E > 1);
        const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
        const diyfp m_minus = lower_boundary_is_closer
                              ? diyfp(4 * v.f - 1, v.e - 2)  // (B)
                              : diyfp(2 * v.f - 1, v.e - 1); // (A)
    
        // Determine the normalized w+ = m+.
        const diyfp w_plus = diyfp::normalize(m_plus);
    
        // Determine w- = m- such that e_(w-) = e_(w+).
        const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
    
        return {diyfp::normalize(v), w_minus, w_plus};
    }
    
    // Given normalized diyfp w, Grisu needs to find a (normalized) cached
    // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
    // within a certain range [alpha, gamma] (Definition 3.2 from [1])
    //
    //      alpha <= e = e_c + e_w + q <= gamma
    //
    // or
    //
    //      f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
    //                          <= f_c * f_w * 2^gamma
    //
    // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
    //
    //      2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
    //
    // or
    //
    //      2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
    //
    // The choice of (alpha,gamma) determines the size of the table and the form of
    // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
    // in practice:
    //
    // The idea is to cut the number c * w = f * 2^e into two parts, which can be
    // processed independently: An integral part p1, and a fractional part p2:
    //
    //      f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
    //              = (f div 2^-e) + (f mod 2^-e) * 2^e
    //              = p1 + p2 * 2^e
    //
    // The conversion of p1 into decimal form requires a series of divisions and
    // modulos by (a power of) 10. These operations are faster for 32-bit than for
    // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
    // achieved by choosing
    //
    //      -e >= 32   or   e <= -32 := gamma
    //
    // In order to convert the fractional part
    //
    //      p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
    //
    // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
    // d[-i] are extracted in order:
    //
    //      (10 * p2) div 2^-e = d[-1]
    //      (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
    //
    // The multiplication by 10 must not overflow. It is sufficient to choose
    //
    //      10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
    //
    // Since p2 = f mod 2^-e < 2^-e,
    //
    //      -e <= 60   or   e >= -60 := alpha
    
    constexpr int kAlpha = -60;
    constexpr int kGamma = -32;
    
    struct cached_power // c = f * 2^e ~= 10^k
    {
        uint64_t f;
        int e;
        int k;
    };
    
    /*!
    For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
    power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
    satisfies (Definition 3.2 from [1])
    
         alpha <= e_c + e + q <= gamma.
    */
    inline cached_power get_cached_power_for_binary_exponent(int e)
    {
        // Now
        //
        //      alpha <= e_c + e + q <= gamma                                    (1)
        //      ==> f_c * 2^alpha <= c * 2^e * 2^q
        //
        // and since the c's are normalized, 2^(q-1) <= f_c,
        //
        //      ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
        //      ==> 2^(alpha - e - 1) <= c
        //
        // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
        //
        //      k = ceil( log_10( 2^(alpha - e - 1) ) )
        //        = ceil( (alpha - e - 1) * log_10(2) )
        //
        // From the paper:
        // "In theory the result of the procedure could be wrong since c is rounded,
        //  and the computation itself is approximated [...]. In practice, however,
        //  this simple function is sufficient."
        //
        // For IEEE double precision floating-point numbers converted into
        // normalized diyfp's w = f * 2^e, with q = 64,
        //
        //      e >= -1022      (min IEEE exponent)
        //           -52        (p - 1)
        //           -52        (p - 1, possibly normalize denormal IEEE numbers)
        //           -11        (normalize the diyfp)
        //         = -1137
        //
        // and
        //
        //      e <= +1023      (max IEEE exponent)
        //           -52        (p - 1)
        //           -11        (normalize the diyfp)
        //         = 960
        //
        // This binary exponent range [-1137,960] results in a decimal exponent
        // range [-307,324]. One does not need to store a cached power for each
        // k in this range. For each such k it suffices to find a cached power
        // such that the exponent of the product lies in [alpha,gamma].
        // This implies that the difference of the decimal exponents of adjacent
        // table entries must be less than or equal to
        //
        //      floor( (gamma - alpha) * log_10(2) ) = 8.
        //
        // (A smaller distance gamma-alpha would require a larger table.)
    
        // NB:
        // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
    
        constexpr int kCachedPowersSize = 79;
        constexpr int kCachedPowersMinDecExp = -300;
        constexpr int kCachedPowersDecStep = 8;
    
        static constexpr cached_power kCachedPowers[] =
        {
            { 0xAB70FE17C79AC6CA, -1060, -300 },
            { 0xFF77B1FCBEBCDC4F, -1034, -292 },
            { 0xBE5691EF416BD60C, -1007, -284 },
            { 0x8DD01FAD907FFC3C,  -980, -276 },
            { 0xD3515C2831559A83,  -954, -268 },
            { 0x9D71AC8FADA6C9B5,  -927, -260 },
            { 0xEA9C227723EE8BCB,  -901, -252 },
            { 0xAECC49914078536D,  -874, -244 },
            { 0x823C12795DB6CE57,  -847, -236 },
            { 0xC21094364DFB5637,  -821, -228 },
            { 0x9096EA6F3848984F,  -794, -220 },
            { 0xD77485CB25823AC7,  -768, -212 },
            { 0xA086CFCD97BF97F4,  -741, -204 },
            { 0xEF340A98172AACE5,  -715, -196 },
            { 0xB23867FB2A35B28E,  -688, -188 },
            { 0x84C8D4DFD2C63F3B,  -661, -180 },
            { 0xC5DD44271AD3CDBA,  -635, -172 },
            { 0x936B9FCEBB25C996,  -608, -164 },
            { 0xDBAC6C247D62A584,  -582, -156 },
            { 0xA3AB66580D5FDAF6,  -555, -148 },
            { 0xF3E2F893DEC3F126,  -529, -140 },
            { 0xB5B5ADA8AAFF80B8,  -502, -132 },
            { 0x87625F056C7C4A8B,  -475, -124 },
            { 0xC9BCFF6034C13053,  -449, -116 },
            { 0x964E858C91BA2655,  -422, -108 },
            { 0xDFF9772470297EBD,  -396, -100 },
            { 0xA6DFBD9FB8E5B88F,  -369,  -92 },
            { 0xF8A95FCF88747D94,  -343,  -84 },
            { 0xB94470938FA89BCF,  -316,  -76 },
            { 0x8A08F0F8BF0F156B,  -289,  -68 },
            { 0xCDB02555653131B6,  -263,  -60 },
            { 0x993FE2C6D07B7FAC,  -236,  -52 },
            { 0xE45C10C42A2B3B06,  -210,  -44 },
            { 0xAA242499697392D3,  -183,  -36 },
            { 0xFD87B5F28300CA0E,  -157,  -28 },
            { 0xBCE5086492111AEB,  -130,  -20 },
            { 0x8CBCCC096F5088CC,  -103,  -12 },
            { 0xD1B71758E219652C,   -77,   -4 },
            { 0x9C40000000000000,   -50,    4 },
            { 0xE8D4A51000000000,   -24,   12 },
            { 0xAD78EBC5AC620000,     3,   20 },
            { 0x813F3978F8940984,    30,   28 },
            { 0xC097CE7BC90715B3,    56,   36 },
            { 0x8F7E32CE7BEA5C70,    83,   44 },
            { 0xD5D238A4ABE98068,   109,   52 },
            { 0x9F4F2726179A2245,   136,   60 },
            { 0xED63A231D4C4FB27,   162,   68 },
            { 0xB0DE65388CC8ADA8,   189,   76 },
            { 0x83C7088E1AAB65DB,   216,   84 },
            { 0xC45D1DF942711D9A,   242,   92 },
            { 0x924D692CA61BE758,   269,  100 },
            { 0xDA01EE641A708DEA,   295,  108 },
            { 0xA26DA3999AEF774A,   322,  116 },
            { 0xF209787BB47D6B85,   348,  124 },
            { 0xB454E4A179DD1877,   375,  132 },
            { 0x865B86925B9BC5C2,   402,  140 },
            { 0xC83553C5C8965D3D,   428,  148 },
            { 0x952AB45CFA97A0B3,   455,  156 },
            { 0xDE469FBD99A05FE3,   481,  164 },
            { 0xA59BC234DB398C25,   508,  172 },
            { 0xF6C69A72A3989F5C,   534,  180 },
            { 0xB7DCBF5354E9BECE,   561,  188 },
            { 0x88FCF317F22241E2,   588,  196 },
            { 0xCC20CE9BD35C78A5,   614,  204 },
            { 0x98165AF37B2153DF,   641,  212 },
            { 0xE2A0B5DC971F303A,   667,  220 },
            { 0xA8D9D1535CE3B396,   694,  228 },
            { 0xFB9B7CD9A4A7443C,   720,  236 },
            { 0xBB764C4CA7A44410,   747,  244 },
            { 0x8BAB8EEFB6409C1A,   774,  252 },
            { 0xD01FEF10A657842C,   800,  260 },
            { 0x9B10A4E5E9913129,   827,  268 },
            { 0xE7109BFBA19C0C9D,   853,  276 },
            { 0xAC2820D9623BF429,   880,  284 },
            { 0x80444B5E7AA7CF85,   907,  292 },
            { 0xBF21E44003ACDD2D,   933,  300 },
            { 0x8E679C2F5E44FF8F,   960,  308 },
            { 0xD433179D9C8CB841,   986,  316 },
            { 0x9E19DB92B4E31BA9,  1013,  324 },
        };
    
        // This computation gives exactly the same results for k as
        //      k = ceil((kAlpha - e - 1) * 0.30102999566398114)
        // for |e| <= 1500, but doesn't require floating-point operations.
        // NB: log_10(2) ~= 78913 / 2^18
        assert(e >= -1500);
        assert(e <=  1500);
        const int f = kAlpha - e - 1;
        const int k = (f * 78913) / (1 << 18) + (f > 0);
    
        const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
        assert(index >= 0);
        assert(index < kCachedPowersSize);
        static_cast<void>(kCachedPowersSize); // Fix warning.
    
        const cached_power cached = kCachedPowers[index];
        assert(kAlpha <= cached.e + e + 64);
        assert(kGamma >= cached.e + e + 64);
    
        return cached;
    }
    
    /*!
    For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
    For n == 0, returns 1 and sets pow10 := 1.
    */
    inline int find_largest_pow10(const uint32_t n, uint32_t& pow10)
    {
        // LCOV_EXCL_START
        if (n >= 1000000000)
        {
            pow10 = 1000000000;
            return 10;
        }
        // LCOV_EXCL_STOP
        else if (n >= 100000000)
        {
            pow10 = 100000000;
            return  9;
        }
        else if (n >= 10000000)
        {
            pow10 = 10000000;
            return  8;
        }
        else if (n >= 1000000)
        {
            pow10 = 1000000;
            return  7;
        }
        else if (n >= 100000)
        {
            pow10 = 100000;
            return  6;
        }
        else if (n >= 10000)
        {
            pow10 = 10000;
            return  5;
        }
        else if (n >= 1000)
        {
            pow10 = 1000;
            return  4;
        }
        else if (n >= 100)
        {
            pow10 = 100;
            return  3;
        }
        else if (n >= 10)
        {
            pow10 = 10;
            return  2;
        }
        else
        {
            pow10 = 1;
            return 1;
        }
    }
    
    inline void grisu2_round(char* buf, int len, uint64_t dist, uint64_t delta,
                             uint64_t rest, uint64_t ten_k)
    {
        assert(len >= 1);
        assert(dist <= delta);
        assert(rest <= delta);
        assert(ten_k > 0);
    
        //               <--------------------------- delta ---->
        //                                  <---- dist --------->
        // --------------[------------------+-------------------]--------------
        //               M-                 w                   M+
        //
        //                                  ten_k
        //                                <------>
        //                                       <---- rest ---->
        // --------------[------------------+----+--------------]--------------
        //                                  w    V
        //                                       = buf * 10^k
        //
        // ten_k represents a unit-in-the-last-place in the decimal representation
        // stored in buf.
        // Decrement buf by ten_k while this takes buf closer to w.
    
        // The tests are written in this order to avoid overflow in unsigned
        // integer arithmetic.
    
        while (rest < dist
                and delta - rest >= ten_k
                and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
        {
            assert(buf[len - 1] != '0');
            buf[len - 1]--;
            rest += ten_k;
        }
    }
    
    /*!
    Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
    M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
    */
    inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
                                 diyfp M_minus, diyfp w, diyfp M_plus)
    {
        static_assert(kAlpha >= -60, "internal error");
        static_assert(kGamma <= -32, "internal error");
    
        // Generates the digits (and the exponent) of a decimal floating-point
        // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
        // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
        //
        //               <--------------------------- delta ---->
        //                                  <---- dist --------->
        // --------------[------------------+-------------------]--------------
        //               M-                 w                   M+
        //
        // Grisu2 generates the digits of M+ from left to right and stops as soon as
        // V is in [M-,M+].
    
        assert(M_plus.e >= kAlpha);
        assert(M_plus.e <= kGamma);
    
        uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
        uint64_t dist  = diyfp::sub(M_plus, w      ).f; // (significand of (M+ - w ), implicit exponent is e)
    
        // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
        //
        //      M+ = f * 2^e
        //         = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
        //         = ((p1        ) * 2^-e + (p2        )) * 2^e
        //         = p1 + p2 * 2^e
    
        const diyfp one(uint64_t{1} << -M_plus.e, M_plus.e);
    
        uint32_t p1 = static_cast<uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
        uint64_t p2 = M_plus.f & (one.f - 1);                    // p2 = f mod 2^-e
    
        // 1)