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