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