Coverage Report

Created: 2024-11-21 07:03

/src/mpdecimal-4.0.0/libmpdec/io.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2008-2024 Stefan Krah. All rights reserved.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 *
8
 * 1. Redistributions of source code must retain the above copyright
9
 *    notice, this list of conditions and the following disclaimer.
10
 * 2. Redistributions in binary form must reproduce the above copyright
11
 *    notice, this list of conditions and the following disclaimer in the
12
 *    documentation and/or other materials provided with the distribution.
13
 *
14
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24
 * SUCH DAMAGE.
25
 */
26
27
28
#include <assert.h>
29
#include <ctype.h>
30
#include <errno.h>
31
#include <limits.h>
32
#include <locale.h>
33
#include <stdio.h>
34
#include <stdlib.h>
35
#include <string.h>
36
37
#include "io.h"
38
#include "mpdecimal.h"
39
#include "typearith.h"
40
41
42
/* This file contains functions for decimal <-> string conversions, including
43
   PEP-3101 formatting for numeric types. */
44
45
46
#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && __GNUC__ >= 7
47
  #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
48
  #pragma GCC diagnostic ignored "-Wmisleading-indentation"
49
  #pragma GCC diagnostic ignored "-Warray-bounds"
50
#endif
51
52
53
/*
54
 * Work around the behavior of tolower() and strcasecmp() in certain
55
 * locales. For example, in tr_TR.utf8:
56
 *
57
 * tolower((unsigned char)'I') == 'I'
58
 *
59
 * u is the exact uppercase version of l; n is strlen(l) or strlen(l)+1
60
 */
61
static inline int
62
_mpd_strneq(const char *s, const char *l, const char *u, size_t n)
63
193k
{
64
193k
    while (--n != SIZE_MAX) {
65
193k
        if (*s != *l && *s != *u) {
66
193k
            return 0;
67
193k
        }
68
0
        s++; u++; l++;
69
0
    }
70
71
0
    return 1;
72
193k
}
73
74
static mpd_ssize_t
75
strtoexp(const char *s)
76
0
{
77
0
    char *end;
78
0
    mpd_ssize_t retval;
79
80
0
    errno = 0;
81
0
    retval = mpd_strtossize(s, &end, 10);
82
0
    if (errno == 0 && !(*s != '\0' && *end == '\0'))
83
0
        errno = EINVAL;
84
85
0
    return retval;
86
0
}
87
88
/*
89
 * Scan 'len' words. The most significant word contains 'r' digits,
90
 * the remaining words are full words. Skip dpoint. The string 's' must
91
 * consist of digits and an optional single decimal point at 'dpoint'.
92
 */
93
static void
94
string_to_coeff(mpd_uint_t *data, const char *s, const char *dpoint, int r,
95
                size_t len)
96
64.6k
{
97
64.6k
    int j;
98
99
64.6k
    if (r > 0) {
100
62.7k
        data[--len] = 0;
101
329k
        for (j = 0; j < r; j++, s++) {
102
267k
            if (s == dpoint) s++;
103
267k
            data[len] = 10 * data[len] + (*s - '0');
104
267k
        }
105
62.7k
    }
106
107
726k
    while (--len != SIZE_MAX) {
108
661k
        data[len] = 0;
109
13.2M
        for (j = 0; j < MPD_RDIGITS; j++, s++) {
110
12.5M
            if (s == dpoint) s++;
111
12.5M
            data[len] = 10 * data[len] + (*s - '0');
112
12.5M
        }
113
661k
    }
114
64.6k
}
115
116
/*
117
 * Partially verify a numeric string of the form:
118
 *
119
 *     [cdigits][.][cdigits][eE][+-][edigits]
120
 *
121
 * If successful, return a pointer to the location of the first
122
 * relevant coefficient digit. This digit is either non-zero or
123
 * part of one of the following patterns:
124
 *
125
 *     ["0\x00", "0.\x00", "0.E", "0.e", "0E", "0e"]
126
 *
127
 * The locations of a single optional dot or indicator are stored
128
 * in 'dpoint' and 'exp'.
129
 *
130
 * The end of the string is stored in 'end'. If an indicator [eE]
131
 * occurs without trailing [edigits], the condition is caught
132
 * later by strtoexp().
133
 */
134
static const char *
135
scan_dpoint_exp(const char *s, const char **dpoint, const char **exp,
136
                const char **end)
137
64.6k
{
138
64.6k
    const char *coeff = NULL;
139
140
64.6k
    *dpoint = NULL;
141
64.6k
    *exp = NULL;
142
12.9M
    for (; *s != '\0'; s++) {
143
12.8M
        switch (*s) {
144
0
        case '.':
145
0
            if (*dpoint != NULL || *exp != NULL)
146
0
                return NULL;
147
0
            *dpoint = s;
148
0
            break;
149
0
        case 'E': case 'e':
150
0
            if (*exp != NULL)
151
0
                return NULL;
152
0
            *exp = s;
153
0
            if (*(s+1) == '+' || *(s+1) == '-')
154
0
                s++;
155
0
            break;
156
12.8M
        default:
157
12.8M
            if (!isdigit((unsigned char)*s))
158
0
                return NULL;
159
12.8M
            if (coeff == NULL && *exp == NULL) {
160
93.3k
                if (*s == '0') {
161
57.4k
                    if (!isdigit((unsigned char)*(s+1)))
162
28.6k
                        if (!(*(s+1) == '.' &&
163
28.6k
                              isdigit((unsigned char)*(s+2))))
164
28.6k
                            coeff = s;
165
57.4k
                }
166
35.9k
                else {
167
35.9k
                    coeff = s;
168
35.9k
                }
169
93.3k
            }
170
12.8M
            break;
171
172
12.8M
        }
173
12.8M
    }
174
175
64.6k
    *end = s;
176
64.6k
    return coeff;
177
64.6k
}
178
179
/* scan the payload of a NaN */
180
static const char *
181
scan_payload(const char *s, const char **end)
182
0
{
183
0
    const char *coeff;
184
185
0
    while (*s == '0')
186
0
        s++;
187
0
    coeff = s;
188
189
0
    while (isdigit((unsigned char)*s))
190
0
        s++;
191
0
    *end = s;
192
193
0
    return (*s == '\0') ? coeff : NULL;
194
0
}
195
196
/* convert a character string to a decimal */
197
void
198
mpd_qset_string(mpd_t *dec, const char *s, const mpd_context_t *ctx,
199
                uint32_t *status)
