xref: /freebsd/lib/libc/stdlib/strfmon.c (revision 0fddbf874719b9bd50cf66ac26d1140bb3f2be69)
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 		if (cs_precedes == 1) {
307 			if (sign_posn == 1 || sign_posn == 3) {
308 				PRINTS(signstr);
309 				if (sep_by_space == 2)		/* XXX: ? */
310 					PRINT(' ');
311 			}
312 
313 			if (!(flags & SUPRESS_CURR_SYMBOL)) {
314 				PRINTS(currency_symbol);
315 
316 				if (sign_posn == 4) {
317 					if (sep_by_space == 2)
318 						PRINT(space_char);
319 					PRINTS (signstr);
320 					if (sep_by_space == 1)
321 						PRINT(' ');
322 				}
323 				else
324 					if (sep_by_space == 1)
325 						PRINT(space_char);
326 			}
327 		}
328 		else
329 			if (sign_posn == 1)
330 				PRINTS(signstr);
331 
332 		PRINTS(asciivalue);
333 
334 		if (cs_precedes == 0) {
335 			if (sign_posn == 3) {
336 				if (sep_by_space == 1)
337 					PRINT(' ');
338 				PRINTS(signstr);
339 			}
340 
341 			if (!(flags & SUPRESS_CURR_SYMBOL)) {
342 				if ((sign_posn == 3 && sep_by_space == 2)
343 					|| (sep_by_space == 1
344 						&& (sign_posn = 0
345 						    || sign_posn == 1
346 						    || sign_posn == 2
347 						    || sign_posn == 4)))
348 						PRINT(space_char);
349 				PRINTS(currency_symbol); /* XXX: len */
350 				if (sign_posn == 4) {
351 					if (sep_by_space == 2)
352 						PRINT(' ');
353 					PRINTS(signstr);
354 				}
355 			}
356 		}
357 
358 		if (sign_posn == 2) {
359 			if (sep_by_space == 2)
360 				PRINT(' ');
361 			PRINTS(signstr);
362 		}
363 
364 		if (sign_posn == 0 && (flags & IS_NEGATIVE))
365 			PRINT(')');
366 
367 		if (dst - tmpptr < width) {
368 			if (flags & LEFT_JUSTIFY) {
369 				while (dst - tmpptr <= width)
370 					PRINT(' ');
371 			} else {
372 				pad_size = dst-tmpptr;
373 				memmove(tmpptr+width-pad_size, tmpptr, 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 	return (dst - s - 1);	/* return size of put data except trailing '\0' */
383 
384 e2big_error:
385 	errno = E2BIG;
386 	goto end_error;
387 
388 format_error:
389 	errno = EINVAL;
390 
391 end_error:
392 	if (asciivalue != NULL)
393 		free(asciivalue);
394 	if (currency_symbol != NULL)
395 		free(currency_symbol);
396 	va_end(ap);
397 	return (-1);
398 }
399 
400 static void
401 __setup_vars(int flags, char *cs_precedes, char *sep_by_space,
402 		char *sign_posn, char **signstr) {
403 
404 	struct lconv *lc = localeconv();
405 
406 	if (flags & IS_NEGATIVE) {
407 		*cs_precedes = lc->n_cs_precedes;
408 		*sep_by_space = lc->n_sep_by_space;
409 		*sign_posn = (flags & PARENTH_POSN)? 0 : lc->n_sign_posn;
410 		*signstr = (lc->negative_sign == '\0')? "-" : lc->negative_sign;
411 	} else {
412 		*cs_precedes = lc->p_cs_precedes;
413 		*sep_by_space = lc->p_sep_by_space;
414 		*sign_posn = (flags & PARENTH_POSN)? 0 : lc->p_sign_posn;
415 		*signstr = lc->positive_sign;
416 	}
417 
418 	/* Set defult values for unspecified information. */
419 	if (*cs_precedes != 0)
420 		*cs_precedes = 1;
421 	if (*sep_by_space == CHAR_MAX)
422 		*sep_by_space = 0;
423 	if (*sign_posn == CHAR_MAX)
424 		*sign_posn = 0;
425 }
426 
427 static int
428 __calc_left_pad(int flags, char *cur_symb) {
429 
430 	char cs_precedes, sep_by_space, sign_posn, *signstr;
431 	int left_chars = 0;
432 
433 	__setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn, &signstr);
434 
435 	if (cs_precedes != 0) {
436 		left_chars += strlen(cur_symb);
437 		if (sep_by_space != 0)
438 			left_chars++;
439 	}
440 
441 	switch (sign_posn) {
442 		case 1:
443 			left_chars += strlen(signstr);
444 			break;
445 		case 3:
446 		case 4:
447 			if (cs_precedes != 0)
448 				left_chars +=  strlen(signstr);
449 	}
450 	return left_chars;
451 }
452 
453 static int
454 get_groups(int size, char *grouping) {
455 
456 	int	chars = 0;
457 
458 	if (*grouping == CHAR_MAX || *grouping <= 0)	/* no grouping ? */
459 		return 0;
460 
461 	while (size > (int)*grouping) {
462 		chars++;
463 		size -= (int)*grouping++;
464 		/* no more grouping ? */
465 		if (*grouping == CHAR_MAX)
466 			break;
467 		/* rest grouping with same value ? */
468 		if (*grouping == 0) {
469 			chars += (size - 1) / *(grouping - 1);
470 			break;
471 		}
472 	}
473 	return chars;
474 }
475 
476 /* convert double to ASCII */
477 static char *
478 __format_grouped_double(double value, int *flags,
479 			int left_prec, int right_prec, int pad_char) {
480 
481 	char		*rslt;
482 	char		*avalue;
483 	int		avalue_size;
484 	char		fmt[32];
485 
486 	size_t		bufsize;
487 	char		*bufend;
488 
489 	int		padded;
490 
491 	struct lconv	*lc = localeconv();
492 	char		*grouping;
493 	char		decimal_point;
494 	char		thousands_sep;
495 
496 	int groups = 0;
497 
498 	grouping = lc->mon_grouping;
499 	decimal_point = *lc->mon_decimal_point;
500 	if (decimal_point == '\0') {
501 		decimal_point = *lc->decimal_point;
502 		if (decimal_point == '\0')
503 			decimal_point = '.';
504 	}
505 	thousands_sep = *lc->mon_thousands_sep;
506 	if (thousands_sep == '\0') {
507 		thousands_sep = *lc->thousands_sep;
508 	}
509 
510 	/* fill left_prec with default value */
511 	if (left_prec == -1)
512 		left_prec = 0;
513 
514 	/* fill right_prec with default value */
515 	if (right_prec == -1) {
516                 if (*flags & USE_INTL_CURRENCY)
517                         right_prec = lc->int_frac_digits;
518                 else
519                         right_prec = lc->frac_digits;
520 
521 		if (right_prec == CHAR_MAX)	/* POSIX locale ? */
522 			right_prec = 2;
523 	}
524 
525 	if (*flags & NEED_GROUPING)
526 		left_prec += get_groups(left_prec, grouping);
527 
528 	/* convert to string */
529 	snprintf(fmt, sizeof(fmt), "%%%d.%df", left_prec+right_prec+1, right_prec);
530 	avalue_size = asprintf(&avalue, fmt, value);
531 	if (avalue_size < 0)
532 		return NULL;
533 
534 	/* make sure that we've enough space for result string */
535 	bufsize = strlen(avalue)*2+1;
536 	rslt = malloc(bufsize);
537 	if (rslt == NULL) {
538 		free(avalue);
539 		return NULL;
540 	}
541 	memset(rslt, 0, bufsize);
542 	bufend = rslt + bufsize - 1;	/* reserve space for trailing '\0' */
543 
544 	/* skip spaces at beggining */
545 	padded = 0;
546 	while (avalue[padded] == ' ') {
547 		padded++;
548 		avalue_size--;
549 	}
550 
551 	if (right_prec > 0) {
552 		bufend -= right_prec;
553 		memcpy(bufend, avalue+avalue_size+padded-right_prec, right_prec);
554 		*--bufend = decimal_point;
555 		avalue_size -= (right_prec + 1);
556 	}
557 
558 	if ((*flags & NEED_GROUPING) &&
559 		thousands_sep != '\0' &&	/* XXX: need investigation */
560 		*grouping != CHAR_MAX &&
561 		*grouping > 0) {
562 
563 #define GRPCPY(howmany) {					\
564 	int i = howmany;					\
565 	while (i-- > 0) {					\
566 		avalue_size--;					\
567 		*--bufend = *(avalue+avalue_size+padded);	\
568 	}							\
569 }
570 
571 #define GRPSEP	{						\
572 	*--bufend = thousands_sep;				\
573 	groups++;						\
574 }
575 
576 		while (avalue_size > (int)*grouping) {
577 			GRPCPY(*grouping);
578 			GRPSEP;
579 			grouping++;
580 
581 			/* no more grouping ? */
582 			if (*grouping == CHAR_MAX)
583 				break;
584 
585 			/* rest grouping with same value ? */
586 			if (*grouping == 0) {
587 				grouping--;
588 				while (avalue_size > *grouping) {
589 					GRPCPY(*grouping);
590 					GRPSEP;
591 				}
592 			}
593 		}
594 		if (avalue_size != 0)
595 			GRPCPY(avalue_size);
596 		padded -= groups;
597 
598 	} else {
599 		bufend -= avalue_size;
600 		memcpy(bufend, avalue+padded, avalue_size);
601 		if (right_prec == 0)
602 			padded--;	/* decrease assumed $decimal_point */
603 	}
604 
605 	/* do padding with pad_char */
606 	if (padded > 0) {
607 		bufend -= padded;
608 		memset(bufend, pad_char, padded);
609 	}
610 
611 	bufsize = bufsize-(rslt-bufend);
612 	memmove(rslt, bufend, bufsize);
613 	free(avalue);
614 	return rslt;
615 }
616