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: stable/10/lib/libc/stdlib/strfmon.c 268881 2014-07-19 15:12:38Z pfg $");
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
vstrfmon_l(char * __restrict s,size_t maxsize,locale_t loc,const char * __restrict format,va_list ap)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
strfmon_l(char * __restrict s,size_t maxsize,locale_t loc,const char * __restrict format,...)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
strfmon(char * __restrict s,size_t maxsize,const char * __restrict format,...)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
__setup_vars(int flags,char * cs_precedes,char * sep_by_space,char * sign_posn,char ** signstr)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
__calc_left_pad(int flags,char * cur_symb)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
get_groups(int size,char * grouping)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 *
__format_grouped_double(double value,int * flags,int left_prec,int right_prec,int pad_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
530 size_t bufsize;
531 char *bufend;
532
533 int padded;
534
535 struct lconv *lc = localeconv();
536 char *grouping;
537 char decimal_point;
538 char thousands_sep;
539
540 int groups = 0;
541
542 grouping = lc->mon_grouping;
543 decimal_point = *lc->mon_decimal_point;
544 if (decimal_point == '\0')
545 decimal_point = *lc->decimal_point;
546 thousands_sep = *lc->mon_thousands_sep;
547 if (thousands_sep == '\0')
548 thousands_sep = *lc->thousands_sep;
549
550 /* fill left_prec with default value */
551 if (left_prec == -1)
552 left_prec = 0;
553
554 /* fill right_prec with default value */
555 if (right_prec == -1) {
556 if (*flags & USE_INTL_CURRENCY)
557 right_prec = lc->int_frac_digits;
558 else
559 right_prec = lc->frac_digits;
560
561 if (right_prec == CHAR_MAX) /* POSIX locale ? */
562 right_prec = 2;
563 }
564
565 if (*flags & NEED_GROUPING)
566 left_prec += get_groups(left_prec, grouping);
567
568 /* convert to string */
569 avalue_size = asprintf(&avalue, "%*.*f", left_prec + right_prec + 1,
570 right_prec, value);
571 if (avalue_size < 0)
572 return (NULL);
573
574 /* make sure that we've enough space for result string */
575 bufsize = avalue_size * 2 + 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 beggining */
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;
595 avalue_size -= (right_prec + 1);
596 }
597
598 if ((*flags & NEED_GROUPING) &&
599 thousands_sep != '\0' && /* XXX: need investigation */
600 *grouping != CHAR_MAX &&
601 *grouping > 0) {
602 while (avalue_size > (int)*grouping) {
603 GRPCPY(*grouping);
604 GRPSEP;
605 grouping++;
606
607 /* no more grouping ? */
608 if (*grouping == CHAR_MAX)
609 break;
610
611 /* rest grouping with same value ? */
612 if (*grouping == 0) {
613 grouping--;
614 while (avalue_size > *grouping) {
615 GRPCPY(*grouping);
616 GRPSEP;
617 }
618 }
619 }
620 if (avalue_size != 0)
621 GRPCPY(avalue_size);
622 padded -= groups;
623
624 } else {
625 bufend -= avalue_size;
626 memcpy(bufend, avalue+padded, avalue_size);
627 if (right_prec == 0)
628 padded--; /* decrease assumed $decimal_point */
629 }
630
631 /* do padding with pad_char */
632 if (padded > 0) {
633 bufend -= padded;
634 memset(bufend, pad_char, padded);
635 }
636
637 bufsize = bufsize - (bufend - rslt) + 1;
638 memmove(rslt, bufend, bufsize);
639 free(avalue);
640 return (rslt);
641 }
642