200
64.6k
{
201
64.6k
    mpd_ssize_t q, r, len;
202
64.6k
    const char *coeff, *end;
203
64.6k
    const char *dpoint = NULL, *exp = NULL;
204
64.6k
    size_t digits;
205
64.6k
    uint8_t sign = MPD_POS;
206
207
64.6k
    mpd_set_flags(dec, 0);
208
64.6k
    dec->len = 0;
209
64.6k
    dec->exp = 0;
210
211
    /* sign */
212
64.6k
    if (*s == '+') {
213
0
        s++;
214
0
    }
215
64.6k
    else if (*s == '-') {
216
0
        mpd_set_negative(dec);
217
0
        sign = MPD_NEG;
218
0
        s++;
219
0
    }
220
221
64.6k
    if (_mpd_strneq(s, "nan", "NAN", 3)) { /* NaN */
222
0
        s += 3;
223
0
        mpd_setspecial(dec, sign, MPD_NAN);
224
0
        if (*s == '\0')
225
0
            return;
226
        /* validate payload: digits only */
227
0
        if ((coeff = scan_payload(s, &end)) == NULL)
228
0
            goto conversion_error;
229
        /* payload consists entirely of zeros */
230
0
        if (*coeff == '\0')
231
0
            return;
232
0
        digits = end - coeff;
233
        /* prec >= 1, clamp is 0 or 1 */
234
0
        if (digits > (size_t)(ctx->prec-ctx->clamp))
235
0
            goto conversion_error;
236
0
    } /* sNaN */
237
64.6k
    else if (_mpd_strneq(s, "snan", "SNAN", 4)) {
238
0
        s += 4;
239
0
        mpd_setspecial(dec, sign, MPD_SNAN);
240
0
        if (*s == '\0')
241
0
            return;
242
        /* validate payload: digits only */
243
0
        if ((coeff = scan_payload(s, &end)) == NULL)
244
0
            goto conversion_error;
245
        /* payload consists entirely of zeros */
246
0
        if (*coeff == '\0')
247
0
            return;
248
0
        digits = end - coeff;
249
0
        if (digits > (size_t)(ctx->prec-ctx->clamp))
250
0
            goto conversion_error;
251
0
    }
252
64.6k
    else if (_mpd_strneq(s, "inf", "INF", 3)) {
253
0
        s += 3;
254
0
        if (*s == '\0' || _mpd_strneq(s, "inity", "INITY", 6)) {
255
            /* numeric-value: infinity */
256
0
            mpd_setspecial(dec, sign, MPD_INF);
257
0
            return;
258
0
        }
259
0
        goto conversion_error;
260
0
    }
261
64.6k
    else {
262
        /* scan for start of coefficient, decimal point, indicator, end */
263
64.6k
        if ((coeff = scan_dpoint_exp(s, &dpoint, &exp, &end)) == NULL)
264
0
            goto conversion_error;
265
266
        /* numeric-value: [exponent-part] */
267
64.6k
        if (exp) {
268
            /* exponent-part */
269
0
            end = exp; exp++;
270
0
            dec->exp = strtoexp(exp);
271
0
            if (errno) {
272
0
                if (!(errno == ERANGE &&
273
0
                     (dec->exp == MPD_SSIZE_MAX ||
274
0
                      dec->exp == MPD_SSIZE_MIN)))
275
0
                    goto conversion_error;
276
0
            }
277
0
        }
278
279
64.6k
        digits = end - coeff;
280
64.6k
        if (dpoint) {
281
0
            size_t fracdigits = end-dpoint-1;
282
0
            if (dpoint > coeff) digits--;
283
284
0
            if (fracdigits > MPD_MAX_PREC) {
285
0
                goto conversion_error;
286
0
            }
287
0
            if (dec->exp < MPD_SSIZE_MIN+(mpd_ssize_t)fracdigits) {
288
0
                dec->exp = MPD_SSIZE_MIN;
289
0
            }
290
0
            else {
291
0
                dec->exp -= (mpd_ssize_t)fracdigits;
292
0
            }
293
0
        }
294
64.6k
        if (digits > MPD_MAX_PREC) {
295
0
            goto conversion_error;
296
0
        }
297
64.6k
        if (dec->exp > MPD_EXP_INF) {
298
0
            dec->exp = MPD_EXP_INF;
299
0
        }
300
64.6k
        if (dec->exp == MPD_SSIZE_MIN) {
301
0
            dec->exp = MPD_SSIZE_MIN+1;
302
0
        }
303
64.6k
    }
304
305
64.6k
    _mpd_idiv_word(&q, &r, (mpd_ssize_t)digits, MPD_RDIGITS);
306
307
64.6k
    len = (r == 0) ? q : q+1;
308
64.6k
    if (len == 0) {
309
0
        goto conversion_error; /* GCOV_NOT_REACHED */
310
0
    }
311
64.6k
    if (!mpd_qresize(dec, len, status)) {
312
0
        mpd_seterror(dec, MPD_Malloc_error, status);
313
0
        return;
314
0
    }
315
64.6k
    dec->len = len;
316
317
64.6k
    string_to_coeff(dec->data, coeff, dpoint, (int)r, len);
318
319
64.6k
    mpd_setdigits(dec);
320
64.6k
    mpd_qfinalize(dec, ctx, status);
321
64.6k
    return;
322
323
0
conversion_error:
324
    /* standard wants a positive NaN */
325
0
    mpd_seterror(dec, MPD_Conversion_syntax, status);
326
0
}
327
328
/* convert a character string to a decimal, use a maxcontext for conversion */
329
void
330
mpd_qset_string_exact(mpd_t *dec, const char *s, uint32_t *status)
331
0
{
332
0
    mpd_context_t maxcontext;
333
0
    uint32_t workstatus = 0;
334
335
0
    mpd_maxcontext(&maxcontext);
336
0
    mpd_qset_string(dec, s, &maxcontext, &workstatus);
337
338
0
    if (workstatus & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
339
        /* we want exact results */
340
0
        mpd_seterror(dec, MPD_Invalid_operation, status);
341
0
    }
342
0
    *status |= (workstatus&MPD_Errors);
343
0
}
344
345
/* Print word x with n decimal digits to string s. dot is either NULL
346
   or the location of a decimal point. */
347
#define EXTRACT_DIGIT(s, x, d, dot) \
348
1.55M
        if (s == dot) *s++ = '.'; *s++ = '0' + (char)(x / d); x %= d
349
static inline char *
350
word_to_string(char *s, mpd_uint_t x, int n, char *dot)
351
88.9k
{
352
88.9k
    switch(n) {
353
0
#ifdef CONFIG_64
354
0
    case 20: EXTRACT_DIGIT(s, x, 10000000000000000000ULL, dot); /* GCOV_NOT_REACHED */
355
84.7k
    case 19: EXTRACT_DIGIT(s, x, 1000000000000000000ULL, dot);
356
84.9k
    case 18: EXTRACT_DIGIT(s, x, 100000000000000000ULL, dot);
357
85.0k
    case 17: EXTRACT_DIGIT(s, x, 10000000000000000ULL, dot);
358
85.1k
    case 16: EXTRACT_DIGIT(s, x, 1000000000000000ULL, dot);
359
85.2k
    case 15: EXTRACT_DIGIT(s, x, 100000000000000ULL, dot);
360
85.3k
    case 14: EXTRACT_DIGIT(s, x, 10000000000000ULL, dot);
361
85.5k
    case 13: EXTRACT_DIGIT(s, x, 1000000000000ULL, dot);
362
85.6k
    case 12: EXTRACT_DIGIT(s, x, 100000000000ULL, dot);
363
85.8k
    case 11: EXTRACT_DIGIT(s, x, 10000000000ULL, dot);
364
85.8k
#endif
365
85.9k
    case 10: EXTRACT_DIGIT(s, x, 1000000000UL, dot);
366
86.5k
    case 9:  EXTRACT_DIGIT(s, x, 100000000UL, dot);
367
86.7k
    case 8:  EXTRACT_DIGIT(s, x, 10000000UL, dot);
368
86.9k
    case 7:  EXTRACT_DIGIT(s, x, 1000000UL, dot);
369
87.0k
    case 6:  EXTRACT_DIGIT(s, x, 100000UL, dot);
370
87.2k
    case 5:  EXTRACT_DIGIT(s, x, 10000UL, dot);
371
87.4k
    case 4:  EXTRACT_DIGIT(s, x, 1000UL, dot);
372
87.7k
    case 3:  EXTRACT_DIGIT(s, x, 100UL, dot);
373
88.0k
    case 2:  EXTRACT_DIGIT(s, x, 10UL, dot);
374
88.9k
    default: if (s == dot) *s++ = '.'; *s++ = '0' + (char)x;
375
88.9k
    }
376
377
88.9k
    *s = '\0';
378
88.9k
    return s;
379
88.9k
}
380
381
/* Print exponent x to string s. Undefined for MPD_SSIZE_MIN. */
382
static inline char *
383
exp_to_string(char *s, mpd_ssize_t x)
384
0
{
385
0
    char sign = '+';
386
387
0
    if (x < 0) {
388
0
        sign = '-';
389
0
        x = -x;
390
0
    }
391
0
    *s++ = sign;
392
393
0
    return word_to_string(s, x, mpd_word_digits(x), NULL);
394
0
}
395
396
/* Print the coefficient of dec to string s. len(dec) > 0. */
397
static inline char *
398
coeff_to_string(char *s, const mpd_t *dec)
399
4.32k
{
400
4.32k
    mpd_uint_t x;
401
4.32k
    mpd_ssize_t i;
402
403
    /* most significant word */
404
4.32k
    x = mpd_msword(dec);
405
4.32k
    s = word_to_string(s, x, mpd_word_digits(x), NULL);
406
407
    /* remaining full words */
408
88.3k
    for (i=dec->len-2; i >= 0; --i) {
409
83.9k
        x = dec->data[i];
410
83.9k
        s = word_to_string(s, x, MPD_RDIGITS, NULL);
411
83.9k
    }
412
413
4.32k
    return s;
414
4.32k
}
415
416
/* Print the coefficient of dec to string s. len(dec) > 0. dot is either
417
   NULL or a pointer to the location of a decimal point. */
