xref: /netbsd-src/lib/libc/stdlib/strfmon.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: strfmon.c,v 1.13 2017/11/27 23:54:28 maya 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.13 2017/11/27 23:54:28 maya 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 			    strlen(currency_symbol) > 3) {
246 				space_char = currency_symbol[3];
247 				currency_symbol[3] = '\0';
248 			}
249 
250 		} else
251 			currency_symbol = strdup(lc->currency_symbol);
252 
253 		if (currency_symbol == NULL)
254 			goto end_error;			/* ENOMEM. */
255 
256 		/* value itself */
257 		value = va_arg(ap, double);
258 
259 		/* detect sign */
260 		if (value < 0) {
261 			flags |= IS_NEGATIVE;
262 			value = -value;
263 		}
264 
265 		/* fill left_prec with amount of padding chars */
266 		if (left_prec >= 0) {
267 			pad_size = __calc_left_pad(lc, (flags ^ IS_NEGATIVE),
268 							currency_symbol) -
269 				   __calc_left_pad(lc, flags, currency_symbol);
270 			if (pad_size < 0)
271 				pad_size = 0;
272 		}
273 
274 		asciivalue = __format_grouped_double(lc, value, &flags,
275 				left_prec, right_prec, pad_char);
276 		if (asciivalue == NULL)
277 			goto end_error;		/* errno already set     */
278 						/* to ENOMEM by malloc() */
279 
280 		/* set some variables for later use */
281 		__setup_vars(lc, flags, &cs_precedes, &sep_by_space,
282 				&sign_posn, &signstr);
283 
284 		/*
285 		 * Description of some LC_MONETARY's values:
286 		 *
287 		 * p_cs_precedes & n_cs_precedes
288 		 *
289 		 * = 1 - $currency_symbol precedes the value
290 		 *       for a monetary quantity with a non-negative value
291 		 * = 0 - symbol succeeds the value
292 		 *
293 		 * p_sep_by_space & n_sep_by_space
294                  *
295 		 * = 0 - no space separates $currency_symbol
296 		 *       from the value for a monetary quantity with a
297 		 *	 non-negative value
298 		 * = 1 - space separates the symbol from the value
299 		 * = 2 - space separates the symbol and the sign string,
300 		 *       if adjacent.
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 & SUPRESS_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 
345 		PRINTS(asciivalue);
346 
347 		if (cs_precedes == 0) {
348 			if (sign_posn == 3) {
349 				if (sep_by_space == 1)
350 					PRINT(' ');
351 				PRINTS(signstr);
352 			}
353 
354 			if (!(flags & SUPRESS_CURR_SYMBOL)) {
355 				if ((sign_posn == 3 && sep_by_space == 2)
356 				    || (sep_by_space == 1
357 				    && (sign_posn == 0
358 				    || sign_posn == 1
359 				    || sign_posn == 2
360 				    || sign_posn == 4)))
361 					PRINT(space_char);
362 				PRINTS(currency_symbol); /* XXX: len */
363 				if (sign_posn == 4) {
364 					if (sep_by_space == 2)
365 						PRINT(' ');
366 					PRINTS(signstr);
367 				}
368 			}
369 		}
370 
371 		if (sign_posn == 2) {
372 			if (sep_by_space == 2)
373 				PRINT(' ');
374 			PRINTS(signstr);
375 		}
376 
377 		if (sign_posn == 0 && (flags & IS_NEGATIVE))
378 			PRINT(')');
379 
380 		if (dst - tmpptr < width) {
381 			if (flags & LEFT_JUSTIFY) {
382 				while (dst - tmpptr < width)
383 					PRINT(' ');
384 			} else {
385 				_DIAGASSERT(__type_fit(int, dst - tmpptr));
386 				pad_size = dst - tmpptr;
387 				memmove(tmpptr + width-pad_size, tmpptr,
388 				    (size_t) pad_size);
389 				memset(tmpptr, ' ', (size_t) width-pad_size);
390 				dst += width-pad_size;
391 			}
392 		}
393 	}
394 
395 	PRINT('\0');
396 	free(asciivalue);
397 	free(currency_symbol);
398 	return (dst - s - 1);	/* return size of put data except trailing '\0' */
399 
400 e2big_error:
401 	errno = E2BIG;
402 	goto end_error;
403 
404 format_error:
405 	errno = EINVAL;
406 
407 end_error:
408 	sverrno = errno;
409 	if (asciivalue != NULL)
410 		free(asciivalue);
411 	if (currency_symbol != NULL)
412 		free(currency_symbol);
413 	errno = sverrno;
414 	return (-1);
415 }
416 
417 static void
418 __setup_vars(struct lconv *lc, int flags, char *cs_precedes, char *sep_by_space,
419 		char *sign_posn, const char **signstr) {
420 
421 	if ((flags & IS_NEGATIVE) && (flags & USE_INTL_CURRENCY)) {
422 		*cs_precedes = lc->int_n_cs_precedes;
423 		*sep_by_space = lc->int_n_sep_by_space;
424 		*sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_n_sign_posn;
425 		*signstr = (*lc->negative_sign == '\0') ? "-"
426 		    : lc->negative_sign;
427 	} else if (flags & USE_INTL_CURRENCY) {
428 		*cs_precedes = lc->int_p_cs_precedes;
429 		*sep_by_space = lc->int_p_sep_by_space;
430 		*sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_p_sign_posn;
431 		*signstr = lc->positive_sign;
432 	} else if (flags & IS_NEGATIVE) {
433 		*cs_precedes = lc->n_cs_precedes;
434 		*sep_by_space = lc->n_sep_by_space;
435 		*sign_posn = (flags & PARENTH_POSN) ? 0 : lc->n_sign_posn;
436 		*signstr = (*lc->negative_sign == '\0') ? "-"
437 		    : lc->negative_sign;
438 	} else {
439 		*cs_precedes = lc->p_cs_precedes;
440 		*sep_by_space = lc->p_sep_by_space;
441 		*sign_posn = (flags & PARENTH_POSN) ? 0 : lc->p_sign_posn;
442 		*signstr = lc->positive_sign;
443 	}
444 
445 	/* Set default values for unspecified information. */
446 	if (*cs_precedes != 0)
447 		*cs_precedes = 1;
448 	if ((unsigned char)*sep_by_space == NBCHAR_MAX)
449 		*sep_by_space = 1;
450 	if ((unsigned char)*sign_posn == NBCHAR_MAX)
451 		*sign_posn = 0;
452 }
453 
454 static int
455 __calc_left_pad(struct lconv *lc, int flags, char *cur_symb) {
456 
457 	char cs_precedes, sep_by_space, sign_posn;
458 	const char *signstr;
459 	size_t left_chars = 0;
460 
461 	__setup_vars(lc, flags, &cs_precedes, &sep_by_space, &sign_posn, &signstr);
462 
463 	if (cs_precedes != 0) {
464 		left_chars += strlen(cur_symb);
465 		if (sep_by_space != 0)
466 			left_chars++;
467 	}
468 
469 	switch (sign_posn) {
470 		case 1:
471 			left_chars += strlen(signstr);
472 			break;
473 		case 3:
474 		case 4:
475 			if (cs_precedes != 0)
476 				left_chars += strlen(signstr);
477 	}
478 	_DIAGASSERT(__type_fit(int, left_chars));
479 	return (int)left_chars;
480 }
481 
482 static int
483 get_groups(int size, char *grouping) {
484 
485 	int	chars = 0;
486 
487 	if ((unsigned char)*grouping == NBCHAR_MAX || *grouping <= 0)	/* no grouping ? */
488 		return (0);
489 
490 	while (size > (int)*grouping) {
491 		chars++;
492 		size -= (int)*grouping++;
493 		/* no more grouping ? */
494 		if ((unsigned char)*grouping == NBCHAR_MAX)
495 			break;
496 		/* rest grouping with same value ? */
497 		if (*grouping == 0) {
498 			chars += (size - 1) / *(grouping - 1);
499 			break;
500 		}
501 	}
502 	return (chars);
503 }
504 
505 /* convert double to ASCII */
506 static char *
507 __format_grouped_double(struct lconv *lc, double value, int *flags,
508 			int left_prec, int right_prec, int pad_char) {
509 
510 	char		*rslt;
511 	char		*avalue;
512 	int		avalue_size;
513 
514 	size_t		bufsize;
515 	char		*bufend;
516 
517 	int		padded;
518 
519 	char		*grouping;
520 	char		decimal_point;
521 	char		thousands_sep;
522 
523 	int groups = 0;
524 
525 	grouping = lc->mon_grouping;
526 	decimal_point = *lc->mon_decimal_point;
527 	if (decimal_point == '\0')
528 		decimal_point = *lc->decimal_point;
529 	thousands_sep = *lc->mon_thousands_sep;
530 	if (thousands_sep == '\0')
531 		thousands_sep = *lc->thousands_sep;
532 
533 	/* fill left_prec with default value */
534 	if (left_prec == -1)
535 		left_prec = 0;
536 
537 	/* fill right_prec with default value */
538 	if (right_prec == -1) {
539                 if (*flags & USE_INTL_CURRENCY)
540                         right_prec = lc->int_frac_digits;
541                 else
542                         right_prec = lc->frac_digits;
543 
544 		if (right_prec == CHAR_MAX)	/* POSIX locale ? */
545 			right_prec = 2;
546 	}
547 
548 	if (*flags & NEED_GROUPING)
549 		left_prec += get_groups(left_prec, grouping);
550 
551 	/* convert to string */
552 	avalue_size = asprintf(&avalue, "%*.*f", left_prec + right_prec + 1,
553 	    right_prec, value);
554 	if (avalue_size < 0)
555 		return (NULL);
556 
557 	/* make sure that we've enough space for result string */
558 	bufsize = avalue_size * 2 + 1;
559 	rslt = calloc(1, bufsize);
560 	if (rslt == NULL) {
561 		free(avalue);
562 		return (NULL);
563 	}
564 	bufend = rslt + bufsize - 1;	/* reserve space for trailing '\0' */
565 
566 	/* skip spaces at beggining */
567 	padded = 0;
568 	while (avalue[padded] == ' ') {
569 		padded++;
570 		avalue_size--;
571 	}
572 
573 	if (right_prec > 0) {
574 		bufend -= right_prec;
575 		memcpy(bufend, avalue + avalue_size+padded-right_prec,
576 		    (size_t) right_prec);
577 		*--bufend = decimal_point;
578 		avalue_size -= (right_prec + 1);
579 	}
580 
581         /* XXX: Why not use %' instead? */
582 	if ((*flags & NEED_GROUPING) &&
583 	    thousands_sep != '\0' &&	/* XXX: need investigation */
584 	    (unsigned char)*grouping != NBCHAR_MAX &&
585 	    *grouping > 0) {
586 		while (avalue_size > (int)*grouping) {
587 			GRPCPY(*grouping);
588 			GRPSEP;
589 			grouping++;
590 
591 			/* no more grouping ? */
592 			if ((unsigned char)*grouping == NBCHAR_MAX)
593 				break;
594 
595 			/* rest grouping with same value ? */
596 			if (*grouping == 0) {
597 				grouping--;
598 				while (avalue_size > *grouping) {
599 					GRPCPY(*grouping);
600 					GRPSEP;
601 				}
602 			}
603 		}
604 		if (avalue_size != 0)
605 			GRPCPY(avalue_size);
606 		padded -= groups;
607 
608 	} else {
609 		bufend -= avalue_size;
610 		memcpy(bufend, avalue+padded, (size_t) avalue_size);
611 		if (right_prec == 0)
612 			padded--;	/* decrease assumed $decimal_point */
613 	}
614 
615 	/* do padding with pad_char */
616 	if (padded > 0) {
617 		bufend -= padded;
618 		memset(bufend, pad_char, (size_t) padded);
619 	}
620 
621 	memmove(rslt, bufend, bufend - rslt + 1);
622 	free(avalue);
623 	return (rslt);
624 }
625 
626 ssize_t
627 strfmon(char * __restrict s, size_t maxsize, const char * __restrict format,
628     ...)
629 {
630 	ssize_t rv;
631 	va_list ap;
632 
633 	va_start(ap, format);
634 	rv = vstrfmon_l(s, maxsize, _current_locale(), format, ap);
635 	va_end(ap);
636 
637 	return rv;
638 }
639 
640 ssize_t
641 strfmon_l(char * __restrict s, size_t maxsize, locale_t loc,
642     const char * __restrict format, ...)
643 {
644 	ssize_t rv;
645 	va_list ap;
646 
647 	va_start(ap, format);
648 	rv = vstrfmon_l(s, maxsize, loc, format, ap);
649 	va_end(ap);
650 
651 	return rv;
652 }
653