Home | History | Annotate | Line # | Download | only in stdlib
      1 /*	$NetBSD: strfmon.c,v 1.25 2026/11/17 11:15:09 kre Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2001 Alexey Zelkin <phantom (at) FreeBSD.org>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  *
     28  */
     29 
     30 #include <sys/cdefs.h>
     31 #if defined(LIBC_SCCS) && !defined(lint)
     32 #if 0
     33 __FBSDID("$FreeBSD: src/lib/libc/stdlib/strfmon.c,v 1.14 2003/03/20 08:18:55 ache Exp $");
     34 #else
     35 __RCSID("$NetBSD: strfmon.c,v 1.25 2026/11/17 11:15:09 kre Exp $");
     36 #endif
     37 #endif /* LIBC_SCCS and not lint */
     38 
     39 #include "namespace.h"
     40 
     41 #include <sys/types.h>
     42 #include <assert.h>
     43 #include <ctype.h>
     44 #include <errno.h>
     45 #include <limits.h>
     46 #include <locale.h>
     47 #include <monetary.h>
     48 #include <stdarg.h>
     49 #include <stddef.h>
     50 #include <stdio.h>
     51 #include <stdlib.h>
     52 #include <string.h>
     53 #include <wchar.h>
     54 
     55 #include "setlocale_local.h"
     56 
     57 /* internal flags */
     58 #define	NEED_GROUPING		0x01	/* print digits grouped (default) */
     59 #define	SIGN_POSN_USED		0x02	/* '+' or '(' usage flag */
     60 #define	LOCALE_POSN		0x04	/* use locale defined +/- (default) */
     61 #define	PARENTH_POSN		0x08	/* enclose negative amount in () */
     62 #define	SUPPRESS_CURR_SYMBOL	0x10	/* suppress the currency from output */
     63 #define	LEFT_JUSTIFY		0x20	/* left justify */
     64 #define	USE_INTL_CURRENCY	0x40	/* use international currency symbol */
     65 #define	IS_NEGATIVE		0x80	/* is argument value negative ? */
     66 
     67 /* internal macros */
     68 #define	PRINT(CH) do {						\
     69 	if (dst >= s + maxsize) 				\
     70 		goto e2big_error;				\
     71 	*dst++ = CH;						\
     72 } while (0)
     73 
     74 #define	PRINTS(STR) do {					\
     75 	const char *tmps = STR;					\
     76 	while (*tmps != '\0')					\
     77 		PRINT(*tmps++);					\
     78 } while (0)
     79 
     80 #define PRINT_WIDE(WCH, CH) do {				\
     81 	int __w__ = __add_wide_char(dst, s + maxsize, (WCH));	\
     82 	int __c__ = (CH);					\
     83 	switch (__w__) {					\
     84 	case -2:	goto e2big_error;		break;	\
     85 	case -1:	if (__c__ != 0) PRINT(__c__);	break;	\
     86 	default:	dst += __w__;			break;	\
     87 	}							\
     88 } while (0)
     89 
     90 #define	GET_NUMBER(VAR, LOC)	do {				\
     91 	VAR = 0;						\
     92 	while (isdigit_l((unsigned char)*fmt, LOC)) {		\
     93 		if (VAR > INT_MAX / 10)				\
     94 			goto e2big_error;			\
     95 		VAR *= 10;					\
     96 		VAR += *fmt - '0';				\
     97 		if (VAR < 0)					\
     98 			goto e2big_error;			\
     99 		fmt++;						\
    100 	}							\
    101 } while (0)
    102 
    103 #define	GRPCPY(howmany) do {					\
    104 	int i = howmany;					\
    105 	while (i-- > 0) {					\
    106 		avalue_size--;					\
    107 		*--bufend = *(avalue + avalue_size + padded);	\
    108 	}							\
    109 } while (0)
    110 
    111 #define	GRPSEP do {						\
    112 	bufend -= thousands_sep_size;				\
    113 	memcpy(bufend, thousands_sep, thousands_sep_size);	\
    114 	groups++;						\
    115 } while (0)
    116 
    117 #define	RANGE_CHECK(v, op, n)					\
    118 	((*(const unsigned char *)(v) op (n)) ||		\
    119 	    (((*(const unsigned char *)(v)) & 0x80) != 0))
    120 
    121 static void __setup_vars(int, char *, char *, char *, const char **,
    122     struct lconv *);
    123 static int __calc_left_pad(int, int, int, struct lconv *);
    124 static int __calc_right_pad(int, int, int, struct lconv *);
    125 static char *__format_grouped_double(double, int *, int *, int, int,
    126     char *, size_t, struct lconv *, locale_t loc);
    127 static int __columns(const char *, locale_t);
    128 static int __count_grps(int, char *);
    129 static int __add_wide_char(char *, char *, wchar_t);
    130 
    131 static char __nullstr[] = "";
    132 
    133 /*
    134  * This would be better as MB_CUR_MAX but that isn't a constant,
    135  * and not using a constant screws with the stack protector, so
    136  * let's not do that.   15 is much too big for any rational encoding
    137  * of a single character, but still so small that an array 16 bytes
    138  * (15 +1 for a \0) on the stack isn't any kind of a problem.
    139  */
    140 #define MAX_ENCODED_CHAR_LEN	15
    141 
    142 static ssize_t
    143 vstrfmon_l(char * __restrict s, size_t maxsize, locale_t loc,
    144     const char * __restrict format, va_list ap)
    145 {
    146 	char 		*dst;		/* output destination pointer */
    147 	const char 	*fmt;		/* current format poistion pointer */
    148 	struct lconv 	*lc;		/* pointer to lconv structure */
    149 	char		*asciivalue;	/* formatted double pointer */
    150 
    151 	int		flags;		/* formatting options */
    152 	char		pad_char[MAX_ENCODED_CHAR_LEN+1];  /* padding char */
    153 	size_t		pad_char_len;
    154 	int		pad_size;	/* pad size */
    155 	int		width;		/* field width */
    156 	int		left_prec;	/* left precision */
    157 	int		right_prec;	/* right precision */
    158 	double		value;		/* just value */
    159 	wchar_t		space_char = L' '; /* space after currency */
    160 
    161 	char		cs_precedes,	/* values gathered from struct lconv */
    162 			sep_by_space,
    163 			sign_posn, osp,
    164 			*currency_symbol;
    165 	const char	*signstr, *othersign;
    166 	int		cs_cols, ss_cols, os_cols;
    167 
    168 	int		cols_used;
    169 
    170 	mbstate_t	mbs;
    171 
    172 	char		*tmpptr;	/* temporary vars */
    173 	int		sverrno;
    174 
    175 	mbstate_t	fmt_state;
    176 	wchar_t		fmt_char;
    177 	size_t		fmt_ch_len;
    178 
    179 	lc = localeconv_l(loc);
    180 	dst = s;
    181 	fmt = format;
    182 	asciivalue = NULL;
    183 	currency_symbol = NULL;
    184 
    185 	(void)mbrtowc(NULL, NULL, 0, &fmt_state);	/* init */
    186 	for (;;) {
    187 		fmt_ch_len = mbrtowc(&fmt_char, fmt, MB_CUR_MAX,
    188 		    &fmt_state);
    189 		if (fmt_ch_len == 0)
    190 			break;
    191 		if (fmt_ch_len == (size_t)-1)	/* errno == EILSEQ */
    192 			goto end_error;
    193 		if (fmt_ch_len == (size_t)-2)
    194 			goto format_error;
    195 
    196 		if (fmt_char != L'%')
    197 			goto literal;
    198 
    199 		/* '%' found ! */
    200 
    201 		/* "%%" mean just '%' */
    202 		if (fmt[1] == '%') {
    203 			fmt++;
    204 	literal:;
    205 			PRINT_WIDE(fmt_char, '?');
    206 			fmt += fmt_ch_len;
    207 			continue;
    208 		}
    209 
    210 		/* set up initial values */
    211 		flags = NEED_GROUPING | LOCALE_POSN;
    212 		pad_char[0] = ' ';	/* padding character is "space" */
    213 		pad_char[1] = '\0';
    214 		pad_char_len = 1;
    215 		pad_size = 0;		/* no padding initially */
    216 		left_prec = -1;		/* no left precision specified */
    217 		right_prec = -1;	/* no right precision specified */
    218 		width = -1;		/* no width specified */
    219 		value = 0;		/* we have no value to print now */
    220 		cols_used = 0;		/* output width in columns */
    221 
    222 		/* Flags */
    223 		for (;;) {
    224 			/*
    225 			 * Once we are in a conversion description
    226 			 * all chars are required to be ascii, except
    227 			 * the one char after a '=' flag, so we can
    228 			 * just read them as bytes ... or this is close
    229 			 * enough for now.
    230 			 */
    231 			switch (*++fmt) {
    232 			case '=':	/* fill character */
    233 				(void)mbrtowc(NULL, NULL, 0, &mbs);
    234 				pad_char_len = mbrtowc(&space_char,
    235 				    ++fmt, MAX_ENCODED_CHAR_LEN, &mbs);
    236 				if (pad_char_len == 0 ||
    237 				    pad_char_len >= MAX_ENCODED_CHAR_LEN)
    238 					goto format_error;
    239 				memcpy(pad_char, fmt, pad_char_len);
    240 				pad_char[pad_char_len] = '\0';
    241 				fmt += pad_char_len - 1;
    242 
    243 				/*
    244 				 * return the borrowed var to its
    245 				 * regularly scheduled purpose
    246 				 */
    247 				space_char = L' ';
    248 				continue;
    249 
    250 			case '^':	/* not group currency  */
    251 				flags &= ~NEED_GROUPING;
    252 				continue;
    253 
    254 			case '+':	/* use locale defined signs */
    255 				if (flags & (SIGN_POSN_USED|PARENTH_POSN))
    256 					goto format_error;
    257 				flags |= SIGN_POSN_USED;
    258 				continue;
    259 
    260 			case '(':	/* enclose negatives with () */
    261 				if (flags & SIGN_POSN_USED)
    262 					goto format_error;
    263 				flags &= ~LOCALE_POSN;	/* was dflt */
    264 				flags |= SIGN_POSN_USED | PARENTH_POSN;
    265 				continue;
    266 
    267 			case '!':	/* suppress currency symbol */
    268 				flags |= SUPPRESS_CURR_SYMBOL;
    269 				continue;
    270 
    271 			case '-':	/* alignment (left)  */
    272 				flags |= LEFT_JUSTIFY;
    273 				continue;
    274 
    275 			default:
    276 				break;
    277 			}
    278 			break;
    279 		}
    280 
    281 		/* field Width */
    282 		if (isdigit_l((unsigned char)*fmt, loc)) {
    283 			ptrdiff_t d = dst - s;
    284 
    285 			GET_NUMBER(width, loc);
    286 
    287 			/*
    288 			 * Do we have enough space to place a number of
    289 			 * the required width ?
    290 			 */
    291 			if ((size_t)(d + width) >= maxsize)
    292 				goto e2big_error;
    293 		}
    294 
    295 		/* Left precision */
    296 		if (*fmt == '#') {
    297 			if (!isdigit_l((unsigned char)*++fmt, loc))
    298 				goto format_error;
    299 			GET_NUMBER(left_prec, loc);
    300 
    301 			if ((unsigned int)left_prec >= maxsize - (dst - s))
    302 				goto e2big_error;
    303 		}
    304 
    305 		/* Right precision */
    306 		if (*fmt == '.') {
    307 			if (!isdigit_l((unsigned char)*++fmt, loc))
    308 				goto format_error;
    309 			GET_NUMBER(right_prec, loc);
    310 
    311 			if ((unsigned int)right_prec >=
    312 			    maxsize - (dst - s) - left_prec)
    313 				goto e2big_error;
    314 		}
    315 
    316 		/* Conversion Characters */
    317 		switch (*fmt++) {
    318 
    319 		case 'i':	/* use international currency format */
    320 			flags |= USE_INTL_CURRENCY;
    321 			break;
    322 
    323 		case 'n':	/* use national currency format */
    324 			flags &= ~USE_INTL_CURRENCY;
    325 			break;
    326 
    327 		default:	/* required character is missing or
    328 				   premature EOS */
    329 			goto format_error;
    330 		}
    331 
    332 		space_char = L' ';	/* to be sure, to be sure... */
    333 		if (currency_symbol != NULL)
    334 			free(currency_symbol);
    335 		if (flags & USE_INTL_CURRENCY) {
    336 			size_t l;
    337 
    338 			currency_symbol = strdup(lc->int_curr_symbol);
    339 			if (currency_symbol != NULL &&
    340 			    /*
    341 			     * should be 3 characters, not bytes
    342 			     * but the international currency symbol
    343 			     * is supposed to be from ISO4217:2015, so
    344 			     * only ASCII, so, just leave this (for now)
    345 			     */
    346 			    (l = strlen(currency_symbol)) > 3) {
    347 				size_t chlen;
    348 				const int e = errno;
    349 
    350 				(void)mbrtowc_l(NULL, NULL, 0, &mbs, loc);
    351 				/* any errno set here gets ignored, we deal */
    352 				chlen = mbrtowc_l(&space_char,
    353 				    currency_symbol + 3, MAX_ENCODED_CHAR_LEN,
    354 				    &mbs, loc);
    355 				if (chlen == 0 ||
    356 				    chlen > MAX_ENCODED_CHAR_LEN ||
    357 				    wcwidth(space_char) != 1)
    358 					space_char = L' ';
    359 				currency_symbol[3] = '\0';
    360 				errno = e;
    361 			}
    362 		} else
    363 			currency_symbol = strdup(lc->currency_symbol);
    364 
    365 		if (currency_symbol == NULL)
    366 			goto end_error;			/* ENOMEM. */
    367 
    368 		cs_cols = __columns(currency_symbol, loc);
    369 		if (cs_cols < 0) {
    370 			cs_cols = 0;
    371 			flags |= SUPPRESS_CURR_SYMBOL;
    372 		}
    373 
    374 		/* value itself */
    375 		value = va_arg(ap, double);
    376 
    377 		/* detect sign */
    378 		if (value < 0) {
    379 			flags |= IS_NEGATIVE;
    380 			value = -value;
    381 		}
    382 
    383 		/*
    384 		 * set some variables for later use
    385 		 */
    386 		/* First a couple for the other sign */
    387 		__setup_vars(flags ^ IS_NEGATIVE, &cs_precedes,
    388 		    &sep_by_space, &osp, &othersign, lc);
    389 		/* And then the the actual data to use */
    390 		__setup_vars(flags, &cs_precedes,
    391 		    &sep_by_space, &sign_posn, &signstr, lc);
    392 
    393 		ss_cols = __columns(signstr, loc);
    394 		if (ss_cols < 0) {
    395 			signstr = __nullstr;
    396 			ss_cols = 0;
    397 		}
    398 		os_cols = __columns(othersign, loc);
    399 		if (os_cols < 0) {
    400 			othersign = __nullstr;
    401 			os_cols = 0;
    402 		}
    403 
    404 #undef	CMP_SP
    405 /*
    406  * Compare +/- sign positions
    407  *
    408  * This gives true if either both are zero, or they are different
    409  * and false only when they are the same and not zero
    410  */
    411 #define CMP_SP(a, b) ((~lc-> a##_sign_posn ^ ~lc-> b##_sign_posn) != 0)
    412 
    413 		/*
    414 		 * If () will be used for negative numbers, it doesn't
    415 		 * matter what the sign strings are.
    416 		 */
    417 		if (flags & PARENTH_POSN) {
    418 			/*
    419 			 * we were given the '(' flag, so
    420 			 * everything is always OK.   **)**
    421 			 */
    422 		} else if (flags & SIGN_POSN_USED) {
    423 			/*
    424 			 * The '+' flag was used
    425 			 */
    426 			if (ss_cols == 0 && os_cols == 0)
    427 				goto format_error;
    428 
    429 			if (strcmp(signstr, othersign) == 0) {
    430 			     /* sign strings identical */
    431 			     /* error if positions the same */
    432 			     if (sign_posn == osp)
    433 				goto format_error;
    434 			}
    435 
    436 			if (sign_posn == 0)
    437 				sign_posn = 1;
    438 			/*
    439 			 * We are instructed to use signs,
    440 			 * and we have suiable strings to use
    441 			 * then all is OK
    442 			 */
    443 		} else if (sign_posn == 0) {
    444 			/*
    445 			 * here the locale has told us to use
    446 			 * parens, which is OK, unless it would
    447 			 * also tell us to use parens for the
    448 			 * values of the other sign.
    449 			 */
    450 			if (osp == 0)
    451 				goto format_error;
    452 
    453 		} else if (ss_cols != os_cols &&
    454 			    (ss_cols > 0 || os_cols > 0)) {
    455 			/*
    456 			 * signs are clearly different, no issue
    457 			 */
    458 		} else if ((ss_cols > 0 || os_cols > 0) &&
    459 			    (strcmp(signstr, othersign) != 0)) {
    460 			/*
    461 			 * sign strings are different, and at least
    462 			 * one has a visible width, also no issue
    463 			 */
    464 		} else if (!(flags & SIGN_POSN_USED) &&
    465 			    ((ss_cols > 0 || os_cols > 0) &&
    466 			     ((flags & USE_INTL_CURRENCY) ?
    467 			        CMP_SP(int_p, int_n) : CMP_SP(p, n)))) {
    468 			/*
    469 			 * '+' flag not used, and sign strings go in
    470 			 * different places, and at least one of them
    471 			 * will be visible, so OK if they look the
    472 			 * same, no issue
    473 			 */
    474 		} else if (ss_cols <= 0 && os_cols <= 0) {
    475 			/*
    476 			 * Replace the negative sign with "-"
    477 			 */
    478 			if (flags & IS_NEGATIVE) {
    479 				signstr = "-";
    480 				ss_cols = 1;
    481 			} else
    482 				os_cols = 1;	/*othersign not used*/
    483 		} else {
    484 			/*
    485 			 * arrange to place a negative sign before
    486 			 * the value, and the positive sign after it.
    487 			 * Now the cases are different!
    488 			 */
    489 			sign_posn = (flags & IS_NEGATIVE) ? 1 : 2;
    490 		}
    491 #undef	CMP_SP
    492 
    493 		if (ss_cols < 0) {
    494 			signstr = __nullstr;
    495 			ss_cols = 0;
    496 		}
    497 		if (os_cols < 0) {
    498 			/* othersign = __nullstr; // not needed */
    499 			os_cols = 0;
    500 		}
    501 
    502 		/* fill left_prec with amount of padding chars */
    503 		if (left_prec >= 0) {
    504 			pad_size = __calc_left_pad((flags ^ IS_NEGATIVE),
    505 				        cs_cols, os_cols, lc)
    506 				 - __calc_left_pad(flags, cs_cols, ss_cols, lc);
    507 
    508 			if (pad_size < 0)
    509 				pad_size = 0;
    510 		}
    511 
    512 		if (asciivalue != NULL)
    513 			free(asciivalue);
    514 		asciivalue = __format_grouped_double(value, &flags, &cols_used,
    515 		    left_prec, right_prec, pad_char, pad_char_len, lc, loc);
    516 		if (asciivalue == NULL)
    517 			goto end_error;		/* errno already set     */
    518 						/* to ENOMEM by malloc() */
    519 
    520 		/*
    521 		 * Description of some LC_MONETARY's values:
    522 		 *
    523 		 * p_cs_precedes & n_cs_precedes
    524 		 *
    525 		 * = 1 - $currency_symbol precedes the value
    526 		 *	 for a monetary quantity with a non-negative value
    527 		 * = 0 - symbol succeeds the value
    528 		 *
    529 		 * p_sep_by_space & n_sep_by_space
    530 		 *
    531 		 * = 0 - no space separates $currency_symbol
    532 		 *	 from the value for a monetary quantity with a
    533 		 *	 non-negative value
    534 		 * = 1 - space separates the symbol from the value
    535 		 * = 2 - space separates the symbol and the sign string,
    536 		 *	 if adjacent.
    537 		 *
    538 		 * p_sign_posn & n_sign_posn
    539 		 *
    540 		 * = 0 - parentheses enclose the quantity and the
    541 		 *	 $currency_symbol
    542 		 * = 1 - the sign string precedes the quantity and the
    543 		 *	 $currency_symbol
    544 		 * = 2 - the sign string succeeds the quantity and the
    545 		 *	 $currency_symbol
    546 		 * = 3 - the sign string precedes the $currency_symbol
    547 		 * = 4 - the sign string succeeds the $currency_symbol
    548 		 *
    549 		 */
    550 
    551 		tmpptr = dst;
    552 
    553 		if (flags & PARENTH_POSN)
    554 			sign_posn = 111;	/* invalid, so no signstr */
    555 
    556 		if ((sign_posn == 0 && !(flags & SIGN_POSN_USED)) ||
    557 		    (flags & (PARENTH_POSN|IS_NEGATIVE)) ==
    558 					(PARENTH_POSN|IS_NEGATIVE)) {
    559 			PRINT('(');
    560 			cols_used++;
    561 		}
    562 
    563 		while (pad_size-- > 0) {
    564 			PRINT(' ');
    565 			cols_used++;
    566 		}
    567 
    568 		if (cs_precedes == 1) {
    569 			if (sign_posn == 1 || sign_posn == 3 ||
    570 			    (sign_posn == 0 && (flags & SIGN_POSN_USED))) {
    571 				PRINTS(signstr);
    572 				cols_used += ss_cols;
    573 				if (sep_by_space == 2) {
    574 					PRINT(' ');
    575 					cols_used++;
    576 				}
    577 			}
    578 
    579 			if (!(flags & SUPPRESS_CURR_SYMBOL)) {
    580 				PRINTS(currency_symbol);
    581 				cols_used += cs_cols;
    582 
    583 				if (sign_posn == 4) {
    584 					if (sep_by_space == 2) {
    585 						PRINT(' ');
    586 						cols_used++;
    587 					}
    588 					PRINTS(signstr);
    589 					if (sep_by_space == 1) {
    590 						PRINT(' ');
    591 						cols_used++;
    592 					}
    593 				} else if (sep_by_space == 1) {
    594 					cols_used++;	/* we know width==1 */
    595 					PRINT_WIDE(space_char, ' ');
    596 				}
    597 			}
    598 		} else if (sign_posn == 1 ||
    599 			  (sign_posn == 0 && (flags & SIGN_POSN_USED))) {
    600 			PRINTS(signstr);
    601 			cols_used += ss_cols;
    602 			if (sep_by_space == 2) {
    603 				PRINT(' ');
    604 				cols_used++;
    605 			}
    606 		}
    607 
    608 		PRINTS(asciivalue);
    609 
    610 		if (cs_precedes == 0) {
    611 			if (sign_posn == 3) {
    612 				if (sep_by_space == 1) {
    613 					PRINT(' ');
    614 					cols_used++;
    615 				}
    616 				PRINTS(signstr);
    617 				cols_used += ss_cols;
    618 			}
    619 
    620 			if (!(flags & SUPPRESS_CURR_SYMBOL)) {
    621 				if ((sign_posn == 3 && sep_by_space == 2)
    622 				    || (sep_by_space == 1
    623 				    && (sign_posn == 0 || sign_posn == 1 ||
    624 					sign_posn == 2 || sign_posn == 4)  )) {
    625 						cols_used++;
    626 						PRINT_WIDE(space_char, ' ');
    627 				}
    628 
    629 				PRINTS(currency_symbol);
    630 				cols_used += cs_cols;
    631 				if (sign_posn == 4) {
    632 					if (sep_by_space == 2) {
    633 						PRINT(' ');
    634 						cols_used++;
    635 					}
    636 					PRINTS(signstr);
    637 					cols_used += ss_cols;
    638 				}
    639 			}
    640 		}
    641 
    642 		if (sign_posn == 2) {
    643 			if (sep_by_space == 2) {
    644 				PRINT(' ');
    645 				cols_used++;
    646 			}
    647 			PRINTS(signstr);
    648 			cols_used += ss_cols;
    649 		}
    650 
    651 		/* if aligning, pad the right side as well */
    652 		if (left_prec >= 0) {
    653 			pad_size = __calc_right_pad((flags ^ IS_NEGATIVE),
    654 					cs_cols, os_cols, lc) -
    655 				  __calc_right_pad(flags, cs_cols, ss_cols, lc);
    656 
    657 			if (pad_size < 0)
    658 				pad_size = 0;
    659 
    660 			while (pad_size-- > 0) {
    661 				PRINT(' ');
    662 				cols_used++;
    663 			}
    664 		}
    665 
    666 		if ((sign_posn == 0 && !(flags & SIGN_POSN_USED)) ||
    667 		    (flags & (PARENTH_POSN|IS_NEGATIVE)) ==
    668 					(PARENTH_POSN|IS_NEGATIVE)) {
    669 			PRINT(')');
    670 			cols_used++;
    671 		}
    672 
    673 		if (cols_used < width) {
    674 			if (flags & LEFT_JUSTIFY) {
    675 				while (cols_used++ < width)
    676 					PRINT(' ');
    677 			} else {
    678 				size_t wps;
    679 
    680 				wps = width - cols_used;
    681 				memmove(tmpptr + wps, tmpptr,
    682 				    (size_t)(dst - tmpptr));
    683 				memset(tmpptr, ' ', wps);
    684 				dst += wps;
    685 			}
    686 		}
    687 	}
    688 
    689 	PRINT('\0');
    690 	free(asciivalue);
    691 	free(currency_symbol);
    692 	return (dst - s - 1);	/* return size of data except trailing '\0' */
    693 
    694  e2big_error:;
    695 	errno = E2BIG;
    696 	goto end_error;
    697 
    698  format_error:;
    699 	errno = EINVAL;
    700 
    701  end_error:;
    702 	sverrno = errno;
    703 	if (asciivalue != NULL)
    704 		free(asciivalue);
    705 	if (currency_symbol != NULL)
    706 		free(currency_symbol);
    707 	errno = sverrno;
    708 	return (-1);
    709 }
    710 
    711 static int
    712 __add_wide_char(char *dst, char *limit, wchar_t wch)
    713 {
    714 	char sc[MAX_ENCODED_CHAR_LEN + 1];
    715 	int clen;
    716 	const int e = errno;
    717 
    718 	(void)wctomb(NULL, L'\0');
    719 	clen = wctomb(sc, wch);
    720 	errno = e;
    721 	if (clen > 0) {
    722 		if (dst + clen >= limit)
    723 			return -2;
    724 		memcpy(dst, sc, (size_t)clen);
    725 		return clen;
    726 	}
    727 	return -1;
    728 }
    729 
    730 static void
    731 __setup_vars(int flags, char *cs_precedes, char *sep_by_space,
    732     char *sign_posn, const char **signstr, struct lconv *lc)
    733 {
    734 
    735 	if ((flags & IS_NEGATIVE) && (flags & USE_INTL_CURRENCY)) {
    736 		*cs_precedes = lc->int_n_cs_precedes;
    737 		*sep_by_space = lc->int_n_sep_by_space;
    738 		*sign_posn = lc->int_n_sign_posn;
    739 	} else if (flags & USE_INTL_CURRENCY) {
    740 		*cs_precedes = lc->int_p_cs_precedes;
    741 		*sep_by_space = lc->int_p_sep_by_space;
    742 		*sign_posn = lc->int_p_sign_posn;
    743 	} else if (flags & IS_NEGATIVE) {
    744 		*cs_precedes = lc->n_cs_precedes;
    745 		*sep_by_space = lc->n_sep_by_space;
    746 		*sign_posn = lc->n_sign_posn;
    747 	} else {
    748 		*cs_precedes = lc->p_cs_precedes;
    749 		*sep_by_space = lc->p_sep_by_space;
    750 		*sign_posn = lc->p_sign_posn;
    751 	}
    752 	if ((flags & (PARENTH_POSN|IS_NEGATIVE)) == (PARENTH_POSN|IS_NEGATIVE))
    753 		*sign_posn = 0;
    754 
    755 	if (signstr != NULL) {
    756 		if (flags & IS_NEGATIVE)
    757 			*signstr = lc->negative_sign;
    758 		else
    759 			*signstr = lc->positive_sign;
    760 	}
    761 
    762 	/* Set default values for unspecified/invalid information. */
    763 	if (*cs_precedes != 0)
    764 		*cs_precedes = 1;
    765 	if (RANGE_CHECK(sep_by_space, >, 2))
    766 		*sep_by_space = 0;
    767 	if (RANGE_CHECK(sign_posn, >, 4))
    768 		*sign_posn = 1;
    769 }
    770 
    771 /*
    772  * Func name is misleading (but historic), this calculates the number of
    773  * characters that are inserted before the value string for a value and
    774  * using options as given by flags (+/-, $ or not, ...)
    775  *
    776  * Taking the difference between what this returns for the sign of the
    777  * value we have, and what would be used for a value of the opposite sign,
    778  * will reveal how many pad chars need to be inserted.
    779  */
    780 static int
    781 __calc_left_pad(int flags, int cs_cols, int s_cols, struct lconv *lc)
    782 {
    783 	char cs_precedes, sep_by_space, sign_posn;
    784 	int left_chars = 0;
    785 
    786 	__setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn, NULL, lc);
    787 
    788 	if ((flags & (PARENTH_POSN|IS_NEGATIVE)) ==
    789 	    (PARENTH_POSN|IS_NEGATIVE) ||
    790 	    (!(flags & SIGN_POSN_USED) && sign_posn == 0)) {
    791 		left_chars++;	/* One char needed for '(' **)** */
    792 		sign_posn = 0;
    793 	}
    794 
    795 	if (cs_precedes != 0) {
    796 		/* space needed for currency symbol */
    797 		left_chars += cs_cols;
    798 		if (sep_by_space != 0)	/* either 1 or 2, space goes with $ */
    799 			left_chars++;
    800 	}
    801 
    802 	switch (sign_posn) {
    803 	case 0:
    804 		/* paren marking, handled above */
    805 		break;
    806 	case 1:
    807 		left_chars += s_cols;
    808 		break;
    809 	case 3:
    810 	case 4:
    811 		if (cs_precedes != 0)
    812 			left_chars += s_cols;
    813 		break;
    814 	}
    815 	return left_chars;
    816 }
    817 
    818 /*
    819  * The same for the right side
    820  */
    821 static int
    822 __calc_right_pad(int flags, int cs_cols, int s_cols, struct lconv *lc)
    823 {
    824 	char cs_precedes, sep_by_space, sign_posn;
    825 	int right_chars = 0;
    826 
    827 	__setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn, NULL, lc);
    828 
    829 	if ((flags & (PARENTH_POSN|IS_NEGATIVE)) ==
    830 	    (PARENTH_POSN|IS_NEGATIVE) ||
    831 	    (!(flags & SIGN_POSN_USED) && sign_posn == 0)) {
    832 		right_chars++;	/* **(** One char needed for ')' */
    833 		sign_posn = 0;
    834 	}
    835 
    836 	if (cs_precedes == 0) {
    837 		right_chars += cs_cols;
    838 		if (sep_by_space != 0)
    839 			right_chars++;
    840 	}
    841 
    842 	switch (sign_posn) {
    843 	case 0:
    844 		break;
    845 	case 2:
    846 		right_chars += s_cols;
    847 		break;
    848 	case 3:
    849 	case 4:
    850 		if (cs_precedes == 0)
    851 			right_chars += s_cols;
    852 		break;
    853 	}
    854 	return right_chars;
    855 }
    856 
    857 /*
    858  * Determine how many thousands_separator sequences will be
    859  * inserted into a string of <size> digits, using the
    860  * grouping algorithm given by <grouping>
    861  */
    862 static int
    863 __count_grps(int size, char *grouping)
    864 {
    865 	int	seps = 0;
    866 
    867 	if (*grouping == CHAR_MAX ||		/* no grouping ? */
    868 	    RANGE_CHECK(grouping, <=, 0))
    869 		return 0;
    870 
    871 	while (RANGE_CHECK(grouping, < , size)) {
    872 		seps++;
    873 		size -= (int)(unsigned char)*grouping++;
    874 
    875 		/* no more grouping ? */
    876 		if (RANGE_CHECK(grouping, ==, CHAR_MAX))
    877 			break;
    878 
    879 		/* remainder grouping with same value ? */
    880 		if (*grouping == 0) {
    881 			/* known that: grouping[-1] != 0 */
    882 			seps += (size - 1) / *(grouping - 1);
    883 			break;
    884 		}
    885 	}
    886 	return seps;
    887 }
    888 
    889 /* convert double to locale-encoded string */
    890 static char *
    891 __format_grouped_double(double value, int *flags, int *usedp, int left_prec,
    892     int right_prec, char *pad_char, size_t pad_char_len,
    893     struct lconv *lc, locale_t loc)
    894 {
    895 	char		*rslt;
    896 	char		*avalue;
    897 	int		avalue_size;
    898 
    899 	size_t		bufsize;
    900 	char		*bufend;
    901 
    902 	int		padded;
    903 
    904 	char		*grouping;
    905 	const char	*decimal_point;
    906 	const char	*thousands_sep;
    907 	size_t		decimal_point_size;
    908 	size_t		thousands_sep_size;
    909 	int		decimal_point_cols;
    910 	int		thousands_sep_cols;
    911 
    912 	int		groups = 0;
    913 	int		used = 0;
    914 
    915 	grouping = lc->mon_grouping;
    916 	decimal_point = lc->mon_decimal_point;
    917 	if (*decimal_point == '\0')		/* POSIX will say to do this */
    918 		decimal_point = lc->decimal_point;
    919 	thousands_sep = lc->mon_thousands_sep;
    920 #if 0
    921 	if (*thousands_sep == '\0')		/* but not to do this */
    922 		thousands_sep = lc->thousands_sep;
    923 #endif
    924 
    925 	decimal_point_size = strlen(decimal_point);
    926 	thousands_sep_size = strlen(thousands_sep);
    927 	decimal_point_cols = __columns(decimal_point, loc);
    928 	thousands_sep_cols = __columns(thousands_sep, loc);
    929 
    930 	/* fill left_prec with default value */
    931 	if (left_prec == -1)
    932 		left_prec = 0;
    933 
    934 	/* fill right_prec with default value */
    935 	if (right_prec == -1) {
    936 		if (*flags & USE_INTL_CURRENCY)
    937 			right_prec = lc->int_frac_digits;
    938 		else
    939 			right_prec = lc->frac_digits;
    940 
    941 		if (right_prec == CHAR_MAX)	/* POSIX locale ? */
    942 			right_prec = 0;
    943 	}
    944 
    945 	if (decimal_point_size == 0)
    946 		right_prec = 0;
    947 
    948 	if (*flags & NEED_GROUPING)
    949 		left_prec +=
    950 		    __count_grps(left_prec, grouping) * thousands_sep_cols;
    951 
    952 	/*
    953 	 * convert to string
    954 	 *
    955 	 * The field width specified allows for the minimum number of
    956 	 * digits before the decimal point (left_prec), the number after
    957 	 * it, and if that was not 0, 1 more for the '.'.
    958 	 * nb: this is using printf(3), the decimal point is always '.'
    959 	 * (and so is always 1 byte).
    960 	 */
    961 	avalue_size = asprintf_l(&avalue, loc, "%*.*f",
    962 	    left_prec + right_prec + (right_prec ? 1 : 0), right_prec, value);
    963 	if (avalue_size < 0)
    964 		return (NULL);
    965 
    966 	/*
    967 	 * make sure that we've enough space for result string
    968 	 * (it is OK to be more than enough)
    969 	 *
    970 	 * avalue_size are the digits, with often a '.', and leading
    971 	 * padding to allow for the left_precision
    972 	 *
    973 	 * In extreme cases every character in the result might need
    974 	 * a grouping character (really 1 less, but being bigger is OK)
    975 	 * where each grouping character is thousands_sep_size bytes.
    976 	 *
    977 	 * Thus: avalue_size + (avalue_size * thousands_sep_size)
    978 	 * or:   avalue_size * (1 + thousands_sep_size)
    979 	 *
    980 	 * After that we need to insert the locale radix char, which
    981 	 * is decimal_point_size bytes (we could -1 for the '.' present)
    982 	 *
    983 	 * And one more for the \0 to end it all.
    984 	 */
    985 	bufsize = avalue_size * (1 + thousands_sep_size) +
    986 	    decimal_point_size + 1;
    987 
    988 	/* skip spaces at beginning */
    989 	padded = 0;
    990 	while (avalue[padded] == ' ') {
    991 		padded++;
    992 		avalue_size--;
    993 	}
    994 	bufsize += padded * (pad_char_len - 1);
    995 
    996 	rslt = calloc(1, bufsize);
    997 	if (rslt == NULL) {
    998 		free(avalue);
    999 		return (NULL);
   1000 	}
   1001 	bufend = rslt + bufsize - 1;	/* reserve space for trailing '\0' */
   1002 
   1003 	if (right_prec > 0) {
   1004 		bufend -= right_prec;
   1005 		memcpy(bufend, avalue + avalue_size + padded - right_prec,
   1006 		    (size_t) right_prec);
   1007 		bufend -= decimal_point_size;
   1008 		memcpy(bufend, decimal_point, decimal_point_size);
   1009 		avalue_size -= (right_prec + 1);
   1010 		used += right_prec + decimal_point_cols;
   1011 	}
   1012 
   1013 	/*
   1014 	 * If grouping has not been suppressed, and the width of
   1015 	 * the grouping separator is > 0 columns, and there is
   1016 	 * a defined (non-null) grouping algorithm, then we
   1017 	 * perform that algorithm here.
   1018 	 */
   1019 	if ((*flags & NEED_GROUPING) &&
   1020 	    thousands_sep_cols > 0 &&
   1021 	    *grouping != CHAR_MAX && *grouping > 0) {
   1022 		/* Moving from right to left */
   1023 		while (avalue_size > (int)*grouping) {
   1024 			/* insert the digits for the group */
   1025 			GRPCPY(*grouping);
   1026 			/* then a separator */
   1027 			GRPSEP;
   1028 			used += thousands_sep_cols + *grouping;
   1029 			/* and advance to the next step */
   1030 			grouping++;
   1031 
   1032 			/* no more grouping ? */
   1033 			if (RANGE_CHECK(grouping, ==, CHAR_MAX))
   1034 				break;
   1035 
   1036 			/* rest grouping with same value ? */
   1037 			if (*grouping == 0) {
   1038 				/* go back to the last group size */
   1039 				grouping--;
   1040 				/* and use it until out of digits */
   1041 				while (avalue_size > *grouping) {
   1042 					GRPCPY(*grouping);
   1043 					GRPSEP;
   1044 					used += thousands_sep_cols + *grouping;
   1045 				}
   1046 				break;
   1047 			}
   1048 		}
   1049 		/* If digits remain uncopied, do them now */
   1050 		if (avalue_size != 0) {
   1051 			used += avalue_size;	/* must be before GRPCPY */
   1052 			GRPCPY(avalue_size);
   1053 		}
   1054 		/*
   1055 		 * we need N less padding chars for each separator inserted
   1056 		 * where N is the width of the separator
   1057 		 */
   1058 		padded -= groups * thousands_sep_cols;
   1059 	} else {
   1060 		/*
   1061 		 * No grouping to do, the easy case, just
   1062 		 * copy the digits
   1063 		 */
   1064 		bufend -= avalue_size;
   1065 		memcpy(bufend, avalue + padded, (size_t) avalue_size);
   1066 		used += avalue_size;
   1067 	}
   1068 
   1069 	/* do padding with pad_char */
   1070 	if (padded > 0) {
   1071 		used += padded;
   1072 		if (pad_char_len == 1) {
   1073 			/* the most common case */
   1074 			bufend -= padded;
   1075 			memset(bufend, pad_char[0], padded);
   1076 		} else while (padded-- > 0) {
   1077 			bufend -= pad_char_len;
   1078 			memcpy(bufend, pad_char, pad_char_len);
   1079 		}
   1080 	}
   1081 
   1082 	/* copy the formatted digit string into the output buffer */
   1083 	bufsize = rslt + bufsize - bufend;
   1084 	memmove(rslt, bufend, bufsize);
   1085 	free(avalue);		/* and we're done with that now */
   1086 	*usedp += used;
   1087 	return (rslt);
   1088 }
   1089 
   1090 /*
   1091  * Given a limited length multi-byte character string s
   1092  * return the number of columns that will be used to display
   1093  * that string.
   1094  *
   1095  * The string ends at the first \0 encountered within MAX_CH chars.
   1096  * The whole string must be consumed, but at most MAX_CH-1 wide chars
   1097  * (plus a null) can be present.
   1098  *
   1099  * This is not intended as a general purpose column counting function,
   1100  * just to determine the widths of the various symbols used in strfmon()
   1101  * - the decimmal_point, thousands_sep, and currency symbol.
   1102  *
   1103  * Returns -1 if any error is encountered (too much input, invalid
   1104  * byte sequence, ...) or the number of columns required (>= 0).
   1105  */
   1106 #define MAX_CH 8
   1107 static int
   1108 __columns(const char *s, locale_t loc)
   1109 {
   1110 	wchar_t widech[MAX_CH];	/* strings of up to 7 (wide) chars + nul */
   1111 	size_t count;
   1112 	mbstate_t ps;
   1113 
   1114 	(void)mbrtowc_l(NULL, NULL, 1, &ps, loc);	/* init state */
   1115 	count = mbsrtowcs_l(widech, &s, MAX_CH, &ps, loc);
   1116 	if (count == (size_t)-1 || count > MAX_CH - 1 || s != NULL)
   1117 		return -1;
   1118 	return wcswidth_l(widech, count, loc);
   1119 }
   1120 
   1121 ssize_t
   1122 strfmon(char * __restrict s, size_t maxsize,
   1123     const char * __restrict format, ...)
   1124 {
   1125 	ssize_t ret;
   1126 	va_list ap;
   1127 
   1128 	va_start(ap, format);
   1129 	ret = vstrfmon_l(s, maxsize, _current_locale(), format, ap);
   1130 	va_end(ap);
   1131 
   1132 	return ret;
   1133 }
   1134 
   1135 ssize_t
   1136 strfmon_l(char * __restrict s, size_t maxsize, locale_t loc,
   1137     const char * __restrict format, ...)
   1138 {
   1139 	ssize_t ret;
   1140 	va_list ap;
   1141 
   1142 	va_start(ap, format);
   1143 	ret = vstrfmon_l(s, maxsize, loc, format, ap);
   1144 	va_end(ap);
   1145 
   1146 	return ret;
   1147 }
   1148