418
static inline char *
419
coeff_to_string_dot(char *s, char *dot, const mpd_t *dec)
420
23
{
421
23
    mpd_uint_t x;
422
23
    mpd_ssize_t i;
423
424
    /* most significant word */
425
23
    x = mpd_msword(dec);
426
23
    s = word_to_string(s, x, mpd_word_digits(x), dot);
427
428
    /* remaining full words */
429
593
    for (i=dec->len-2; i >= 0; --i) {
430
570
        x = dec->data[i];
431
570
        s = word_to_string(s, x, MPD_RDIGITS, dot);
432
570
    }
433
434
23
    return s;
435
23
}
436
437
/* Format type */
438
0
#define MPD_FMT_LOWER       0x00000000
439
0
#define MPD_FMT_UPPER       0x00000001
440
0
#define MPD_FMT_TOSCI       0x00000002
441
0
#define MPD_FMT_TOENG       0x00000004
442
8.70k
#define MPD_FMT_EXP         0x00000008
443
13.0k
#define MPD_FMT_FIXED       0x00000010
444
4.35k
#define MPD_FMT_PERCENT     0x00000020
445
4.18k
#define MPD_FMT_SIGN_SPACE  0x00000040
446
4.18k
#define MPD_FMT_SIGN_PLUS   0x00000080
447
340
#define MPD_FMT_SIGN_COERCE 0x00000100
448
449
/* Default place of the decimal point for MPD_FMT_TOSCI, MPD_FMT_EXP */
450
4.35k
#define MPD_DEFAULT_DOTPLACE 1
451
452
/*
453
 * Set *result to the string representation of a decimal. Return the length
454
 * of *result, not including the terminating '\0' character.
455
 *
456
 * Formatting is done according to 'flags'. A return value of -1 with *result
457
 * set to NULL indicates MPD_Malloc_error.
458
 *
459
 * 'dplace' is the default place of the decimal point. It is always set to
460
 * MPD_DEFAULT_DOTPLACE except for zeros in combination with MPD_FMT_EXP.
461
 */
462
static mpd_ssize_t
463
_mpd_to_string(char **result, const mpd_t *dec, int flags, mpd_ssize_t dplace)
464
4.35k
{
465
4.35k
    char *decstring = NULL, *cp = NULL;
466
4.35k
    mpd_ssize_t ldigits;
467
4.35k
    mpd_ssize_t mem = 0, k;
468
469
4.35k
    if (mpd_isspecial(dec)) {
470
471
0
        mem = sizeof "-Infinity%";
472
0
        if (mpd_isnan(dec) && dec->len > 0) {
473
            /* diagnostic code */
474
0
            mem += dec->digits;
475
0
        }
476
0
        cp = decstring = mpd_alloc(mem, sizeof *decstring);
477
0
        if (cp == NULL) {
478
0
            *result = NULL;
479
0
            return -1;
480
0
        }
481
482
0
        if (mpd_isnegative(dec)) {
483
0
            *cp++ = '-';
484
0
        }
485
0
        else if (flags&MPD_FMT_SIGN_SPACE) {
486
0
            *cp++ = ' ';
487
0
        }
488
0
        else if (flags&MPD_FMT_SIGN_PLUS) {
489
0
            *cp++ = '+';
490
0
        }
491
492
0
        if (mpd_isnan(dec)) {
493
0
            if (mpd_isqnan(dec)) {
494
0
                strcpy(cp, "NaN");
495
0
                cp += 3;
496
0
            }
497
0
            else {
498
0
                strcpy(cp, "sNaN");
499
0
                cp += 4;
500
0
            }
501
0
            if (dec->len > 0) { /* diagnostic code */
502
0
                cp = coeff_to_string(cp, dec);
503
0
            }
504
0
        }
505
0
        else if (mpd_isinfinite(dec)) {
506
0
            strcpy(cp, "Infinity");
507
0
            cp += 8;
508
0
        }
509
0
        else { /* debug */
510
0
            abort(); /* GCOV_NOT_REACHED */
511
0
        }
512
0
    }
513
4.35k
    else {
514
4.35k
        assert(dec->len > 0);
515
516
        /*
517
         * For easier manipulation of the decimal point's location
518
         * and the exponent that is finally printed, the number is
519
         * rescaled to a virtual representation with exp = 0. Here
520
         * ldigits denotes the number of decimal digits to the left
521
         * of the decimal point and remains constant once initialized.
522
         *
523
         * dplace is the location of the decimal point relative to
524
         * the start of the coefficient. Note that 3) always holds
525
         * when dplace is shifted.
526
         *
527
         *   1) ldigits := dec->digits - dec->exp
528
         *   2) dplace  := ldigits            (initially)
529
         *   3) exp     := ldigits - dplace   (initially exp = 0)
530
         *
531
         *   0.00000_.____._____000000.
532
         *    ^      ^    ^           ^
533
         *    |      |    |           |
534
         *    |      |    |           `- dplace >= digits
535
         *    |      |    `- dplace in the middle of the coefficient
536
         *    |      ` dplace = 1 (after the first coefficient digit)
537
         *    `- dplace <= 0
538
         */
539
540
4.35k
        ldigits = dec->digits + dec->exp;
541
542
4.35k
        if (flags&MPD_FMT_EXP) {
543
0
            ;
544
0
        }
545
4.35k
        else if (flags&MPD_FMT_FIXED || (dec->exp <= 0 && ldigits > -6)) {
546
            /* MPD_FMT_FIXED: always use fixed point notation.
547
             * MPD_FMT_TOSCI, MPD_FMT_TOENG: for a certain range,
548
             * override exponent notation. */
549
4.35k
            dplace = ldigits;
550
4.35k
        }
551
0
        else if (flags&MPD_FMT_TOENG) {
552
0
            if (mpd_iszero(dec)) {
553
                /* If the exponent is divisible by three,
554
                 * dplace = 1. Otherwise, move dplace one
555
                 * or two places to the left. */
556
0
                dplace = -1 + mod_mpd_ssize_t(dec->exp+2, 3);
557
0
            }
558
0
            else { /* ldigits-1 is the adjusted exponent, which
559
                    * should be divisible by three. If not, move
560
                    * dplace one or two places to the right. */
561
0
                dplace += mod_mpd_ssize_t(ldigits-1, 3);
562
0
            }
563
0
        }
564
565
        /*
566
         * Basic space requirements:
567
         *
568
         * [-][.][coeffdigits][E][-][expdigits+1][%]['\0']
569
         *
570
         * If the decimal point lies outside of the coefficient digits,
571
         * space is adjusted accordingly.
572
         */
573
4.35k
        if (dplace <= 0) {
574
1
            mem = -dplace + dec->digits + 2;
575
1
        }
576
4.35k
        else if (dplace >= dec->digits) {
577
4.32k
            mem = dplace;
578
4.32k
        }
579
23
        else {
580
23
            mem = dec->digits;
581
23
        }
582
4.35k
        mem += (MPD_EXPDIGITS+1+6);
583
584
4.35k
        cp = decstring = mpd_alloc(mem, sizeof *decstring);
585
4.35k
        if (cp == NULL) {
586
0
            *result = NULL;
587
0
            return -1;
588
0
        }
589
590
591
4.35k
        if (mpd_isnegative(dec) && !(flags&MPD_FMT_SIGN_COERCE && mpd_iszero(dec))) {
592
170
            *cp++ = '-';
593
170
        }
594
4.18k
        else if (flags&MPD_FMT_SIGN_SPACE) {
595
0
            *cp++ = ' ';
596
0
        }
597
4.18k
        else if (flags&MPD_FMT_SIGN_PLUS) {
598
0
            *cp++ = '+';
599
0
        }
600
601
4.35k
        if (dplace <= 0) {
602
            /* space: -dplace+dec->digits+2 */
603
1
            *cp++ = '0';
604
1
            *cp++ = '.';
605
184
            for (k = 0; k < -dplace; k++) {
606
183
                *cp++ = '0';
607
183
            }
608
1
            cp = coeff_to_string(cp, dec);
609
1
        }
610
4.35k
        else if (dplace >= dec->digits) {
611
            /* space: dplace */
612
4.32k
            cp = coeff_to_string(cp, dec);
613
4.32k
            for (k = 0; k < dplace-dec->digits; k++) {
614
0
                *cp++ = '0';
615
0
            }
616
4.32k
        }
617
23
        else {
618
            /* space: dec->digits+1 */
619
23
            cp = coeff_to_string_dot(cp, cp+dplace, dec);
620
23
        }
621
622
        /*
623
         * Conditions for printing an exponent:
624
         *
625
         *   MPD_FMT_TOSCI, MPD_FMT_TOENG: only if ldigits != dplace
626
         *   MPD_FMT_FIXED:                never (ldigits == dplace)
627
         *   MPD_FMT_EXP:                  always
628
         */
629
4.35k
        if (ldigits != dplace || flags&MPD_FMT_EXP) {
630
            /* space: expdigits+2 */
631
0
            *cp++ = (flags&MPD_FMT_UPPER) ? 'E' : 'e';
632
0
            cp = exp_to_string(cp, ldigits-dplace);
633
0
        }
634
4.35k
    }
635
636
4.35k
    if (flags&MPD_FMT_PERCENT) {
637
0
        *cp++ = '%';
638
0
    }
639
640
4.35k
    assert(cp < decstring+mem);
641
4.35k
    assert(cp-decstring < MPD_SSIZE_MAX);
642
643
4.35k
    *cp = '\0';
644
4.35k
    *result = decstring;
645
4.35k
    return (mpd_ssize_t)(cp-decstring);
646
4.35k
}
647
648
char *
649
mpd_to_sci(const mpd_t *dec, int fmt)
650
0
{
651
0
    char *res;
652
0
    int flags = MPD_FMT_TOSCI;
653
654
0
    flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
655
0
    (void)_mpd_to_string(&res, dec, flags, MPD_DEFAULT_DOTPLACE);
656
0
    return res;
657
0
}
658
659
char *
660
mpd_to_eng(const mpd_t *dec, int fmt)
661
0
{
662
0
    char *res;
663
0
    int flags = MPD_FMT_TOENG;
664
665
0
    flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
666
0
    (void)_mpd_to_string(&res, dec, flags, MPD_DEFAULT_DOTPLACE);
667
0
    return res;
668
0
}
669
670
mpd_ssize_t
671
mpd_to_sci_size(char **res, const mpd_t *dec, int fmt)
672
0
{
673
0
    int flags = MPD_FMT_TOSCI;
674
675
0
    flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
676
0
    return _mpd_to_string(res, dec, flags, MPD_DEFAULT_DOTPLACE);
677
0
}
678
679
mpd_ssize_t
680
mpd_to_eng_size(char **res, const mpd_t *dec, int fmt)
681
0
{
682
0
    int flags = MPD_FMT_TOENG;
683
684
0
    flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
685
0
    return _mpd_to_string(res, dec, flags, MPD_DEFAULT_DOTPLACE);
686
0
}
687
688
/* Copy a single UTF-8 char to dest. See: The Unicode Standard, version 5.2,
689
   chapter 3.9: Well-formed UTF-8 byte sequences. */
