aboutsummaryrefslogtreecommitdiff
path: root/include/jsoncons/detail/write_number.hpp
blob: 261346737ddbe5daf122736784e47eb620471e65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// Copyright 2013 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// See https://github.com/danielaparker/jsoncons for latest version

#ifndef JSONCONS_DETAIL_WRITE_NUMBER_HPP
#define JSONCONS_DETAIL_WRITE_NUMBER_HPP

#include <stdexcept>
#include <string>
#include <cmath>
#include <locale>
#include <limits> // std::numeric_limits
#include <exception>
#include <stdio.h> // snprintf
#include <jsoncons/config/jsoncons_config.hpp>
#include <jsoncons/json_options.hpp>
#include <jsoncons/detail/grisu3.hpp>
#include <jsoncons/detail/parse_number.hpp>
#include <jsoncons/more_type_traits.hpp>

namespace jsoncons { 
namespace detail {

    inline
    char to_hex_character(uint8_t c)
    {
        return (char)((c < 10) ? ('0' + c) : ('A' - 10 + c));
    }

    // from_integer

    template<class Integer,class Result>
    typename std::enable_if<type_traits::is_integer<Integer>::value,std::size_t>::type
    from_integer(Integer value, Result& result)
    {
        using char_type = typename Result::value_type;

        char_type buf[255];
        char_type *p = buf;
        const char_type* last = buf+255;

        bool is_negative = value < 0;

        if (value < 0)
        {
            do
            {
                *p++ = static_cast<char_type>(48 - (value % 10));
            }
            while ((value /= 10) && (p < last));
        }
        else
        {

            do
            {
                *p++ = static_cast<char_type>(48 + value % 10);
            }
            while ((value /= 10) && (p < last));
        }
        JSONCONS_ASSERT(p != last);

        std::size_t count = (p - buf);
        if (is_negative)
        {
            result.push_back('-');
            ++count;
        }
        while (--p >= buf)
        {
            result.push_back(*p);
        }

        return count;
    }

    // integer_to_string_hex

    template<class Integer,class Result>
    typename std::enable_if<type_traits::is_integer<Integer>::value,std::size_t>::type
    integer_to_string_hex(Integer value, Result& result)
    {
        using char_type = typename Result::value_type;

        char_type buf[255];
        char_type *p = buf;
        const char_type* last = buf+255;

        bool is_negative = value < 0;

        if (value < 0)
        {
            do
            {
                *p++ = to_hex_character(0-(value % 16));
            }
            while ((value /= 16) && (p < last));
        }
        else
        {

            do
            {
                *p++ = to_hex_character(value % 16);
            }
            while ((value /= 16) && (p < last));
        }
        JSONCONS_ASSERT(p != last);

        std::size_t count = (p - buf);
        if (is_negative)
        {
            result.push_back('-');
            ++count;
        }
        while (--p >= buf)
        {
            result.push_back(*p);
        }

        return count;
    }

    // write_double

    // fast exponent
    template <class Result>
    void fill_exponent(int K, Result& result)
    {
        if (K < 0)
        {
            result.push_back('-');
            K = -K;
        }
        else
        {
            result.push_back('+'); // compatibility with sprintf
        }

        if (K < 10)
        {
            result.push_back('0'); // compatibility with sprintf
            result.push_back((char)('0' + K));
        }
        else if (K < 100)
        {
            result.push_back((char)('0' + K / 10)); K %= 10;
            result.push_back((char)('0' + K));
        }
        else if (K < 1000)
        {
            result.push_back((char)('0' + K / 100)); K %= 100;
            result.push_back((char)('0' + K / 10)); K %= 10;
            result.push_back((char)('0' + K));
        }
        else
        {
            jsoncons::detail::from_integer(K, result);
        }
    }

