xref: /freebsd/lib/libc/stdlib/strfmon.c (revision 9729f076e4d93c5a37e78d427bfe0f1ab99bbcc6)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include <sys/types.h>
39 #include <ctype.h>
40 #include <errno.h>
41 #include <limits.h>
42 #include <locale.h>
43 #include <monetary.h>
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 
49 #include "xlocale_private.h"
50 
51 /* internal flags */
52 #define	NEED_GROUPING		0x01	/* print digits grouped (default) */
53 #define	SIGN_POSN_USED		0x02	/* '+' or '(' usage flag */
54 #define	LOCALE_POSN		0x04	/* use locale defined +/- (default) */
55 #define	PARENTH_POSN		0x08	/* enclose negative amount in () */
56 #define	SUPPRESS_CURR_SYMBOL	0x10	/* suppress the currency from output */
57 #define	LEFT_JUSTIFY		0x20	/* left justify */
58 #define	USE_INTL_CURRENCY	0x40	/* use international currency symbol */
59 #define	IS_NEGATIVE		0x80	/* is argument value negative ? */
60 
61 /* internal macros */
62 #define	PRINT(CH) do {						\
63 	if (dst >= s + maxsize)				\
64 		goto e2big_error;				\
65 	*dst++ = CH;						\
66 } while (0)
67 
68 #define	PRINTS(STR) do {					\
69 	char *tmps = STR;					\
70 	while (*tmps != '\0')					\
71 		PRINT(*tmps++);					\
72 } while (0)
73 
74 #define	GET_NUMBER(VAR) do {					\
75 	VAR = 0;						\
76 	while (isdigit((unsigned char)*fmt)) {			\
77 		if (VAR > INT_MAX / 10)				\
78 			goto e2big_error;			\
79 		VAR *= 10;					\
80 		VAR += *fmt - '0';				\
81 		if (VAR < 0)					\
82 			goto e2big_error;			\
83 		fmt++;						\
84 	}							\
85 } while (0)
86 
87 #define	GRPCPY(howmany) do {					\
88 	int i = howmany;					\
89 	while (i-- > 0) {					\
90 		avalue_size--;					\
91 		*--bufend = *(avalue + avalue_size + padded);	\
92 	}							\
93 } while (0)
94 
95 #define	GRPSEP do {						\
96 	bufend -= thousands_sep_size;				\
97 	memcpy(bufend, thousands_sep, thousands_sep_size);	\
98 	groups++;						\
99 } while (0)
100 
101 static void __setup_vars(int, char *, char *, char *, char **);
102 static int __calc_left_pad(int, char *);
103 static char *__format_grouped_double(double, int *, int, int, int);
104 
105 static ssize_t
106 vstrfmon_l(char * __restrict s, size_t maxsize, locale_t loc,
107     const char * __restrict format, va_list ap)
108 {
109 	char		*dst;		/* output destination pointer */
110 	const char	*fmt;		/* current format poistion pointer */
111 	struct lconv	*lc;		/* pointer to lconv structure */
112 	char		*asciivalue;	/* formatted double pointer */
113 
114 	int		flags;		/* formatting options */
115 	int		pad_char;	/* padding character */
116 	int		pad_size;	/* pad size */
117 	int		width;		/* field width */
118 	int		left_prec;	/* left precision */
119 	int		right_prec;	/* right precision */
120 	double		value;		/* just value */
121 	char		space_char = ' '; /* space after currency */
122 
123 	char		cs_precedes,	/* values gathered from struct lconv */
124 			sep_by_space,
125 			sign_posn,
126 			*signstr,
127 			*currency_symbol;
128 
129 	char		*tmpptr;	/* temporary vars */
130 	int		sverrno;
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) {
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 		value = 0;		/* we have no value to print now */
162 
163 		/* Flags */
164 		while (1) {
165 			switch (*++fmt) {
166 				case '=':	/* fill character */
167 					pad_char = *++fmt;
168 					if (pad_char == '\0')
169 						goto format_error;
170 					continue;
171 				case '^':	/* not group currency  */
172 					flags &= ~(NEED_GROUPING);
173 					continue;
174 				case '+':	/* use locale defined signs */
175 					if (flags & SIGN_POSN_USED)
176 						goto format_error;
177 					flags |= (SIGN_POSN_USED|LOCALE_POSN);
178 					continue;
179 				case '(':	/* enclose negatives with () */
180 					if (flags & SIGN_POSN_USED)
181 						goto format_error;
182 					flags |= (SIGN_POSN_USED|PARENTH_POSN);
183 					continue;
184 				case '!':	/* suppress currency symbol */
185 					flags |= SUPPRESS_CURR_SYMBOL;
186 					continue;
187 				case '-':	/* alignment (left)  */
188 					flags |= LEFT_JUSTIFY;
189 					continue;
190 				default:
191 					break;
192 			}
193 			break;
194 		}
195 
196 		/* field Width */
197 		if (isdigit((unsigned char)*fmt)) {
198 			GET_NUMBER(width);
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((unsigned char)*++fmt))
209 				goto format_error;
210 			GET_NUMBER(left_prec);
211 			if ((unsigned int)left_prec >= maxsize - (dst - s))
212 				goto e2big_error;
213 		}
214 
215 		/* Right precision */
216 		if (*fmt == '.') {
217 			if (!isdigit((unsigned char)*++fmt))
218 				goto format_error;
219 			GET_NUMBER(right_prec);
220 			if ((unsigned int)right_prec >= maxsize - (dst - s) -
221 			    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:	/* required character is missing or
234 					   premature EOS */
235 				goto format_error;
236 		}
237 
238 		if (currency_symbol != NULL)
239 			free(currency_symbol);
240 		if (flags & USE_INTL_CURRENCY) {
241 			currency_symbol = strdup(lc->int_curr_symbol);
242 			if (currency_symbol != NULL &&
243 			    strlen(currency_symbol) > 3) {
244 				space_char = currency_symbol[3];
245 				currency_symbol[3] = '\0';
246 			}
247 		} else
248 			currency_symbol = strdup(lc->currency_symbol);
249 
250 		if (currency_symbol == NULL)
251 			goto end_error;			/* ENOMEM. */
252 
253 		/* value itself */
254 		value = va_arg(ap, double);
255 
256 		/* detect sign */
257 		if (value < 0) {
258 			flags |= IS_NEGATIVE;
259 			value = -value;
260 		}
261 
262 		/* fill left_prec with amount of padding chars */
263 		if (left_prec >= 0) {
264 			pad_size = __calc_left_pad((flags ^ IS_NEGATIVE),
265 							currency_symbol) -
266 				   __calc_left_pad(flags, currency_symbol);
267 			if (pad_size < 0)
268 				pad_size = 0;
269 		}
270 
271 		if (asciivalue != NULL)
272 			free(asciivalue);
273 		asciivalue = __format_grouped_double(value, &flags,
274 				left_prec, right_prec, pad_char);
275 		if (asciivalue == NULL)
276 			goto end_error;		/* errno already set     */
277 						/* to ENOMEM by malloc() */
278 
279 		/* set some variables for later use */
280 		__setup_vars(flags, &cs_precedes, &sep_by_space,
281 				&sign_posn, &signstr);
282 
283 		/*
284 		 * Description of some LC_MONETARY's values:
285 		 *
286 		 * p_cs_precedes & n_cs_precedes
287 		 *
288 		 * = 1 - $currency_symbol precedes the value
289 		 *       for a monetary quantity with a non-negative value
290 		 * = 0 - symbol succeeds the value
291 		 *
292 		 * p_sep_by_space & n_sep_by_space
293 		 *
294 		 * = 0 - no space separates $currency_symbol
295 		 *       from the value for a monetary quantity with a
296 		 *       non-negative value
297 		 * = 1 - space separates the symbol from the value
298 		 * = 2 - space separates the symbol and the sign string,
299 		 *       if adjacent; otherwise, a space separates
300 		 *       the sign string from the value
301 		 *
302 		 * p_sign_posn & n_sign_posn
303 		 *
304 		 * = 0 - parentheses enclose the quantity and the
305 		 *       $currency_symbol
306 		 * = 1 - the sign string precedes the quantity and the
307 		 *       $currency_symbol
308 		 * = 2 - the sign string succeeds the quantity and the
309 		 *       $currency_symbol
310 		 * = 3 - the sign string precedes the $currency_symbol
311 		 * = 4 - the sign string succeeds the $currency_symbol
312 		 *
313 		 */
314 
315 		tmpptr = dst;
316 
317 		while (pad_size-- > 0)
318 			PRINT(' ');
319 
320 		if (sign_posn == 0 && (flags & IS_NEGATIVE))
321 			PRINT('(');
322 
323 		if (cs_precedes == 1) {
324 			if (sign_posn == 1 || sign_posn == 3) {
325 				PRINTS(signstr);
326 				if (sep_by_space == 2)		/* XXX: ? */
327 					PRINT(' ');
328 			}
329 
330 			if (!(flags & SUPPRESS_CURR_SYMBOL)) {
331 				PRINTS(currency_symbol);
332 
333 				if (sign_posn == 4) {
334 					if (sep_by_space == 2)
335 						PRINT(space_char);
336 					PRINTS(signstr);
337 					if (sep_by_space == 1)
338 						PRINT(' ');
339 				} else if (sep_by_space == 1)
340 					PRINT(space_char);
341 			}
342 		} else if (sign_posn == 1) {
343 			PRINTS(signstr);
344 			if (sep_by_space == 2)
345 				PRINT(' ');
346 		}
347 
348 		PRINTS(asciivalue);
349 
350 		if (cs_precedes == 0) {
351 			if (sign_posn == 3) {
352 				if (sep_by_space == 1)
353 					PRINT(' ');
354 				PRINTS(signstr);
355 			}
356 
357 			if (!(flags & SUPPRESS_CURR_SYMBOL)) {
358 				if ((sign_posn == 3 && sep_by_space == 2)
359 				    || (sep_by_space == 1
360 				    && (sign_posn == 0
361 				    || sign_posn == 1
362 				    || sign_posn == 2
363 				    || sign_posn == 4)))
364 					PRINT(space_char);
365 				PRINTS(currency_symbol); /* XXX: len */
366 				if (sign_posn == 4) {
367 					if (sep_by_space == 2)
368 						PRINT(' ');
369 					PRINTS(signstr);
370 				}
371 			}
372 		}
373 
374 		if (sign_posn == 2) {
375 			if (sep_by_space == 2)
376 				PRINT(' ');
377 			PRINTS(signstr);
378 		}
379 
380 		if (sign_posn == 0) {
381 			if (flags & IS_NEGATIVE)
382 				PRINT(')');
383 			else if (left_prec >= 0)
384 				PRINT(' ');
385 		}
386 
387 		if (dst - tmpptr < width) {
388 			if (flags & LEFT_JUSTIFY) {
389 				while (dst - tmpptr < width)
390 					PRINT(' ');
391 			} else {
392 				pad_size = dst - tmpptr;
393 				memmove(tmpptr + width - pad_size, tmpptr,
394 				    pad_size);
395 				memset(tmpptr, ' ', width - pad_size);
396 				dst += width - pad_size;
397 			}
398 		}
399 	}
400 
401 	PRINT('\0');
402 	free(asciivalue);
403 	free(currency_symbol);
404 	return (dst - s - 1);	/* return size of put data except trailing '\0' */
405 
406 e2big_error:
407 	errno = E2BIG;
408 	goto end_error;
409 
410 format_error:
411 	errno = EINVAL;
412 
413 end_error:
414 	sverrno = errno;
415 	if (asciivalue != NULL)
416 		free(asciivalue);
417 	if (currency_symbol != NULL)
418 		free(currency_symbol);
419 	errno = sverrno;
420 	return (-1);
421 }
422 
423 static void
424 __setup_vars(int flags, char *cs_precedes, char *sep_by_space,
425     char *sign_posn, char **signstr)
426 {
427 	struct lconv *lc = localeconv();
428 
429 	if ((flags & IS_NEGATIVE) && (flags & USE_INTL_CURRENCY)) {
430 		*cs_precedes = lc->int_n_cs_precedes;
431 		*sep_by_space = lc->int_n_sep_by_space;
432 		*sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_n_sign_posn;
433 		*signstr = (lc->negative_sign[0] == '\0') ? "-"
434 		    : lc->negative_sign;
435 	} else if (flags & USE_INTL_CURRENCY) {
436 		*cs_precedes = lc->int_p_cs_precedes;
437 		*sep_by_space = lc->int_p_sep_by_space;
438 		*sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_p_sign_posn;
439 		*signstr = lc->positive_sign;
440 	} else if (flags & IS_NEGATIVE) {
441 		*cs_precedes = lc->n_cs_precedes;
442 		*sep_by_space = lc->n_sep_by_space;
443 		*sign_posn = (flags & PARENTH_POSN) ? 0 : lc->n_sign_posn;
444 		*signstr = (lc->negative_sign[0] == '\0') ? "-"
445 		    : lc->negative_sign;
446 	} else {
447 		*cs_precedes = lc->p_cs_precedes;
448 		*sep_by_space = lc->p_sep_by_space;
449 		*sign_posn = (flags & PARENTH_POSN) ? 0 : lc->p_sign_posn;
450 		*signstr = lc->positive_sign;
451 	}
452 
453 	/* Set default values for unspecified information. */
454 	if (*cs_precedes != 0)
455 		*cs_precedes = 1;
456 	if (*sep_by_space == CHAR_MAX)
457 		*sep_by_space = 0;
458 	if (*sign_posn == CHAR_MAX)
459 		*sign_posn = 0;
460 }
461 
462 static int
463 __calc_left_pad(int flags, char *cur_symb)
464 {
465 	char cs_precedes, sep_by_space, sign_posn, *signstr;
466 	int left_chars = 0;
467 
468 	__setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn, &signstr);
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,
518     int left_prec, int right_prec, int pad_char)
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 	struct lconv	*lc = localeconv();
531 	char		*grouping;
532 	const char	*decimal_point;
533 	const char	*thousands_sep;
534 	size_t		decimal_point_size;
535 	size_t		thousands_sep_size;
536 
537 	int groups = 0;
538 
539 	grouping = lc->mon_grouping;
540 	decimal_point = lc->mon_decimal_point;
541 	if (*decimal_point == '\0')
542 		decimal_point = lc->decimal_point;
543 	thousands_sep = lc->mon_thousands_sep;
544 	if (*thousands_sep == '\0')
545 		thousands_sep = lc->thousands_sep;
546 
547 	decimal_point_size = strlen(decimal_point);
548 	thousands_sep_size = strlen(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 * (1 + thousands_sep_size) + decimal_point_size +
576 	    1;
577 	rslt = calloc(1, bufsize);
578 	if (rslt == NULL) {
579 		free(avalue);
580 		return (NULL);
581 	}
582 	bufend = rslt + bufsize - 1;	/* reserve space for trailing '\0' */
583 
584 	/* skip spaces at beginning */
585 	padded = 0;
586 	while (avalue[padded] == ' ') {
587 		padded++;
588 		avalue_size--;
589 	}
590 
591 	if (right_prec > 0) {
592 		bufend -= right_prec;
593 		memcpy(bufend, avalue + avalue_size + padded - right_prec,
594 		    right_prec);
595 		bufend -= decimal_point_size;
596 		memcpy(bufend, decimal_point, decimal_point_size);
597 		avalue_size -= (right_prec + 1);
598 	}
599 
600 	if ((*flags & NEED_GROUPING) &&
601 	    thousands_sep_size > 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 	} else {
626 		bufend -= avalue_size;
627 		memcpy(bufend, avalue + padded, avalue_size);
628 		/* decrease assumed $decimal_point */
629 		if (right_prec == 0)
630 			padded -= decimal_point_size;
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 = rslt + bufsize - bufend;
640 	memmove(rslt, bufend, bufsize);
641 	free(avalue);
642 	return (rslt);
643 }
644 
645 ssize_t
646 strfmon(char * __restrict s, size_t maxsize, const char * __restrict format,
647     ...)
648 {
649 	size_t ret;
650 	va_list ap;
651 
652 	va_start(ap, format);
653 	ret = vstrfmon_l(s, maxsize, __get_locale(), format, ap);
654 	va_end(ap);
655 
656 	return (ret);
657 }
658 
659 ssize_t
660 strfmon_l(char * __restrict s, size_t maxsize, locale_t loc,
661     const char * __restrict format, ...)
662 {
663 	size_t ret;
664 	va_list ap;
665 
666 	va_start(ap, format);
667 	ret = vstrfmon_l(s, maxsize, loc, format, ap);
668 	va_end(ap);
669 
670 	return (ret);
671 }
672