690
static int
691
_mpd_copy_utf8(char dest[5], const char *s)
692
4.35k
{
693
4.35k
    const unsigned char *cp = (const unsigned char *)s;
694
4.35k
    unsigned char lb, ub;
695
4.35k
    int count, i;
696
697
698
4.35k
    if (*cp == 0) {
699
        /* empty string */
700
0
        dest[0] = '\0';
701
0
        return 0;
702
0
    }
703
4.35k
    else if (*cp <= 0x7f) {
704
        /* ascii */
705
4.35k
        dest[0] = *cp;
706
4.35k
        dest[1] = '\0';
707
4.35k
        return 1;
708
4.35k
    }
709
0
    else if (0xc2 <= *cp && *cp <= 0xdf) {
710
0
        lb = 0x80; ub = 0xbf;
711
0
        count = 2;
712
0
    }
713
0
    else if (*cp == 0xe0) {
714
0
        lb = 0xa0; ub = 0xbf;
715
0
        count = 3;
716
0
    }
717
0
    else if (*cp <= 0xec) {
718
0
        lb = 0x80; ub = 0xbf;
719
0
        count = 3;
720
0
    }
721
0
    else if (*cp == 0xed) {
722
0
        lb = 0x80; ub = 0x9f;
723
0
        count = 3;
724
0
    }
725
0
    else if (*cp <= 0xef) {
726
0
        lb = 0x80; ub = 0xbf;
727
0
        count = 3;
728
0
    }
729
0
    else if (*cp == 0xf0) {
730
0
        lb = 0x90; ub = 0xbf;
731
0
        count = 4;
732
0
    }
733
0
    else if (*cp <= 0xf3) {
734
0
        lb = 0x80; ub = 0xbf;
735
0
        count = 4;
736
0
    }
737
0
    else if (*cp == 0xf4) {
738
0
        lb = 0x80; ub = 0x8f;
739
0
        count = 4;
740
0
    }
741
0
    else {
742
        /* invalid */
743
0
        goto error;
744
0
    }
745
746
0
    dest[0] = (char)*cp++;
747
0
    if (*cp < lb || ub < *cp) {
748
0
        goto error;
749
0
    }
750
0
    dest[1] = (char)*cp++;
751
0
    for (i = 2; i < count; i++) {
752
0
        if (*cp < 0x80 || 0xbf < *cp) {
753
0
            goto error;
754
0
        }
755
0
        dest[i] = (char)*cp++;
756
0
    }
757
0
    dest[i] = '\0';
758
759
0
    return count;
760
761
0
error:
762
0
    dest[0] = '\0';
763
0
    return -1;
764
0
}
765
766
int
767
mpd_validate_lconv(mpd_spec_t *spec)
768
0
{
769
0
    size_t n;
770
0
#if CHAR_MAX == SCHAR_MAX
771
0
    const char *cp = spec->grouping;
772
0
    while (*cp != '\0') {
773
0
        if (*cp++ < 0) {
774
0
            return -1;
775
0
        }
776
0
    }
777
0
#endif
778
0
    n = strlen(spec->dot);
779
0
    if (n == 0 || n > 4) {
780
0
        return -1;
781
0
    }
782
0
    if (strlen(spec->sep) > 4) {
783
0
        return -1;
784
0
    }
785
786
0
    return 0;
787
0
}
788
789
int
790
mpd_parse_fmt_str(mpd_spec_t *spec, const char *fmt, int caps)
791
4.35k
{
792
4.35k
    char *cp = (char *)fmt;
793
4.35k
    int have_align = 0, n;
794
795
    /* defaults */
796
4.35k
    spec->min_width = 0;
797
4.35k
    spec->prec = -1;
798
4.35k
    spec->type = caps ? 'G' : 'g';
799
4.35k
    spec->align = '>';
800
4.35k
    spec->sign = '-';
801
4.35k
    spec->sign_coerce = 0;
802
4.35k
    spec->dot = "";
803
4.35k
    spec->sep = "";
804
4.35k
    spec->grouping = "";
805
806
807
    /* presume that the first character is a UTF-8 fill character */
808
4.35k
    if ((n = _mpd_copy_utf8(spec->fill, cp)) < 0) {
809
0
        return 0;
810
0
    }
811
812
    /* alignment directive, prefixed by a fill character */
813
4.35k
    if (*cp && (*(cp+n) == '<' || *(cp+n) == '>' ||
814
4.35k
                *(cp+n) == '=' || *(cp+n) == '^')) {
815
0
        cp += n;
816
0
        spec->align = *cp++;
817
0
        have_align = 1;
818
0
    } /* alignment directive */
819
4.35k
    else {
820
        /* default fill character */
821
4.35k
        spec->fill[0] = ' ';
822
4.35k
        spec->fill[1] = '\0';
823
4.35k
        if (*cp == '<' || *cp == '>' ||
824
4.35k
            *cp == '=' || *cp == '^') {
825
0
            spec->align = *cp++;
826
0
            have_align = 1;
827
0
        }
828
4.35k
    }
829
830
    /* sign formatting */
831
4.35k
    if (*cp == '+' || *cp == '-' || *cp == ' ') {
832
0
        spec->sign = *cp++;
833
0
    }
834
835
    /* coerce to positive zero */
836
4.35k
    if (*cp == 'z') {
837
0
        spec->sign_coerce = 1;
838
0
        cp++;
839
0
    }
840
841
    /* zero padding */
842
4.35k
    if (*cp == '0') {
843
        /* zero padding implies alignment, which should not be
844
         * specified twice. */
845
0
        if (have_align) {
846
0
            return 0;
847
0
        }
848
0
        spec->align = 'z';
849
0
        spec->fill[0] = *cp++;
850
0
        spec->fill[1] = '\0';
851
0
    }
852
853
    /* minimum width */
854
4.35k
    if (isdigit((unsigned char)*cp)) {
855
0
        if (*cp == '0') {
856
0
            return 0;
857
0
        }
858
0
        errno = 0;
859
0
        spec->min_width = mpd_strtossize(cp, &cp, 10);
860
0
        if (errno == ERANGE || errno == EINVAL) {
861
0
            return 0;
862
0
        }
863
0
    }
864
865
    /* thousands separator */
866
4.35k
    if (*cp == ',') {
867
0
        spec->dot = ".";
868
0
        spec->sep = ",";
869
0
        spec->grouping = "\003\003";
870
0
        cp++;
871
0
    }
872
873
    /* fraction digits or significant digits */
874
4.35k
    if (*cp == '.') {
875
0
        cp++;
876
0
        if (!isdigit((unsigned char)*cp)) {
877
0
            return 0;
878
0
        }
879
0
        errno = 0;
880
0
        spec->prec = mpd_strtossize(cp, &cp, 10);
881
0
        if (errno == ERANGE || errno == EINVAL) {
882
0
            return 0;
883
0
        }
884
0
    }
885
886
    /* type */
887
4.35k
    if (*cp == 'E' || *cp == 'e' || *cp == 'F' || *cp == 'f' ||
888
4.35k
        *cp == 'G' || *cp == 'g' || *cp == '%') {
889
4.35k
        spec->type = *cp++;
890
4.35k
    }
891
0
    else if (*cp == 'N' || *cp == 'n') {
892
        /* locale specific conversion */
893
0
        struct lconv *lc;
894
        /* separator has already been specified */
895
0
        if (*spec->sep) {
896
0
            return 0;
897
0
        }
898
0
        spec->type = *cp++;
899
0
        spec->type = (spec->type == 'N') ? 'G' : 'g';
900
0
        lc = localeconv();
901
0
        spec->dot = lc->decimal_point;
902
0
        spec->sep = lc->thousands_sep;
903
0
        spec->grouping = lc->grouping;
904
0
        if (mpd_validate_lconv(spec) < 0) {
905
0
            return 0; /* GCOV_NOT_REACHED */
906
0
        }
907
0
    }
908
909
    /* check correctness */
910
4.35k
    if (*cp != '\0') {
911
0
        return 0;
912
0
    }
913
914
4.35k
    return 1;
915
4.35k
}
916
917
/*
918
 * The following functions assume that spec->min_width <= MPD_MAX_PREC, which
919
 * is made sure in mpd_qformat_spec. Then, even with a spec that inserts a
920
 * four-byte separator after each digit, nbytes in the following struct
921
 * cannot overflow.
922
 */