    template <class Result>
    void prettify_string(const char *buffer, std::size_t length, int k, int min_exp, int max_exp, Result& result)
    {
        int nb_digits = (int)length;
        int offset;
        /* v = buffer * 10^k
           kk is such that 10^(kk-1) <= v < 10^kk
           this way kk gives the position of the decimal point.
        */
        int kk = nb_digits + k;

        if (nb_digits <= kk && kk <= max_exp)
        {
            /* the first digits are already in. Add some 0s and call it a day. */
            /* the max_exp is a personal choice. Only 16 digits could possibly be relevant.
             * Basically we want to print 12340000000 rather than 1234.0e7 or 1.234e10 */
            for (int i = 0; i < nb_digits; ++i)
            {
                result.push_back(buffer[i]);
            }
            for (int i = nb_digits; i < kk; ++i)
            {
                result.push_back('0');
            }
            result.push_back('.');
            result.push_back('0');
        } 
        else if (0 < kk && kk <= max_exp)
        {
            /* comma number. Just insert a '.' at the correct location. */
            for (int i = 0; i < kk; ++i)
            {
                result.push_back(buffer[i]);
            }
            result.push_back('.');
            for (int i = kk; i < nb_digits; ++i)
            {
                result.push_back(buffer[i]);
            }
        } 
        else if (min_exp < kk && kk <= 0)
        {
            offset = 2 - kk;

            result.push_back('0');
            result.push_back('.');
            for (int i = 2; i < offset; ++i) 
                result.push_back('0');
            for (int i = 0; i < nb_digits; ++i)
            {
                result.push_back(buffer[i]);
            }
        } 
        else if (nb_digits == 1)
        {
            result.push_back(buffer[0]);
            result.push_back('e');
            fill_exponent(kk - 1, result);
        } 
        else
        {
            result.push_back(buffer[0]);
            result.push_back('.');
            for (int i = 1; i < nb_digits; ++i)
            {
                result.push_back(buffer[i]);
            }
            result.push_back('e');
            fill_exponent(kk - 1, result);
        }
    }

    template<class Result>
    void dump_buffer(const char *buffer, std::size_t length, char decimal_point, Result& result)
    {
        const char *sbeg = buffer;
        const char *send = sbeg + length;

        if (sbeg != send)
        {
            bool needs_dot = true;
            for (const char* q = sbeg; q < send; ++q)
            {
                switch (*q)
                {
                case '-':
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                case '+':
                    result.push_back(*q);
                    break;
                case 'e':
                case 'E':
                    result.push_back('e');
                    needs_dot = false;
                    break;
                default:
                    if (*q == decimal_point)
                    {
                        needs_dot = false;
                        result.push_back('.');
                    }
                    break;
                }
            }
            if (needs_dot)
            {
                result.push_back('.');
                result.push_back('0');
                needs_dot = true;
            }
        }
    }

    template<class Result>
    bool dtoa_scientific(double val, char decimal_point, Result& result)
    {
        if (val == 0)
        {
            result.push_back('0');
            result.push_back('.');
            result.push_back('0');
            return true;
        }

        jsoncons::detail::chars_to to_double_;

        char buffer[100];
        int precision = std::numeric_limits<double>::digits10;
        int length = snprintf(buffer, sizeof(buffer), "%1.*e", precision, val);
        if (length < 0)
        {
            return false;
        }
        if (to_double_(buffer, sizeof(buffer)) != val)
        {
            const int precision2 = std::numeric_limits<double>::max_digits10;
            length = snprintf(buffer, sizeof(buffer), "%1.*e", precision2, val);
            if (length < 0)
            {
                return false;
            }
        }
        dump_buffer(buffer, static_cast<std::size_t>(length), decimal_point, result);
        return true;
    }

    template<class Result>
    bool dtoa_general(double val, char decimal_point, Result& result, std::false_type)
    {
        if (val == 0)
        {
            result.push_back('0');
            result.push_back('.');
            result.push_back('0');
            return true;
        }

        jsoncons::detail::chars_to to_double_;

        char buffer[100];
        int precision = std::numeric_limits<double>::digits10;
        int length = snprintf(buffer, sizeof(buffer), "%1.*g", precision, val);
        if (length < 0)
        {
            return false;
        }
        if (to_double_(buffer, sizeof(buffer)) != val)
        {
            const int precision2 = std::numeric_limits<double>::max_digits10;
            length = snprintf(buffer, sizeof(buffer), "%1.*g", precision2, val);
            if (length < 0)
            {
                return false;
            }
        }
        dump_buffer(buffer, length, decimal_point, result);
        return true;
    }

    template<class Result>
    bool dtoa_general(double v, char decimal_point, Result& result, std::true_type)
    {
        if (v == 0)
        {
            result.push_back('0');
            result.push_back('.');
            result.push_back('0');
            return true;
        }

        int length = 0;
        int k;

        char buffer[100];

        double u = std::signbit(v) ? -v : v;
        if (jsoncons::detail::grisu3(u, buffer, &length, &k))
        {
            if (std::signbit(v))
            {
                result.push_back('-');
            }
            // min exp: -4 is consistent with sprintf
            // max exp: std::numeric_limits<double>::max_digits10
            jsoncons::detail::prettify_string(buffer, length, k, -4, std::numeric_limits<double>::max_digits10, result);
            return true;
        }
        else
        {
            return dtoa_general(v, decimal_point, result, std::false_type());
        }
    }

