]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/stdlib/strfmon.c
ssh: Update to OpenSSH 9.7p1
[FreeBSD/FreeBSD.git] / lib / libc / stdlib / strfmon.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001 Alexey Zelkin <phantom@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Copyright (c) 2011 The FreeBSD Foundation
8  *
9  * Portions of this software were developed by David Chisnall
10  * under sponsorship from the FreeBSD Foundation.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  */
34
35 #include <sys/types.h>
36
37 #include <ctype.h>
38 #include <errno.h>
39 #include <limits.h>
40 #include <locale.h>
41 #include <monetary.h>
42 #include <stdarg.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include "xlocale_private.h"
48
49 /* internal flags */
50 #define NEED_GROUPING           0x01    /* print digits grouped (default) */
51 #define SIGN_POSN_USED          0x02    /* '+' or '(' usage flag */
52 #define LOCALE_POSN             0x04    /* use locale defined +/- (default) */
53 #define PARENTH_POSN            0x08    /* enclose negative amount in () */
54 #define SUPPRESS_CURR_SYMBOL    0x10    /* suppress the currency from output */
55 #define LEFT_JUSTIFY            0x20    /* left justify */
56 #define USE_INTL_CURRENCY       0x40    /* use international currency symbol */
57 #define IS_NEGATIVE             0x80    /* is argument value negative ? */
58
59 /* internal macros */
60 #define PRINT(CH) do {                                          \
61         if (dst >= s + maxsize)                                 \
62                 goto e2big_error;                               \
63         *dst++ = CH;                                            \
64 } while (0)
65
66 #define PRINTS(STR) do {                                        \
67         char *tmps = STR;                                       \
68         while (*tmps != '\0')                                   \
69                 PRINT(*tmps++);                                 \
70 } while (0)
71
72 #define GET_NUMBER(VAR, LOC) do {                               \
73         VAR = 0;                                                \
74         while (isdigit_l((unsigned char)*fmt, LOC)) {           \
75                 if (VAR > INT_MAX / 10)                         \
76                         goto e2big_error;                       \
77                 VAR *= 10;                                      \
78                 VAR += *fmt - '0';                              \
79                 if (VAR < 0)                                    \
80                         goto e2big_error;                       \
81                 fmt++;                                          \
82         }                                                       \
83 } while (0)
84
85 #define GRPCPY(howmany) do {                                    \
86         int i = howmany;                                        \
87         while (i-- > 0) {                                       \
88                 avalue_size--;                                  \
89                 *--bufend = *(avalue + avalue_size + padded);   \
90         }                                                       \
91 } while (0)
92
93 #define GRPSEP do {                                             \
94         bufend -= thousands_sep_size;                           \
95         memcpy(bufend, thousands_sep, thousands_sep_size);      \
96         groups++;                                               \
97 } while (0)
98
99 static void __setup_vars(int, char *, char *, char *, char **, struct lconv *);
100 static int __calc_left_pad(int, char *, struct lconv *);
101 static char *__format_grouped_double(double, int *, int, int, int,
102     struct lconv *, locale_t);
103
104 static ssize_t
105 vstrfmon_l(char *__restrict s, size_t maxsize, locale_t loc,
106     const char *__restrict format, va_list ap)
107 {
108         char            *dst;           /* output destination pointer */
109         const char      *fmt;           /* current format poistion pointer */
110         struct lconv    *lc;            /* pointer to lconv structure */
111         char            *asciivalue;    /* formatted double pointer */
112
113         int             flags;                  /* formatting options */
114         int             pad_char;               /* padding character */
115         int             pad_size;               /* pad size */
116         int             width;                  /* field width */
117         int             left_prec;              /* left precision */
118         int             right_prec;             /* right precision */
119         double          value;                  /* just value */
120         char            space_char = ' ';       /* space after currency */
121
122         char            cs_precedes,    /* values gathered from struct lconv */
123                         sep_by_space,
124                         sign_posn,
125                         *signstr,
126                         *currency_symbol;
127
128         char            *tmpptr;        /* temporary vars */
129         int             sverrno;
130
131         FIX_LOCALE(loc);
132
133         lc = localeconv_l(loc);
134         dst = s;
135         fmt = format;
136         asciivalue = NULL;
137         currency_symbol = NULL;
138
139         while (*fmt != 0) {
140                 /* pass nonformating characters AS IS */
141                 if (*fmt != '%')
142                         goto literal;
143
144                 /* '%' found ! */
145
146                 /* "%%" mean just '%' */
147                 if (*(fmt + 1) == '%') {
148                         fmt++;
149 literal:
150                         PRINT(*fmt++);
151                         continue;
152                 }
153
154                 /* set up initial values */
155                 flags = NEED_GROUPING | LOCALE_POSN;
156                 pad_char = ' ';         /* padding character is "space" */
157                 pad_size = 0;           /* no padding initially */
158                 left_prec = -1;         /* no left precision specified */
159                 right_prec = -1;        /* no right precision specified */
160                 width = -1;             /* no width specified */
161
162                 /* Flags */
163                 while (1) {
164                         switch (*++fmt) {
165                         case '=':       /* fill character */
166                                 pad_char = *++fmt;
167                                 if (pad_char == '\0')
168                                         goto format_error;
169                                 continue;
170                         case '^':       /* not group currency */
171                                 flags &= ~(NEED_GROUPING);
172                                 continue;
173                         case '+':       /* use locale defined signs */
174                                 if (flags & SIGN_POSN_USED)
175                                         goto format_error;
176                                 flags |= (SIGN_POSN_USED | LOCALE_POSN);
177                                 continue;
178                         case '(':       /* enclose negatives with () */
179                                 if (flags & SIGN_POSN_USED)
180                                         goto format_error;
181                                 flags |= (SIGN_POSN_USED | PARENTH_POSN);
182                                 continue;
183                         case '!':       /* suppress currency symbol */
184                                 flags |= SUPPRESS_CURR_SYMBOL;
185                                 continue;
186                         case '-':       /* alignment (left) */
187                                 flags |= LEFT_JUSTIFY;
188                                 continue;
189                         default:
190                                 break;
191                         }
192                         break;
193                 }
194
195                 /* field Width */
196                 if (isdigit_l((unsigned char)*fmt, loc)) {
197                         GET_NUMBER(width, loc);
198                         /*
199                          * Do we have enough space to put number with
200                          * required width ?
201                          */
202                         if ((unsigned int)width >= maxsize - (dst - s))
203                                 goto e2big_error;
204                 }
205
206                 /* Left precision */
207                 if (*fmt == '#') {
208                         if (!isdigit_l((unsigned char)*++fmt, loc))
209                                 goto format_error;
210                         GET_NUMBER(left_prec, loc);
211                         if ((unsigned int)left_prec >= maxsize - (dst - s))
212                                 goto e2big_error;
213                 }
214
215                 /* Right precision */
216                 if (*fmt == '.') {
217                         if (!isdigit_l((unsigned char)*++fmt, loc))
218                                 goto format_error;
219                         GET_NUMBER(right_prec, loc);
220                         if ((unsigned int)right_prec >=
221                             maxsize - (dst - s) - left_prec)
222                                 goto e2big_error;
223                 }
224
225                 /* Conversion Characters */
226                 switch (*fmt++) {
227                 case 'i':       /* use international currency format */
228                         flags |= USE_INTL_CURRENCY;
229                         break;
230                 case 'n':       /* use national currency format */
231                         flags &= ~(USE_INTL_CURRENCY);
232                         break;
233                 default:        /*
234                                  * required character is missing or
235                                  * premature EOS
236                                  */
237                         goto format_error;
238                 }
239
240                 if (currency_symbol != NULL)
241                         free(currency_symbol);
242                 if (flags & USE_INTL_CURRENCY) {
243                         currency_symbol = strdup(lc->int_curr_symbol);
244                         if (currency_symbol != NULL &&
245                             strlen(currency_symbol) > 3) {
246                                 space_char = currency_symbol[3];
247                                 currency_symbol[3] = '\0';
248                         }
249                 } else
250                         currency_symbol = strdup(lc->currency_symbol);
251
252                 if (currency_symbol == NULL)
253                         goto end_error; /* ENOMEM. */
254
255                 /* value itself */
256                 value = va_arg(ap, double);
257
258                 /* detect sign */
259                 if (value < 0) {
260                         flags |= IS_NEGATIVE;
261                         value = -value;
262                 }
263
264                 /* fill left_prec with amount of padding chars */
265                 if (left_prec >= 0) {
266                         pad_size = __calc_left_pad((flags ^ IS_NEGATIVE),
267                             currency_symbol, lc) -
268                             __calc_left_pad(flags, currency_symbol, lc);
269                         if (pad_size < 0)
270                                 pad_size = 0;
271                 }
272
273                 if (asciivalue != NULL)
274                         free(asciivalue);
275                 asciivalue = __format_grouped_double(value, &flags, left_prec,
276                     right_prec, pad_char, lc, loc);
277                 if (asciivalue == NULL)
278                         goto end_error; /*
279                                          * errno already set to ENOMEM by
280                                          * malloc()
281                                          */
282
283                 /* set some variables for later use */
284                 __setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn,
285                     &signstr, lc);
286
287                 /*
288                  * Description of some LC_MONETARY's values:
289                  *
290                  * p_cs_precedes & n_cs_precedes
291                  *
292                  * = 1 - $currency_symbol precedes the value
293                  *       for a monetary quantity with a non-negative value
294                  * = 0 - symbol succeeds the value
295                  *
296                  * p_sep_by_space & n_sep_by_space
297                  *
298                  * = 0 - no space separates $currency_symbol
299                  *       from the value for a monetary quantity with a
300                  *       non-negative value
301                  * = 1 - space separates the symbol from the value
302                  * = 2 - space separates the symbol and the sign string,
303                  *       if adjacent; otherwise, a space separates
304                  *       the sign string from the value
305                  *
306                  * p_sign_posn & n_sign_posn
307                  *
308                  * = 0 - parentheses enclose the quantity and the
309                  *       $currency_symbol
310                  * = 1 - the sign string precedes the quantity and the
311                  *       $currency_symbol
312                  * = 2 - the sign string succeeds the quantity and the
313                  *       $currency_symbol
314                  * = 3 - the sign string precedes the $currency_symbol
315                  * = 4 - the sign string succeeds the $currency_symbol
316                  */
317
318                 tmpptr = dst;
319
320                 while (pad_size-- > 0)
321                         PRINT(' ');
322
323                 if (sign_posn == 0 && (flags & IS_NEGATIVE))
324                         PRINT('(');
325
326                 if (cs_precedes == 1) {
327                         if (sign_posn == 1 || sign_posn == 3) {
328                                 PRINTS(signstr);
329                                 if (sep_by_space == 2)
330                                         PRINT(' ');
331                         }
332
333                         if (!(flags & SUPPRESS_CURR_SYMBOL)) {
334                                 PRINTS(currency_symbol);
335
336                                 if (sign_posn == 4) {
337                                         if (sep_by_space == 2)
338                                                 PRINT(space_char);
339                                         PRINTS(signstr);
340                                         if (sep_by_space == 1)
341                                                 PRINT(' ');
342                                 } else if (sep_by_space == 1)
343                                         PRINT(space_char);
344                         }
345                 } else if (sign_posn == 1) {
346                         PRINTS(signstr);
347                         if (sep_by_space == 2)
348                                 PRINT(' ');
349                 }
350
351                 PRINTS(asciivalue);
352
353                 if (cs_precedes == 0) {
354                         if (sign_posn == 3) {
355                                 if (sep_by_space == 1)
356                                         PRINT(' ');
357                                 PRINTS(signstr);
358                         }
359
360                         if (!(flags & SUPPRESS_CURR_SYMBOL)) {
361                                 if ((sign_posn == 3 && sep_by_space == 2) ||
362                                     (sep_by_space == 1 &&
363                                      (sign_posn == 0 || sign_posn == 1 ||
364                                       sign_posn == 2 || sign_posn == 4)))
365                                         PRINT(space_char);
366                                 PRINTS(currency_symbol);
367                                 if (sign_posn == 4) {
368                                         if (sep_by_space == 2)
369                                                 PRINT(' ');
370                                         PRINTS(signstr);
371                                 }
372                         }
373                 }
374
375                 if (sign_posn == 2) {
376                         if (sep_by_space == 2)
377                                 PRINT(' ');
378                         PRINTS(signstr);
379                 }
380
381                 if (sign_posn == 0) {
382                         if (flags & IS_NEGATIVE)
383                                 PRINT(')');
384                         else if (left_prec >= 0)
385                                 PRINT(' ');
386                 }
387
388                 if (dst - tmpptr < width) {
389                         if (flags & LEFT_JUSTIFY) {
390                                 while (dst - tmpptr < width)
391                                         PRINT(' ');
392                         } else {
393                                 pad_size = dst - tmpptr;
394                                 memmove(tmpptr + width - pad_size, tmpptr,
395                                     pad_size);
396                                 memset(tmpptr, ' ', width - pad_size);
397                                 dst += width - pad_size;
398                         }
399                 }
400         }
401
402         PRINT('\0');
403         free(asciivalue);
404         free(currency_symbol);
405         return (dst - s - 1);   /* size of put data except trailing '\0' */
406
407 e2big_error:
408         errno = E2BIG;
409         goto end_error;
410
411 format_error:
412         errno = EINVAL;
413
414 end_error:
415         sverrno = errno;
416         if (asciivalue != NULL)
417                 free(asciivalue);
418         if (currency_symbol != NULL)
419                 free(currency_symbol);
420         errno = sverrno;
421         return (-1);
422 }
423
424 static void
425 __setup_vars(int flags, char *cs_precedes, char *sep_by_space, char *sign_posn,
426     char **signstr, struct lconv *lc)
427 {
428         if ((flags & IS_NEGATIVE) && (flags & USE_INTL_CURRENCY)) {
429                 *cs_precedes = lc->int_n_cs_precedes;
430                 *sep_by_space = lc->int_n_sep_by_space;
431                 *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_n_sign_posn;
432                 *signstr = (lc->negative_sign[0] == '\0') ? "-" :
433                     lc->negative_sign;
434         } else if (flags & USE_INTL_CURRENCY) {
435                 *cs_precedes = lc->int_p_cs_precedes;
436                 *sep_by_space = lc->int_p_sep_by_space;
437                 *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_p_sign_posn;
438                 *signstr = lc->positive_sign;
439         } else if (flags & IS_NEGATIVE) {
440                 *cs_precedes = lc->n_cs_precedes;
441                 *sep_by_space = lc->n_sep_by_space;
442                 *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->n_sign_posn;
443                 *signstr = (lc->negative_sign[0] == '\0') ? "-" :
444                     lc->negative_sign;
445         } else {
446                 *cs_precedes = lc->p_cs_precedes;
447                 *sep_by_space = lc->p_sep_by_space;
448                 *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->p_sign_posn;
449                 *signstr = lc->positive_sign;
450         }
451
452         /* Set default values for unspecified information. */
453         if (*cs_precedes != 0)
454                 *cs_precedes = 1;
455         if (*sep_by_space == CHAR_MAX)
456                 *sep_by_space = 0;
457         if (*sign_posn == CHAR_MAX)
458                 *sign_posn = 0;
459 }
460
461 static int
462 __calc_left_pad(int flags, char *cur_symb, struct lconv *lc)
463 {
464         char cs_precedes, sep_by_space, sign_posn, *signstr;
465         int left_chars = 0;
466
467         __setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn, &signstr,
468             lc);
469
470         if (cs_precedes != 0) {
471                 left_chars += strlen(cur_symb);
472                 if (sep_by_space != 0)
473                         left_chars++;
474         }
475
476         switch (sign_posn) {
477         case 0:
478                 if (flags & IS_NEGATIVE)
479                         left_chars++;
480                 break;
481         case 1:
482                 left_chars += strlen(signstr);
483                 break;
484         case 3:
485         case 4:
486                 if (cs_precedes != 0)
487                         left_chars += strlen(signstr);
488         }
489         return (left_chars);
490 }
491
492 static int
493 get_groups(int size, char *grouping)
494 {
495         int     chars = 0;
496
497         if (*grouping == CHAR_MAX || *grouping <= 0)    /* no grouping ? */
498                 return (0);
499
500         while (size > (int)*grouping) {
501                 chars++;
502                 size -= (int)*grouping++;
503                 /* no more grouping ? */
504                 if (*grouping == CHAR_MAX)
505                         break;
506                 /* rest grouping with same value ? */
507                 if (*grouping == 0) {
508                         chars += (size - 1) / *(grouping - 1);
509                         break;
510                 }
511         }
512         return (chars);
513 }
514
515 /* convert double to locale-encoded string */
516 static char *
517 __format_grouped_double(double value, int *flags, int left_prec, int right_prec,
518     int pad_char, struct lconv *lc, locale_t loc)
519 {
520
521         char            *rslt;
522         char            *avalue;
523         int             avalue_size;
524
525         size_t          bufsize;
526         char            *bufend;
527
528         int             padded;
529
530         char            *grouping;
531         const char      *decimal_point;
532         const char      *thousands_sep;
533         size_t          decimal_point_size;
534         size_t          thousands_sep_size;
535
536         int             groups = 0;
537
538         grouping = lc->mon_grouping;
539         decimal_point = lc->mon_decimal_point;
540         if (*decimal_point == '\0')
541                 decimal_point = lc->decimal_point;
542         thousands_sep = lc->mon_thousands_sep;
543         if (*thousands_sep == '\0')
544                 thousands_sep = lc->thousands_sep;
545
546         decimal_point_size = strlen(decimal_point);
547         thousands_sep_size = strlen(thousands_sep);
548
549         /* fill left_prec with default value */
550         if (left_prec == -1)
551                 left_prec = 0;
552
553         /* fill right_prec with default value */
554         if (right_prec == -1) {
555                 if (*flags & USE_INTL_CURRENCY)
556                         right_prec = lc->int_frac_digits;
557                 else
558                         right_prec = lc->frac_digits;
559
560                 if (right_prec == CHAR_MAX)     /* POSIX locale ? */
561                         right_prec = 2;
562         }
563
564         if (*flags & NEED_GROUPING)
565                 left_prec += get_groups(left_prec, grouping);
566
567         /* convert to string */
568         avalue_size = asprintf_l(&avalue, loc, "%*.*f",
569             left_prec + right_prec + 1, right_prec, value);
570         if (avalue_size < 0)
571                 return (NULL);
572
573         /* make sure that we've enough space for result string */
574         bufsize = avalue_size * (1 + thousands_sep_size) + decimal_point_size +
575             1;
576         rslt = calloc(1, bufsize);
577         if (rslt == NULL) {
578                 free(avalue);
579                 return (NULL);
580         }
581         bufend = rslt + bufsize - 1;    /* reserve space for trailing '\0' */
582
583         /* skip spaces at beginning */
584         padded = 0;
585         while (avalue[padded] == ' ') {
586                 padded++;
587                 avalue_size--;
588         }
589
590         if (right_prec > 0) {
591                 bufend -= right_prec;
592                 memcpy(bufend, avalue + avalue_size + padded - right_prec,
593                     right_prec);
594                 bufend -= decimal_point_size;
595                 memcpy(bufend, decimal_point, decimal_point_size);
596                 avalue_size -= (right_prec + 1);
597         }
598
599         if ((*flags & NEED_GROUPING) && thousands_sep_size > 0 &&
600             *grouping != CHAR_MAX && *grouping > 0) {
601                 while (avalue_size > (int)*grouping) {
602                         GRPCPY(*grouping);
603                         GRPSEP;
604                         grouping++;
605
606                         /* no more grouping ? */
607                         if (*grouping == CHAR_MAX)
608                                 break;
609
610                         /* rest grouping with same value ? */
611                         if (*grouping == 0) {
612                                 grouping--;
613                                 while (avalue_size > *grouping) {
614                                         GRPCPY(*grouping);
615                                         GRPSEP;
616                                 }
617                         }
618                 }
619                 if (avalue_size != 0)
620                         GRPCPY(avalue_size);
621                 padded -= groups;
622         } else {
623                 bufend -= avalue_size;
624                 memcpy(bufend, avalue + padded, avalue_size);
625                 /* decrease assumed $decimal_point */
626                 if (right_prec == 0)
627                         padded -= decimal_point_size;
628         }
629
630         /* do padding with pad_char */
631         if (padded > 0) {
632                 bufend -= padded;
633                 memset(bufend, pad_char, padded);
634         }
635
636         bufsize = rslt + bufsize - bufend;
637         memmove(rslt, bufend, bufsize);
638         free(avalue);
639         return (rslt);
640 }
641
642 ssize_t
643 strfmon(char *restrict s, size_t maxsize, const char *restrict format, ...)
644 {
645         ssize_t ret;
646         va_list ap;
647
648         va_start(ap, format);
649         ret = vstrfmon_l(s, maxsize, __get_locale(), format, ap);
650         va_end(ap);
651
652         return (ret);
653 }
654
655 ssize_t
656 strfmon_l(char *restrict s, size_t maxsize, locale_t loc,
657     const char *restrict format, ...)
658 {
659         ssize_t ret;
660         va_list ap;
661
662         va_start(ap, format);
663         ret = vstrfmon_l(s, maxsize, loc, format, ap);
664         va_end(ap);
665
666         return (ret);
667 }