923
924
/* Multibyte string */
925
typedef struct {
926
    mpd_ssize_t nbytes; /* length in bytes */
927
    mpd_ssize_t nchars; /* length in chars */
928
    mpd_ssize_t cur;    /* current write index */
929
    char *data;
930
} mpd_mbstr_t;
931
932
static inline void
933
_mpd_bcopy(char *dest, const char *src, mpd_ssize_t n)
934
0
{
935
0
    while (--n >= 0) {
936
0
        dest[n] = src[n];
937
0
    }
938
0
}
939
940
static inline void
941
_mbstr_copy_char(mpd_mbstr_t *dest, const char *src, mpd_ssize_t n)
942
0
{
943
0
    dest->nbytes += n;
944
0
    dest->nchars += (n > 0 ? 1 : 0);
945
0
    dest->cur -= n;
946
947
0
    if (dest->data != NULL) {
948
0
        _mpd_bcopy(dest->data+dest->cur, src, n);
949
0
    }
950
0
}
951
952
static inline void
953
_mbstr_copy_ascii(mpd_mbstr_t *dest, const char *src, mpd_ssize_t n)
954
0
{
955
0
    dest->nbytes += n;
956
0
    dest->nchars += n;
957
0
    dest->cur -= n;
958
959
0
    if (dest->data != NULL) {
960
0
        _mpd_bcopy(dest->data+dest->cur, src, n);
961
0
    }
962
0
}
963
964
static inline void
965
_mbstr_copy_pad(mpd_mbstr_t *dest, mpd_ssize_t n)
966
0
{
967
0
    dest->nbytes += n;
968
0
    dest->nchars += n;
969
0
    dest->cur -= n;
970
971
0
    if (dest->data != NULL) {
972
0
        char *cp = dest->data + dest->cur;
973
0
        while (--n >= 0) {
974
0
            cp[n] = '0';
975
0
        }
976
0
    }
977
0
}
978
979
/*
980
 * Copy a numeric string to dest->data, adding separators in the integer
981
 * part according to spec->grouping. If leading zero padding is enabled
982
 * and the result is smaller than spec->min_width, continue adding zeros
983
 * and separators until the minimum width is reached.
984
 *
985
 * The final length of dest->data is stored in dest->nbytes. The number
986
 * of UTF-8 characters is stored in dest->nchars.
987
 *
988
 * First run (dest->data == NULL): determine the length of the result
989
 * string and store it in dest->nbytes.
990
 *
991
 * Second run (write to dest->data): data is written in chunks and in
992
 * reverse order, starting with the rest of the numeric string.
993
 */
994
static void
995
_mpd_add_sep_dot(mpd_mbstr_t *dest,
996
                 const char *sign, /* location of optional sign */
997
                 const char *src, mpd_ssize_t n_src, /* integer part and length */
998
                 const char *dot, /* location of optional decimal point */
999
                 const char *rest, mpd_ssize_t n_rest, /* remaining part and length */
1000
                 const mpd_spec_t *spec)