    template<class Result>
    bool dtoa_fixed(double val, char decimal_point, Result& result, std::false_type)
    {
        if (val == 0)
        {
            result.push_back('0');
            result.push_back('.');
            result.push_back('0');
            return true;
        }

        jsoncons::detail::chars_to to_double_;

        char buffer[100];
        int precision = std::numeric_limits<double>::digits10;
        int length = snprintf(buffer, sizeof(buffer), "%1.*f", precision, val);
        if (length < 0)
        {
            return false;
        }
        if (to_double_(buffer, sizeof(buffer)) != val)
        {
            const int precision2 = std::numeric_limits<double>::max_digits10;
            length = snprintf(buffer, sizeof(buffer), "%1.*f", precision2, val);
            if (length < 0)
            {
                return false;
            }
        }
        dump_buffer(buffer, length, decimal_point, result);
        return true;
    }

    template<class Result>
    bool dtoa_fixed(double v, char decimal_point, Result& result, std::true_type)
    {
        if (v == 0)
        {
            result.push_back('0');
            result.push_back('.');
            result.push_back('0');
            return true;
        }

        int length = 0;
        int k;

        char buffer[100];

        double u = std::signbit(v) ? -v : v;
        if (jsoncons::detail::grisu3(u, buffer, &length, &k))
        {
            if (std::signbit(v))
            {
                result.push_back('-');
            }
            jsoncons::detail::prettify_string(buffer, length, k, std::numeric_limits<int>::lowest(), (std::numeric_limits<int>::max)(), result);
            return true;
        }
        else
        {
            return dtoa_fixed(v, decimal_point, result, std::false_type());
        }
    }

    template<class Result>
    bool dtoa_fixed(double v, char decimal_point, Result& result)
    {
        return dtoa_fixed(v, decimal_point, result, std::integral_constant<bool, std::numeric_limits<double>::is_iec559>());
    }

    template<class Result>
    bool dtoa_general(double v, char decimal_point, Result& result)
    {
        return dtoa_general(v, decimal_point, result, std::integral_constant<bool, std::numeric_limits<double>::is_iec559>());
    }

    class write_double
    {
    private:
        chars_to to_double_;
        float_chars_format float_format_;
        int precision_;
        char decimal_point_;
    public:
        write_double(float_chars_format float_format, int precision)
           : float_format_(float_format), precision_(precision), decimal_point_('.')
        {
    #if !defined(JSONCONS_NO_LOCALECONV)
            struct lconv *lc = localeconv();
            if (lc != nullptr && lc->decimal_point[0] != 0)
            {
                decimal_point_ = lc->decimal_point[0];
            }
    #endif
        }
        write_double(const write_double&) = default;

        write_double& operator=(const write_double&) = default;

        template<class Result>
        std::size_t operator()(double val, Result& result)
        {
            std::size_t count = 0;

            char number_buffer[200];
            int length = 0;

            switch (float_format_)
            {
            case float_chars_format::fixed:
                {
                    if (precision_ > 0)
                    {
                        length = snprintf(number_buffer, sizeof(number_buffer), "%1.*f", precision_, val);
                        if (length < 0)
                        {
                            JSONCONS_THROW(json_runtime_error<std::invalid_argument>("write_double failed."));
                        }
                        dump_buffer(number_buffer, length, decimal_point_, result);
                    }
                    else
                    {
                        if (!dtoa_fixed(val, decimal_point_, result))
                        {
                            JSONCONS_THROW(json_runtime_error<std::invalid_argument>("write_double failed."));
                        }
                    }
                }
                break;
            case float_chars_format::scientific:
                {
                    if (precision_ > 0)
                    {
                        length = snprintf(number_buffer, sizeof(number_buffer), "%1.*e", precision_, val);
                        if (length < 0)
                        {
                            JSONCONS_THROW(json_runtime_error<std::invalid_argument>("write_double failed."));
                        }
                        dump_buffer(number_buffer, length, decimal_point_, result);
                    }
                    else
                    {
                        if (!dtoa_scientific(val, decimal_point_, result))
                        {
                            JSONCONS_THROW(json_runtime_error<std::invalid_argument>("write_double failed."));
                        }
                    }
                }
                break;
            case float_chars_format::general:
                {
                    if (precision_ > 0)
                    {
                        length = snprintf(number_buffer, sizeof(number_buffer), "%1.*g", precision_, val);
                        if (length < 0)
                        {
                            JSONCONS_THROW(json_runtime_error<std::invalid_argument>("write_double failed."));
                        }
                        dump_buffer(number_buffer, length, decimal_point_, result);
                    }
                    else
                    {
                        if (!dtoa_general(val, decimal_point_, result))
                        {
                            JSONCONS_THROW(json_runtime_error<std::invalid_argument>("write_double failed."));
                        }
                    }             
                    break;
                }
                default:
                    JSONCONS_THROW(json_runtime_error<std::invalid_argument>("write_double failed."));
                    break;
            }
            return count;
        }
    };

} // namespace detail
} // namespace jsoncons

#endif