Skip to content
Snippets Groups Projects
json.hpp 624 KiB
Newer Older
  • Learn to ignore specific revisions
  • 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000
        //
        // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
    
        assert(p1 > 0);
    
        uint32_t pow10;
        const int k = find_largest_pow10(p1, pow10);
    
        //      10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
        //
        //      p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
        //         = (d[k-1]         ) * 10^(k-1) + (p1 mod 10^(k-1))
        //
        //      M+ = p1                                             + p2 * 2^e
        //         = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1))          + p2 * 2^e
        //         = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
        //         = d[k-1] * 10^(k-1) + (                         rest) * 2^e
        //
        // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
        //
        //      p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
        //
        // but stop as soon as
        //
        //      rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
    
        int n = k;
        while (n > 0)
        {
            // Invariants:
            //      M+ = buffer * 10^n + (p1 + p2 * 2^e)    (buffer = 0 for n = k)
            //      pow10 = 10^(n-1) <= p1 < 10^n
            //
            const uint32_t d = p1 / pow10;  // d = p1 div 10^(n-1)
            const uint32_t r = p1 % pow10;  // r = p1 mod 10^(n-1)
            //
            //      M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
            //         = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
            //
            assert(d <= 9);
            buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
            //
            //      M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
            //
            p1 = r;
            n--;
            //
            //      M+ = buffer * 10^n + (p1 + p2 * 2^e)
            //      pow10 = 10^n
            //
    
            // Now check if enough digits have been generated.
            // Compute
            //
            //      p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
            //
            // Note:
            // Since rest and delta share the same exponent e, it suffices to
            // compare the significands.
            const uint64_t rest = (uint64_t{p1} << -one.e) + p2;
            if (rest <= delta)
            {
                // V = buffer * 10^n, with M- <= V <= M+.
    
                decimal_exponent += n;
    
                // We may now just stop. But instead look if the buffer could be
                // decremented to bring V closer to w.
                //
                // pow10 = 10^n is now 1 ulp in the decimal representation V.
                // The rounding procedure works with diyfp's with an implicit
                // exponent of e.
                //
                //      10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
                //
                const uint64_t ten_n = uint64_t{pow10} << -one.e;
                grisu2_round(buffer, length, dist, delta, rest, ten_n);
    
                return;
            }
    
            pow10 /= 10;
            //
            //      pow10 = 10^(n-1) <= p1 < 10^n
            // Invariants restored.
        }
    
        // 2)
        //
        // The digits of the integral part have been generated:
        //
        //      M+ = d[k-1]...d[1]d[0] + p2 * 2^e
        //         = buffer            + p2 * 2^e
        //
        // Now generate the digits of the fractional part p2 * 2^e.
        //
        // Note:
        // No decimal point is generated: the exponent is adjusted instead.
        //
        // p2 actually represents the fraction
        //
        //      p2 * 2^e
        //          = p2 / 2^-e
        //          = d[-1] / 10^1 + d[-2] / 10^2 + ...
        //
        // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
        //
        //      p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
        //                      + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
        //
        // using
        //
        //      10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
        //                = (                   d) * 2^-e + (                   r)
        //
        // or
        //      10^m * p2 * 2^e = d + r * 2^e
        //
        // i.e.
        //
        //      M+ = buffer + p2 * 2^e
        //         = buffer + 10^-m * (d + r * 2^e)
        //         = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
        //
        // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
    
        assert(p2 > delta);
    
        int m = 0;
        for (;;)
        {
            // Invariant:
            //      M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
            //         = buffer * 10^-m + 10^-m * (p2                                 ) * 2^e
            //         = buffer * 10^-m + 10^-m * (1/10 * (10 * p2)                   ) * 2^e
            //         = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
            //
            assert(p2 <= UINT64_MAX / 10);
            p2 *= 10;
            const uint64_t d = p2 >> -one.e;     // d = (10 * p2) div 2^-e
            const uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
            //
            //      M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
            //         = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
            //         = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
            //
            assert(d <= 9);
            buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
            //
            //      M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
            //
            p2 = r;
            m++;
            //
            //      M+ = buffer * 10^-m + 10^-m * p2 * 2^e
            // Invariant restored.
    
            // Check if enough digits have been generated.
            //
            //      10^-m * p2 * 2^e <= delta * 2^e
            //              p2 * 2^e <= 10^m * delta * 2^e
            //                    p2 <= 10^m * delta
            delta *= 10;
            dist  *= 10;
            if (p2 <= delta)
            {
                break;
            }
        }
    
        // V = buffer * 10^-m, with M- <= V <= M+.
    
        decimal_exponent -= m;
    
        // 1 ulp in the decimal representation is now 10^-m.
        // Since delta and dist are now scaled by 10^m, we need to do the
        // same with ulp in order to keep the units in sync.
        //
        //      10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
        //
        const uint64_t ten_m = one.f;
        grisu2_round(buffer, length, dist, delta, p2, ten_m);
    
        // By construction this algorithm generates the shortest possible decimal
        // number (Loitsch, Theorem 6.2) which rounds back to w.
        // For an input number of precision p, at least
        //
        //      N = 1 + ceil(p * log_10(2))
        //
        // decimal digits are sufficient to identify all binary floating-point
        // numbers (Matula, "In-and-Out conversions").
        // This implies that the algorithm does not produce more than N decimal
        // digits.
        //
        //      N = 17 for p = 53 (IEEE double precision)
        //      N = 9  for p = 24 (IEEE single precision)
    }
    
    /*!
    v = buf * 10^decimal_exponent
    len is the length of the buffer (number of decimal digits)
    The buffer must be large enough, i.e. >= max_digits10.
    */
    inline void grisu2(char* buf, int& len, int& decimal_exponent,
                       diyfp m_minus, diyfp v, diyfp m_plus)
    {
        assert(m_plus.e == m_minus.e);
        assert(m_plus.e == v.e);
    
        //  --------(-----------------------+-----------------------)--------    (A)
        //          m-                      v                       m+
        //
        //  --------------------(-----------+-----------------------)--------    (B)
        //                      m-          v                       m+
        //
        // First scale v (and m- and m+) such that the exponent is in the range
        // [alpha, gamma].
    
        const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
    
        const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
    
        // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
        const diyfp w       = diyfp::mul(v,       c_minus_k);
        const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
        const diyfp w_plus  = diyfp::mul(m_plus,  c_minus_k);
    
        //  ----(---+---)---------------(---+---)---------------(---+---)----
        //          w-                      w                       w+
        //          = c*m-                  = c*v                   = c*m+
        //
        // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
        // w+ are now off by a small amount.
        // In fact:
        //
        //      w - v * 10^k < 1 ulp
        //
        // To account for this inaccuracy, add resp. subtract 1 ulp.
        //
        //  --------+---[---------------(---+---)---------------]---+--------
        //          w-  M-                  w                   M+  w+
        //
        // Now any number in [M-, M+] (bounds included) will round to w when input,
        // regardless of how the input rounding algorithm breaks ties.
        //
        // And digit_gen generates the shortest possible such number in [M-, M+].
        // Note that this does not mean that Grisu2 always generates the shortest
        // possible number in the interval (m-, m+).
        const diyfp M_minus(w_minus.f + 1, w_minus.e);
        const diyfp M_plus (w_plus.f  - 1, w_plus.e );
    
        decimal_exponent = -cached.k; // = -(-k) = k
    
        grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
    }
    
    /*!
    v = buf * 10^decimal_exponent
    len is the length of the buffer (number of decimal digits)
    The buffer must be large enough, i.e. >= max_digits10.
    */
    template <typename FloatType>
    void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
    {
        static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
                      "internal error: not enough precision");
    
        assert(std::isfinite(value));
        assert(value > 0);
    
        // If the neighbors (and boundaries) of 'value' are always computed for double-precision
        // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
        // decimal representations are not exactly "short".
        //
        // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
        // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
        // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
        // does.
        // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
        // representation using the corresponding std::from_chars function recovers value exactly". That
        // indicates that single precision floating-point numbers should be recovered using
        // 'std::strtof'.
        //
        // NB: If the neighbors are computed for single-precision numbers, there is a single float
        //     (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
        //     value is off by 1 ulp.
    #if 0
        const boundaries w = compute_boundaries(static_cast<double>(value));
    #else
        const boundaries w = compute_boundaries(value);
    #endif
    
        grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
    }
    
    /*!
    @brief appends a decimal representation of e to buf
    @return a pointer to the element following the exponent.
    @pre -1000 < e < 1000
    */
    inline char* append_exponent(char* buf, int e)
    {
        assert(e > -1000);
        assert(e <  1000);
    
        if (e < 0)
        {
            e = -e;
            *buf++ = '-';
        }
        else
        {
            *buf++ = '+';
        }
    
        uint32_t k = static_cast<uint32_t>(e);
        if (k < 10)
        {
            // Always print at least two digits in the exponent.
            // This is for compatibility with printf("%g").
            *buf++ = '0';
            *buf++ = static_cast<char>('0' + k);
        }
        else if (k < 100)
        {
            *buf++ = static_cast<char>('0' + k / 10);
            k %= 10;
            *buf++ = static_cast<char>('0' + k);
        }
        else
        {
            *buf++ = static_cast<char>('0' + k / 100);
            k %= 100;
            *buf++ = static_cast<char>('0' + k / 10);
            k %= 10;
            *buf++ = static_cast<char>('0' + k);
        }
    
        return buf;
    }
    
    /*!
    @brief prettify v = buf * 10^decimal_exponent
    
    If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
    notation. Otherwise it will be printed in exponential notation.
    
    @pre min_exp < 0
    @pre max_exp > 0
    */
    inline char* format_buffer(char* buf, int len, int decimal_exponent,
                               int min_exp, int max_exp)
    {
        assert(min_exp < 0);
        assert(max_exp > 0);
    
        const int k = len;
        const int n = len + decimal_exponent;
    
        // v = buf * 10^(n-k)
        // k is the length of the buffer (number of decimal digits)
        // n is the position of the decimal point relative to the start of the buffer.
    
        if (k <= n and n <= max_exp)
        {
            // digits[000]
            // len <= max_exp + 2
    
            std::memset(buf + k, '0', static_cast<size_t>(n - k));
            // Make it look like a floating-point number (#362, #378)
            buf[n + 0] = '.';
            buf[n + 1] = '0';
            return buf + (n + 2);
        }
    
        if (0 < n and n <= max_exp)
        {
            // dig.its
            // len <= max_digits10 + 1
    
            assert(k > n);
    
            std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
            buf[n] = '.';
            return buf + (k + 1);
        }
    
        if (min_exp < n and n <= 0)
        {
            // 0.[000]digits
            // len <= 2 + (-min_exp - 1) + max_digits10
    
            std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
            buf[0] = '0';
            buf[1] = '.';
            std::memset(buf + 2, '0', static_cast<size_t>(-n));
            return buf + (2 + (-n) + k);
        }
    
        if (k == 1)
        {
            // dE+123
            // len <= 1 + 5
    
            buf += 1;
        }
        else
        {
            // d.igitsE+123
            // len <= max_digits10 + 1 + 5
    
            std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
            buf[1] = '.';
            buf += 1 + k;
        }
    
        *buf++ = 'e';
        return append_exponent(buf, n - 1);
    }
    
    } // namespace dtoa_impl
    
    /*!
    @brief generates a decimal representation of the floating-point number value in [first, last).
    
    The format of the resulting decimal representation is similar to printf's %g
    format. Returns an iterator pointing past-the-end of the decimal representation.
    
    @note The input number must be finite, i.e. NaN's and Inf's are not supported.
    @note The buffer must be large enough.
    @note The result is NOT null-terminated.
    */
    template <typename FloatType>
    char* to_chars(char* first, char* last, FloatType value)
    {
        static_cast<void>(last); // maybe unused - fix warning
        assert(std::isfinite(value));
    
        // Use signbit(value) instead of (value < 0) since signbit works for -0.
        if (std::signbit(value))
        {
            value = -value;
            *first++ = '-';
        }
    
        if (value == 0) // +-0
        {
            *first++ = '0';
            // Make it look like a floating-point number (#362, #378)
            *first++ = '.';
            *first++ = '0';
            return first;
        }
    
        assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
    
        // Compute v = buffer * 10^decimal_exponent.
        // The decimal digits are stored in the buffer, which needs to be interpreted
        // as an unsigned decimal integer.
        // len is the length of the buffer, i.e. the number of decimal digits.
        int len = 0;
        int decimal_exponent = 0;
        dtoa_impl::grisu2(first, len, decimal_exponent, value);
    
        assert(len <= std::numeric_limits<FloatType>::max_digits10);
    
        // Format the buffer like printf("%.*g", prec, value)
        constexpr int kMinExp = -4;
        // Use digits10 here to increase compatibility with version 2.
        constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
    
        assert(last - first >= kMaxExp + 2);
        assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
        assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
    
        return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
    }
    
    } // namespace detail
    } // namespace nlohmann
    
    // #include <nlohmann/detail/macro_scope.hpp>
    
    // #include <nlohmann/detail/meta.hpp>
    
    // #include <nlohmann/detail/output/output_adapters.hpp>
    
    // #include <nlohmann/detail/value_t.hpp>
    
    
    namespace nlohmann
    {
    namespace detail
    {
    ///////////////////
    // serialization //
    ///////////////////
    
    template<typename BasicJsonType>
    class serializer
    {
        using string_t = typename BasicJsonType::string_t;
        using number_float_t = typename BasicJsonType::number_float_t;
        using number_integer_t = typename BasicJsonType::number_integer_t;
        using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
        static constexpr uint8_t UTF8_ACCEPT = 0;
        static constexpr uint8_t UTF8_REJECT = 1;
    
      public:
        /*!
        @param[in] s  output stream to serialize to
        @param[in] ichar  indentation character to use
        */
        serializer(output_adapter_t<char> s, const char ichar)
            : o(std::move(s)), loc(std::localeconv()),
              thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)),
              decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)),
              indent_char(ichar), indent_string(512, indent_char)
        {}
    
        // delete because of pointer members
        serializer(const serializer&) = delete;
        serializer& operator=(const serializer&) = delete;
    
        /*!
        @brief internal implementation of the serialization function
    
        This function is called by the public member function dump and organizes
        the serialization internally. The indentation level is propagated as
        additional parameter. In case of arrays and objects, the function is
        called recursively.
    
        - strings and object keys are escaped using `escape_string()`
        - integer numbers are converted implicitly via `operator<<`
        - floating-point numbers are converted to a string using `"%g"` format
    
        @param[in] val             value to serialize
        @param[in] pretty_print    whether the output shall be pretty-printed
        @param[in] indent_step     the indent level
        @param[in] current_indent  the current indent level (only used internally)
        */
        void dump(const BasicJsonType& val, const bool pretty_print,
                  const bool ensure_ascii,
                  const unsigned int indent_step,
                  const unsigned int current_indent = 0)
        {
            switch (val.m_type)
            {
                case value_t::object:
                {
                    if (val.m_value.object->empty())
                    {
                        o->write_characters("{}", 2);
                        return;
                    }
    
                    if (pretty_print)
                    {
                        o->write_characters("{\n", 2);
    
                        // variable to hold indentation for recursive calls
                        const auto new_indent = current_indent + indent_step;
                        if (JSON_UNLIKELY(indent_string.size() < new_indent))
                        {
                            indent_string.resize(indent_string.size() * 2, ' ');
                        }
    
                        // first n-1 elements
                        auto i = val.m_value.object->cbegin();
                        for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
                        {
                            o->write_characters(indent_string.c_str(), new_indent);
                            o->write_character('\"');
                            dump_escaped(i->first, ensure_ascii);
                            o->write_characters("\": ", 3);
                            dump(i->second, true, ensure_ascii, indent_step, new_indent);
                            o->write_characters(",\n", 2);
                        }
    
                        // last element
                        assert(i != val.m_value.object->cend());
                        assert(std::next(i) == val.m_value.object->cend());
                        o->write_characters(indent_string.c_str(), new_indent);
                        o->write_character('\"');
                        dump_escaped(i->first, ensure_ascii);
                        o->write_characters("\": ", 3);
                        dump(i->second, true, ensure_ascii, indent_step, new_indent);
    
                        o->write_character('\n');
                        o->write_characters(indent_string.c_str(), current_indent);
                        o->write_character('}');
                    }
                    else
                    {
                        o->write_character('{');
    
                        // first n-1 elements
                        auto i = val.m_value.object->cbegin();
                        for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
                        {
                            o->write_character('\"');
                            dump_escaped(i->first, ensure_ascii);
                            o->write_characters("\":", 2);
                            dump(i->second, false, ensure_ascii, indent_step, current_indent);
                            o->write_character(',');
                        }
    
                        // last element
                        assert(i != val.m_value.object->cend());
                        assert(std::next(i) == val.m_value.object->cend());
                        o->write_character('\"');
                        dump_escaped(i->first, ensure_ascii);
                        o->write_characters("\":", 2);
                        dump(i->second, false, ensure_ascii, indent_step, current_indent);
    
                        o->write_character('}');
                    }
    
                    return;
                }
    
                case value_t::array:
                {
                    if (val.m_value.array->empty())
                    {
                        o->write_characters("[]", 2);
                        return;
                    }
    
                    if (pretty_print)
                    {
                        o->write_characters("[\n", 2);
    
                        // variable to hold indentation for recursive calls
                        const auto new_indent = current_indent + indent_step;
                        if (JSON_UNLIKELY(indent_string.size() < new_indent))
                        {
                            indent_string.resize(indent_string.size() * 2, ' ');
                        }
    
                        // first n-1 elements
                        for (auto i = val.m_value.array->cbegin();
                                i != val.m_value.array->cend() - 1; ++i)
                        {
                            o->write_characters(indent_string.c_str(), new_indent);
                            dump(*i, true, ensure_ascii, indent_step, new_indent);
                            o->write_characters(",\n", 2);
                        }
    
                        // last element
                        assert(not val.m_value.array->empty());
                        o->write_characters(indent_string.c_str(), new_indent);
                        dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
    
                        o->write_character('\n');
                        o->write_characters(indent_string.c_str(), current_indent);
                        o->write_character(']');
                    }
                    else
                    {
                        o->write_character('[');
    
                        // first n-1 elements
                        for (auto i = val.m_value.array->cbegin();
                                i != val.m_value.array->cend() - 1; ++i)
                        {
                            dump(*i, false, ensure_ascii, indent_step, current_indent);
                            o->write_character(',');
                        }
    
                        // last element
                        assert(not val.m_value.array->empty());
                        dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
    
                        o->write_character(']');
                    }
    
                    return;
                }
    
                case value_t::string:
                {
                    o->write_character('\"');
                    dump_escaped(*val.m_value.string, ensure_ascii);
                    o->write_character('\"');
                    return;
                }
    
                case value_t::boolean:
                {
                    if (val.m_value.boolean)
                    {
                        o->write_characters("true", 4);
                    }
                    else
                    {
                        o->write_characters("false", 5);
                    }
                    return;
                }
    
                case value_t::number_integer:
                {
                    dump_integer(val.m_value.number_integer);
                    return;
                }
    
                case value_t::number_unsigned:
                {
                    dump_integer(val.m_value.number_unsigned);
                    return;
                }
    
                case value_t::number_float:
                {
                    dump_float(val.m_value.number_float);
                    return;
                }
    
                case value_t::discarded:
                {
                    o->write_characters("<discarded>", 11);
                    return;
                }
    
                case value_t::null:
                {
                    o->write_characters("null", 4);
                    return;
                }
            }
        }
    
      private:
        /*!
        @brief dump escaped string
    
        Escape a string by replacing certain special characters by a sequence of an
        escape character (backslash) and another character and other control
        characters by a sequence of "\u" followed by a four-digit hex
        representation. The escaped string is written to output stream @a o.
    
        @param[in] s  the string to escape
        @param[in] ensure_ascii  whether to escape non-ASCII characters with
                                 \uXXXX sequences
    
        @complexity Linear in the length of string @a s.
        */
        void dump_escaped(const string_t& s, const bool ensure_ascii)
        {
            uint32_t codepoint;
            uint8_t state = UTF8_ACCEPT;
            std::size_t bytes = 0;  // number of bytes written to string_buffer
    
            for (std::size_t i = 0; i < s.size(); ++i)
            {
                const auto byte = static_cast<uint8_t>(s[i]);
    
                switch (decode(state, codepoint, byte))
                {
                    case UTF8_ACCEPT:  // decode found a new code point
                    {
                        switch (codepoint)
                        {
                            case 0x08: // backspace
                            {
                                string_buffer[bytes++] = '\\';
                                string_buffer[bytes++] = 'b';
                                break;
                            }
    
                            case 0x09: // horizontal tab
                            {
                                string_buffer[bytes++] = '\\';
                                string_buffer[bytes++] = 't';
                                break;
                            }
    
                            case 0x0A: // newline
                            {
                                string_buffer[bytes++] = '\\';
                                string_buffer[bytes++] = 'n';
                                break;
                            }
    
                            case 0x0C: // formfeed
                            {
                                string_buffer[bytes++] = '\\';
                                string_buffer[bytes++] = 'f';
                                break;
                            }
    
                            case 0x0D: // carriage return
                            {
                                string_buffer[bytes++] = '\\';
                                string_buffer[bytes++] = 'r';
                                break;
                            }
    
                            case 0x22: // quotation mark
                            {
                                string_buffer[bytes++] = '\\';
                                string_buffer[bytes++] = '\"';
                                break;
                            }
    
                            case 0x5C: // reverse solidus
                            {
                                string_buffer[bytes++] = '\\';
                                string_buffer[bytes++] = '\\';
                                break;
                            }
    
                            default:
                            {
                                // escape control characters (0x00..0x1F) or, if
                                // ensure_ascii parameter is used, non-ASCII characters
                                if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
                                {
                                    if (codepoint <= 0xFFFF)
                                    {
                                        std::snprintf(string_buffer.data() + bytes, 7, "\\u%04x",
                                                      static_cast<uint16_t>(codepoint));
                                        bytes += 6;
                                    }
                                    else
                                    {
                                        std::snprintf(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
                                                      static_cast<uint16_t>(0xD7C0 + (codepoint >> 10)),
                                                      static_cast<uint16_t>(0xDC00 + (codepoint & 0x3FF)));
                                        bytes += 12;
                                    }
                                }
                                else
                                {
                                    // copy byte to buffer (all previous bytes
                                    // been copied have in default case above)
                                    string_buffer[bytes++] = s[i];
                                }
                                break;
                            }
                        }
    
                        // write buffer and reset index; there must be 13 bytes
                        // left, as this is the maximal number of bytes to be
                        // written ("\uxxxx\uxxxx\0") for one code point
                        if (string_buffer.size() - bytes < 13)
                        {
                            o->write_characters(string_buffer.data(), bytes);
                            bytes = 0;
                        }
                        break;
                    }
    
                    case UTF8_REJECT:  // decode found invalid UTF-8 byte
                    {
                        std::string sn(3, '\0');
                        snprintf(&sn[0], sn.size(), "%.2X", byte);
                        JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
                    }
    
                    default:  // decode found yet incomplete multi-byte code point
                    {
                        if (not ensure_ascii)
                        {
                            // code point will not be escaped - copy byte to buffer
                            string_buffer[bytes++] = s[i];
                        }
                        break;
                    }
                }
            }
    
            if (JSON_LIKELY(state == UTF8_ACCEPT))
            {
                // write buffer
                if (bytes > 0)
                {
                    o->write_characters(string_buffer.data(), bytes);
                }
            }
            else
            {
                // we finish reading, but do not accept: string was incomplete
                std::string sn(3, '\0');
                snprintf(&sn[0], sn.size(), "%.2X", static_cast<uint8_t>(s.back()));
                JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
            }
        }
    
        /*!
        @brief dump an integer
    
        Dump a given integer to output stream @a o. Works internally with
        @a number_buffer.
    
        @param[in] x  integer number (signed or unsigned) to dump
        @tparam NumberType either @a number_integer_t or @a number_unsigned_t
        */
        template<typename NumberType, detail::enable_if_t<
                     std::is_same<NumberType, number_unsigned_t>::value or
                     std::is_same<NumberType, number_integer_t>::value,
                     int> = 0>
        void dump_integer(NumberType x)
        {
            // special case for "0"
            if (x == 0)
            {
                o->write_character('0');
                return;
            }
    
            const bool is_negative = (x <= 0) and (x != 0);  // see issue #755
            std::size_t i = 0;
    
            while (x != 0)
            {
                // spare 1 byte for '\0'
                assert(i < number_buffer.size() - 1);
    
                const auto digit = std::labs(static_cast<long>(x % 10));
                number_buffer[i++] = static_cast<char>('0' + digit);
                x /= 10;
            }
    
            if (is_negative)
            {
                // make sure there is capacity for the '-'
                assert(i < number_buffer.size() - 2);
                number_buffer[i++] = '-';
            }
    
            std::reverse(number_buffer.begin(), number_buffer.begin() + i);
            o->write_characters(number_buffer.data(), i);
        }
    
        /*!
        @brief dump a floating-point number
    
        Dump a given floating-point number to output stream @a o. Works internally
        with @a number_buffer.
    
        @param[in] x  floating-point number to dump
        */
        void dump_float(number_float_t x)
        {
            // NaN / inf
            if (not std::isfinite(x))
            {
                o->write_characters("null", 4);
                return;
            }
    
            // If number_float_t is an IEEE-754 single or double precision number,
            // use the Grisu2 algorithm to produce short numbers which are
            // guaranteed to round-trip, using strtof and strtod, resp.
            //
            // NB: The test below works if <long double> == <double>.
            static constexpr bool is_ieee_single_or_double
                = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or
                  (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);
    
            dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
        }
    
        void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
        {
            char* begin = number_buffer.data();
            char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
    
            o->write_characters(begin, static_cast<size_t>(end - begin));
        }
    
        void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
        {
            // get number of digits for a float -> text -> float round-trip
            static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
    
            // the actual conversion
            std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
    
            // negative value indicates an error
            assert(len > 0);
            // check if buffer was large enough
            assert(static_cast<std::size_t>(len) < number_buffer.size());
    
            // erase thousands separator
            if (thousands_sep != '\0')
            {
                const auto end = std::remove(number_buffer.begin(),
                                             number_buffer.begin() + len, thousands_sep);
                std::fill(end, number_buffer.end(), '\0');
                assert((end - number_buffer.begin()) <= len);
                len = (end - number_buffer.begin());
            }
    
            // convert decimal point to '.'
            if (decimal_point != '\0' and decimal_point != '.')
            {
                const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);