1001
0
{
1002
0
    mpd_ssize_t n_sep, n_sign, consume;
1003
0
    const char *g;
1004
0
    int pad = 0;
1005
1006
0
    n_sign = sign ? 1 : 0;
1007
0
    n_sep = (mpd_ssize_t)strlen(spec->sep);
1008
    /* Initial write index: set to location of '\0' in the output string.
1009
     * Irrelevant for the first run. */
1010
0
    dest->cur = dest->nbytes;
1011
0
    dest->nbytes = dest->nchars = 0;
1012
1013
0
    _mbstr_copy_ascii(dest, rest, n_rest);
1014
1015
0
    if (dot) {
1016
0
        _mbstr_copy_char(dest, dot, (mpd_ssize_t)strlen(dot));
1017
0
    }
1018
1019
0
    g = spec->grouping;
1020
0
    consume = *g;
1021
0
    while (1) {
1022
        /* If the group length is 0 or CHAR_MAX or greater than the
1023
         * number of source bytes, consume all remaining bytes. */
1024
0
        if (*g == 0 || *g == CHAR_MAX || consume > n_src) {
1025
0
            consume = n_src;
1026
0
        }
1027
0
        n_src -= consume;
1028
0
        if (pad) {
1029
0
            _mbstr_copy_pad(dest, consume);
1030
0
        }
1031
0
        else {
1032
0
            _mbstr_copy_ascii(dest, src+n_src, consume);
1033
0
        }
1034
1035
0
        if (n_src == 0) {
1036
            /* Either the real source of intpart digits or the virtual
1037
             * source of padding zeros is exhausted. */
1038
0
            if (spec->align == 'z' &&
1039
0
                dest->nchars + n_sign < spec->min_width) {
1040
                /* Zero padding is set and length < min_width:
1041
                 * Generate n_src additional characters. */
1042
0
                n_src = spec->min_width - (dest->nchars + n_sign);
1043
                /* Next iteration:
1044
                 *   case *g == 0 || *g == CHAR_MAX:
1045
                 *      consume all padding characters
1046
                 *   case consume < g*:
1047
                 *      fill remainder of current group
1048
                 *   case consume == g*
1049
                 *      copying is a no-op */
1050
0
                consume = *g - consume;
1051
                /* Switch on virtual source of zeros. */
1052
0
                pad = 1;
1053
0
                continue;
1054
0
            }
1055
0
            break;
1056
0
        }
1057
1058
0
        if (n_sep > 0) {
1059
            /* If padding is switched on, separators are counted
1060
             * as padding characters. This rule does not apply if
1061
             * the separator would be the first character of the
1062
             * result string. */
1063
0
            if (pad && n_src > 1) n_src -= 1;
1064
0
            _mbstr_copy_char(dest, spec->sep, n_sep);
1065
0
        }
1066
1067
        /* If non-NUL, use the next value for grouping. */
1068
0
        if (*g && *(g+1)) g++;
1069
0
        consume = *g;
1070
0
    }
1071
1072
0
    if (sign) {
1073
0
        _mbstr_copy_ascii(dest, sign, 1);
1074
0
    }
1075
1076
0
    if (dest->data) {
1077
0
        dest->data[dest->nbytes] = '\0';
1078
0
    }
1079
0
}
1080
1081
/*
1082
 * Convert a numeric-string to its locale-specific appearance.
1083
 * The string must have one of these forms:
1084
 *
1085
 *     1) [sign] digits [exponent-part]
1086
 *     2) [sign] digits '.' [digits] [exponent-part]
1087
 *
1088
 * Not allowed, since _mpd_to_string() never returns this form:
1089
 *
1090
 *     3) [sign] '.' digits [exponent-part]
1091
 *
1092
 * Input: result->data := original numeric string (ASCII)
1093
 *        result->bytes := strlen(result->data)
1094
 *        result->nchars := strlen(result->data)
1095
 *
1096
 * Output: result->data := modified or original string
1097
 *         result->bytes := strlen(result->data)
1098
 *         result->nchars := number of characters (possibly UTF-8)
1099
 */
1100
static int
1101
_mpd_apply_lconv(mpd_mbstr_t *result, const mpd_spec_t *spec, uint32_t *status)
1102
0
{
1103
0
    const char *sign = NULL, *intpart = NULL, *dot = NULL;
1104
0
    const char *rest, *dp;
1105
0
    char *decstring;
1106
0
    mpd_ssize_t n_int, n_rest;
1107
1108
    /* original numeric string */
1109
0
    dp = result->data;
1110
1111
    /* sign */
1112
0
    if (*dp == '+' || *dp == '-' || *dp == ' ') {
1113
0
        sign = dp++;
1114
0
    }
1115
    /* integer part */
1116
0
    assert(isdigit((unsigned char)*dp));
1117
0
    intpart = dp++;
1118
0
    while (isdigit((unsigned char)*dp)) {
1119
0
        dp++;
1120
0
    }
1121
0
    n_int = (mpd_ssize_t)(dp-intpart);
1122
    /* decimal point */
1123
0
    if (*dp == '.') {
1124
0
        dp++; dot = spec->dot;
1125
0
    }
1126
    /* rest */
1127
0
    rest = dp;
1128
0
    n_rest = result->nbytes - (mpd_ssize_t)(dp-result->data);
1129
1130
0
    if (dot == NULL && (*spec->sep == '\0' || *spec->grouping == '\0')) {
1131
        /* _mpd_add_sep_dot() would not change anything */
1132
0
        return 1;
1133
0
    }
1134
1135
    /* Determine the size of the new decimal string after inserting the
1136
     * decimal point, optional separators and optional padding. */
1137
0
    decstring = result->data;
1138
0
    result->data = NULL;
1139
0
    _mpd_add_sep_dot(result, sign, intpart, n_int, dot,
1140
0
                     rest, n_rest, spec);
1141
1142
0
    result->data = mpd_alloc(result->nbytes+1, 1);
1143
0
    if (result->data == NULL) {
1144
0
        *status |= MPD_Malloc_error;
1145
0
        mpd_free(decstring);
1146
0
        return 0;
1147
0
    }
1148
1149
    /* Perform actual writes. */
1150
0
    _mpd_add_sep_dot(result, sign, intpart, n_int, dot,
1151
0
                     rest, n_rest, spec);
1152
1153
0
    mpd_free(decstring);
1154
0
    return 1;
1155
0
}
1156
1157
/* Add padding to the formatted string if necessary. */
1158
static int
1159
_mpd_add_pad(mpd_mbstr_t *result, const mpd_spec_t *spec, uint32_t *status)
1160
0
{
1161
0
    if (result->nchars < spec->min_width) {
1162
0
        mpd_ssize_t add_chars, add_bytes;
1163
0
        size_t lpad = 0, rpad = 0;
1164
0
        size_t n_fill, len, i, j;
1165
0
        char align = spec->align;
1166
0
        uint8_t err = 0;
1167
0
        char *cp;
1168
1169
0
        n_fill = strlen(spec->fill);
1170
0
        add_chars = (spec->min_width - result->nchars);
1171
        /* max value: MPD_MAX_PREC * 4 */
1172
0
        add_bytes = add_chars * (mpd_ssize_t)n_fill;
1173
1174
0
        cp = result->data = mpd_realloc(result->data,
1175
0
                                        result->nbytes+add_bytes+1,
1176
0
                                        sizeof *result->data, &err);
1177
0
        if (err) {
1178
0
            *status |= MPD_Malloc_error;
1179
0
            mpd_free(result->data);
1180
0
            return 0;
1181
0
        }
1182
1183
0
        if (align == 'z') {
1184
0
            align = '=';
1185
0
        }
1186
1187
0
        if (align == '<') {
1188
0
            rpad = add_chars;
1189
0
        }
1190
0
        else if (align == '>' || align == '=') {
1191
0
            lpad = add_chars;
1192
0
        }
1193
0
        else { /* align == '^' */
1194
0
            lpad = add_chars/2;
1195
0
            rpad = add_chars-lpad;
1196
0
        }
1197
1198
0
        len = result->nbytes;
1199
0
        if (align == '=' && (*cp == '-' || *cp == '+' || *cp == ' ')) {
1200
            /* leave sign in the leading position */
1201
0
            cp++; len--;
1202
0
        }
1203
1204
0
        memmove(cp+n_fill*lpad, cp, len);
1205
0
        for (i = 0; i < lpad; i++) {
1206
0
            for (j = 0; j < n_fill; j++) {
1207
0
                cp[i*n_fill+j] = spec->fill[j];
1208
0
            }
1209
0
        }
1210
0
        cp += (n_fill*lpad + len);
1211
0
        for (i = 0; i < rpad; i++) {
1212
0
            for (j = 0; j < n_fill; j++) {
1213
0
                cp[i*n_fill+j] = spec->fill[j];
1214
0
            }
1215
0
        }
1216
1217
0
        result->nbytes += add_bytes;
1218
0
        result->nchars += add_chars;
1219
0
        result->data[result->nbytes] = '\0';
1220
0
    }
1221
1222
0
    return 1;
1223
0
}
1224
1225
/* Round a number to prec digits. The adjusted exponent stays the same
1226
   or increases by one if rounding up crosses a power of ten boundary.
1227
   If result->digits would exceed MPD_MAX_PREC+1, MPD_Invalid_operation
1228
   is set and the result is NaN. */
