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