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