1229
static inline void
1230
_mpd_round(mpd_t *result, const mpd_t *a, mpd_ssize_t prec,
1231
           const mpd_context_t *ctx, uint32_t *status)
1232
0
{
1233
0
    mpd_ssize_t exp = a->exp + a->digits - prec;
1234
1235
0
    if (prec <= 0) {
1236
0
        mpd_seterror(result, MPD_Invalid_operation, status); /* GCOV_NOT_REACHED */
1237
0
        return; /* GCOV_NOT_REACHED */
1238
0
    }
1239
0
    if (mpd_isspecial(a) || mpd_iszero(a)) {
1240
0
        mpd_qcopy(result, a, status); /* GCOV_NOT_REACHED */
1241
0
        return; /* GCOV_NOT_REACHED */
1242
0
    }
1243
1244
0
    mpd_qrescale_fmt(result, a, exp, ctx, status);
1245
0
    if (result->digits > prec) {
1246
0
        mpd_qrescale_fmt(result, result, exp+1, ctx, status);
1247
0
    }
1248
0
}
1249
1250
/*
1251
 * Return the string representation of an mpd_t, formatted according to 'spec'.
1252
 * The format specification is assumed to be valid. Memory errors are indicated
1253
 * as usual. This function is quiet.
1254
 */
1255
char *
1256
mpd_qformat_spec(const mpd_t *dec, const mpd_spec_t *spec,
1257
                 const mpd_context_t *ctx, uint32_t *status)
1258
4.35k
{
1259
4.35k
    mpd_uint_t dt[MPD_MINALLOC_MAX];
1260
4.35k
    mpd_t tmp = {MPD_STATIC|MPD_STATIC_DATA,0,0,0,MPD_MINALLOC_MAX,dt};
1261
4.35k
    mpd_ssize_t dplace = MPD_DEFAULT_DOTPLACE;
1262
4.35k
    mpd_mbstr_t result;
1263
4.35k
    mpd_spec_t stackspec;
1264
4.35k
    char type = spec->type;
1265
4.35k
    int flags = 0;
1266
1267
1268
4.35k
    if (spec->min_width > MPD_MAX_PREC) {
1269
0
        *status |= MPD_Invalid_operation;
1270
0
        return NULL;
1271
0
    }
1272
1273
4.35k
    if (isupper((unsigned char)type)) {
1274
0
        type = (char)tolower((unsigned char)type);
1275
0
        flags |= MPD_FMT_UPPER;
1276
0
    }
1277
1278
4.35k
    if (spec->sign_coerce) {
1279
0
        flags |= MPD_FMT_SIGN_COERCE;
1280
0
    }
1281
1282
4.35k
    if (spec->sign == ' ') {
1283
0
        flags |= MPD_FMT_SIGN_SPACE;
1284
0
    }
1285
4.35k
    else if (spec->sign == '+') {
1286
0
        flags |= MPD_FMT_SIGN_PLUS;
1287
0
    }
1288
1289
4.35k
    if (mpd_isspecial(dec)) {
1290
0
        if (spec->align == 'z') {
1291
0
            stackspec = *spec;
1292
0
            stackspec.fill[0] = ' ';
1293
0
            stackspec.fill[1] = '\0';
1294
0
            stackspec.align = '>';
1295
0
            spec = &stackspec;
1296
0
        }
1297
0
        if (type == '%') {
1298
0
            flags |= MPD_FMT_PERCENT;
1299
0
        }
1300
0
    }
1301
4.35k
    else {
1302
4.35k
        uint32_t workstatus = 0;
1303
4.35k
        mpd_ssize_t prec;
1304
1305
4.35k
        switch (type) {
1306
0
        case 'g': flags |= MPD_FMT_TOSCI; break;
1307
0
        case 'e': flags |= MPD_FMT_EXP; break;
1308
0
        case '%': flags |= MPD_FMT_PERCENT;
1309
0
                  if (!mpd_qcopy(&tmp, dec, status)) {
1310
0
                      return NULL;
1311
0
                  }
1312
0
                  tmp.exp += 2;
1313
0
                  dec = &tmp;
1314
0
                  type = 'f'; /* fall through */
1315
4.35k
        case 'f': flags |= MPD_FMT_FIXED; break;
1316
0
        default: abort(); /* debug: GCOV_NOT_REACHED */
1317
4.35k
        }
1318
1319
4.35k
        if (spec->prec >= 0) {
1320
0
            if (spec->prec > MPD_MAX_PREC) {
1321
0
                *status |= MPD_Invalid_operation;
1322
0
                goto error;
1323
0
            }
1324
1325
0
            switch (type) {
1326
0
            case 'g':
1327
0
                prec = (spec->prec == 0) ? 1 : spec->prec;
1328
0
                if (dec->digits > prec) {
1329
0
                    _mpd_round(&tmp, dec, prec, ctx,
1330
0
                               &workstatus);
1331
0
                    dec = &tmp;
1332
0
                }
1333
0
                break;
1334
0
            case 'e':
1335
0
                if (mpd_iszero(dec)) {
1336
0
                    dplace = 1-spec->prec;
1337
0
                }
1338
0
                else {
1339
0
                    _mpd_round(&tmp, dec, spec->prec+1, ctx,
1340
0
                               &workstatus);
1341
0
                    dec = &tmp;
1342
0
                }
1343
0
                break;
1344
0
            case 'f':
1345
0
                mpd_qrescale(&tmp, dec, -spec->prec, ctx,
1346
0
                             &workstatus);
1347
0
                dec = &tmp;
1348
0
                break;
1349
0
            }
1350
0
        }
1351
1352
4.35k
        if (type == 'f') {
1353
4.35k
            if (mpd_iszero(dec) && dec->exp > 0) {
1354
0
                mpd_qrescale(&tmp, dec, 0, ctx, &workstatus);
1355
0
                dec = &tmp;
1356
0
            }
1357
4.35k
        }
1358
1359
4.35k
        if (workstatus&MPD_Errors) {
1360
0
            *status |= (workstatus&MPD_Errors);
1361
0
            goto error;
1362
0
        }
1363
4.35k
    }
1364
1365
    /*
1366
     * At this point, for all scaled or non-scaled decimals:
1367
     *   1) 1 <= digits <= MAX_PREC+1
1368
     *   2) adjexp(scaled) = adjexp(orig) [+1]
1369
     *   3)   case 'g': MIN_ETINY <= exp <= MAX_EMAX+1
1370
     *        case 'e': MIN_ETINY-MAX_PREC <= exp <= MAX_EMAX+1
1371
     *        case 'f': MIN_ETINY <= exp <= MAX_EMAX+1
1372
     *   4) max memory alloc in _mpd_to_string:
1373
     *        case 'g': MAX_PREC+36
1374
     *        case 'e': MAX_PREC+36
1375
     *        case 'f': 2*MPD_MAX_PREC+30
1376
     */
1377
4.35k
    result.nbytes = _mpd_to_string(&result.data, dec, flags, dplace);
1378
4.35k
    result.nchars = result.nbytes;
1379
4.35k
    if (result.nbytes < 0) {
1380
0
        *status |= MPD_Malloc_error;
1381
0
        goto error;
1382
0
    }
1383
1384
4.35k
    if (*spec->dot != '\0' && !mpd_isspecial(dec)) {
1385
0
        if (result.nchars > MPD_MAX_PREC+36) {
1386
            /* Since a group length of one is not explicitly
1387
             * disallowed, ensure that it is always possible to
1388
             * insert a four byte separator after each digit. */
1389
0
            *status |= MPD_Invalid_operation;
1390
0
            mpd_free(result.data);
1391
0
            goto error;
1392
0
        }
1393
0
        if (!_mpd_apply_lconv(&result, spec, status)) {
1394
0
            goto error;
1395
0
        }
1396
0
    }
1397
1398
4.35k
    if (spec->min_width) {
1399
0
        if (!_mpd_add_pad(&result, spec, status)) {
1400
0
            goto error;
1401
0
        }
1402
0
    }
1403
1404
4.35k
    mpd_del(&tmp);
1405
4.35k
    return result.data;
1406
1407
0
error:
1408
0
    mpd_del(&tmp);
1409
0
    return NULL;
1410
4.35k
}
1411
1412
char *
1413
mpd_qformat(const mpd_t *dec, const char *fmt, const mpd_context_t *ctx,
1414
            uint32_t *status)
