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