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