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