1415
4.35k
{
1416
4.35k
    mpd_spec_t spec;
1417
1418
4.35k
    if (!mpd_parse_fmt_str(&spec, fmt, 1)) {
1419
0
        *status |= MPD_Invalid_operation;
1420
0
        return NULL;
1421
0
    }
1422
1423
4.35k
    return mpd_qformat_spec(dec, &spec, ctx, status);
1424
4.35k
}
1425
1426
/*
1427
 * The specification has a *condition* called Invalid_operation and an
1428
 * IEEE *signal* called Invalid_operation. The former corresponds to
1429
 * MPD_Invalid_operation, the latter to MPD_IEEE_Invalid_operation.
1430
 * MPD_IEEE_Invalid_operation comprises the following conditions:
1431
 *
1432
 * [MPD_Conversion_syntax, MPD_Division_impossible, MPD_Division_undefined,
1433
 *  MPD_Fpu_error, MPD_Invalid_context, MPD_Invalid_operation,
1434
 *  MPD_Malloc_error]
1435
 *
1436
 * In the following functions, 'flag' denotes the condition, 'signal'
1437
 * denotes the IEEE signal.
1438
 */
1439
1440
static const char *mpd_flag_string[MPD_NUM_FLAGS] = {
1441
    "Clamped",
1442
    "Conversion_syntax",
1443
    "Division_by_zero",
1444
    "Division_impossible",
1445
    "Division_undefined",
1446
    "Fpu_error",
1447
    "Inexact",
1448
    "Invalid_context",
1449
    "Invalid_operation",
1450
    "Malloc_error",
1451
    "Not_implemented",
1452
    "Overflow",
1453
    "Rounded",
1454
    "Subnormal",
1455
    "Underflow",
1456
};
1457
1458
static const char *mpd_signal_string[MPD_NUM_FLAGS] = {
1459
    "Clamped",
1460
    "IEEE_Invalid_operation",
1461
    "Division_by_zero",
1462
    "IEEE_Invalid_operation",
1463
    "IEEE_Invalid_operation",
1464
    "IEEE_Invalid_operation",
1465
    "Inexact",
1466
    "IEEE_Invalid_operation",
1467
    "IEEE_Invalid_operation",
1468
    "IEEE_Invalid_operation",
1469
    "Not_implemented",
1470
    "Overflow",
1471
    "Rounded",
1472
    "Subnormal",
1473
    "Underflow",
1474
};
1475
1476
/* print conditions to buffer, separated by spaces */
1477
int
1478
mpd_snprint_flags(char *dest, int nmemb, uint32_t flags)
1479
0
{
1480
0
    char *cp;
1481
0
    int n, j;
1482
1483
0
    assert(nmemb >= MPD_MAX_FLAG_STRING);
1484
1485
0
    *dest = '\0'; cp = dest;
1486
0
    for (j = 0; j < MPD_NUM_FLAGS; j++) {
1487
0
        if (flags & (1U<<j)) {
1488
0
            n = snprintf(cp, nmemb, "%s ", mpd_flag_string[j]);
1489
0
            if (n < 0 || n >= nmemb) return -1;
1490
0
            cp += n; nmemb -= n;
1491
0
        }
1492
0
    }
1493
1494
0
    if (cp != dest) {
1495
0
        *(--cp) = '\0';
1496
0
    }
1497
1498
0
    return (int)(cp-dest);
1499
0
}
1500
1501
/* print conditions to buffer, in list form */
1502
int
1503
mpd_lsnprint_flags(char *dest, int nmemb, uint32_t flags, const char *flag_string[])
1504
0
{
1505
0
    char *cp;
1506
0
    int n, j;
1507
1508
0
    assert(nmemb >= MPD_MAX_FLAG_LIST);
1509
0
    if (flag_string == NULL) {
1510
0
        flag_string = mpd_flag_string;
1511
0
    }
1512
1513
0
    *dest = '[';
1514
0
    *(dest+1) = '\0';
1515
0
    cp = dest+1;
1516
0
    --nmemb;
1517
1518
0
    for (j = 0; j < MPD_NUM_FLAGS; j++) {
1519
0
        if (flags & (1U<<j)) {
1520
0
            n = snprintf(cp, nmemb, "%s, ", flag_string[j]);
1521
0
            if (n < 0 || n >= nmemb) return -1;
1522
0
            cp += n; nmemb -= n;
1523
0
        }
1524
0
    }
1525
1526
    /* erase the last ", " */
1527
0
    if (cp != dest+1) {
1528
0
        cp -= 2;
1529
0
    }
1530
1531
0
    *cp++ = ']';
1532
0
    *cp = '\0';
1533
1534
0
    return (int)(cp-dest); /* strlen, without NUL terminator */
1535
0
}
1536
1537
/* print signals to buffer, in list form */
1538
int
1539
mpd_lsnprint_signals(char *dest, int nmemb, uint32_t flags, const char *signal_string[])
1540
0
{
1541
0
    char *cp;
1542
0
    int n, j;
1543
0
    int ieee_invalid_done = 0;
1544
1545
0
    assert(nmemb >= MPD_MAX_SIGNAL_LIST);
1546
0
    if (signal_string == NULL) {
1547
0
        signal_string = mpd_signal_string;
1548
0
    }
1549
1550
0
    *dest = '[';
1551
0
    *(dest+1) = '\0';
1552
0
    cp = dest+1;
1553
0
    --nmemb;
1554
1555
0
    for (j = 0; j < MPD_NUM_FLAGS; j++) {
1556
0
        uint32_t f = flags & (1U<<j);
1557
0
        if (f) {
1558
0
            if (f&MPD_IEEE_Invalid_operation) {
1559
0
                if (ieee_invalid_done) {
1560
0
                    continue;
1561
0
                }
1562
0
                ieee_invalid_done = 1;
1563
0
            }
1564
0
            n = snprintf(cp, nmemb, "%s, ", signal_string[j]);
1565
0
            if (n < 0 || n >= nmemb) return -1;
1566
0
            cp += n; nmemb -= n;
1567
0
        }
1568
0
    }
1569
1570
    /* erase the last ", " */
1571
0
    if (cp != dest+1) {
1572
0
        cp -= 2;
1573
0
    }
1574
1575
0
    *cp++ = ']';
1576
0
    *cp = '\0';
1577
1578
0
    return (int)(cp-dest); /* strlen, without NUL terminator */
1579
0
}
1580
1581
/* The following two functions are mainly intended for debugging. */
1582
void
1583
mpd_fprint(FILE *file, const mpd_t *dec)
1584
0
{
1585
0
    char *decstring;
1586
1587
0
    decstring = mpd_to_sci(dec, 1);
1588
0
    if (decstring != NULL) {
1589
0
        fprintf(file, "%s\n", decstring);
1590
0
        mpd_free(decstring);
1591
0
    }
1592
0
    else {
1593
0
        fputs("mpd_fprint: output error\n", file); /* GCOV_NOT_REACHED */
1594
0
    }
1595
0
}
1596
1597
void
1598
mpd_print(const mpd_t *dec)
1599
0
{
1600
0
    char *decstring;
1601
1602
0
    decstring = mpd_to_sci(dec, 1);
1603
0
    if (decstring != NULL) {
1604
0
        printf("%s\n", decstring);
1605
0
        mpd_free(decstring);
1606
0
    }
1607
0
    else {
1608
0
        fputs("mpd_fprint: output error\n", stderr); /* GCOV_NOT_REACHED */
1609
0
    }
1610
0
}