2 * snprintf.c -- formatted output to a string
4 * This is an implementation of snprintf() and vsnprintf()
5 * taken from the Apache web server. This is only used on
6 * systems which do not have a native version.
9 /* ====================================================================
10 * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in
21 * the documentation and/or other materials provided with the
24 * 3. All advertising materials mentioning features or use of this
25 * software must display the following acknowledgment:
26 * "This product includes software developed by the Apache Group
27 * for use in the Apache HTTP server project (http://www.apache.org/)."
29 * 4. The names "Apache Server" and "Apache Group" must not be used to
30 * endorse or promote products derived from this software without
31 * prior written permission. For written permission, please contact
34 * 5. Products derived from this software may not be called "Apache"
35 * nor may "Apache" appear in their names without prior written
36 * permission of the Apache Group.
38 * 6. Redistributions of any form whatsoever must retain the following
40 * "This product includes software developed by the Apache Group
41 * for use in the Apache HTTP server project (http://www.apache.org/)."
43 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
44 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
46 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
47 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
48 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
49 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
50 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
52 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
53 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
54 * OF THE POSSIBILITY OF SUCH DAMAGE.
55 * ====================================================================
57 * This software consists of voluntary contributions made by many
58 * individuals on behalf of the Apache Group and was originally based
59 * on public domain software written at the National Center for
60 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
61 * For more information on the Apache Group and the Apache HTTP server
62 * project, please see <http://www.apache.org/>.
64 * This code is based on, and used with the permission of, the
65 * SIO stdio-replacement strx_* functions by Panos Tsirigotis
66 * <panos@alumni.cs.colorado.edu> for xinetd.
71 #include <sys/types.h>
76 #include <netinet/in.h>
89 #define INT_NULL ((int *)0)
97 typedef WIDE_INT wide_int;
98 typedef unsigned WIDE_INT u_wide_int;
101 #define S_NULL "(null)"
104 #define FLOAT_DIGITS 6
105 #define EXPONENT_LENGTH 10
107 /* These macros allow correct support of 8-bit characters on systems which
108 * support 8-bit characters. Pretty dumb how the cast is required, but
109 * that's legacy libc for ya. These new macros do not support EOF like
110 * the standard macros do. Tough.
112 #define ap_isalpha(c) (isalpha(((unsigned char)(c))))
113 #define ap_isdigit(c) (isdigit(((unsigned char)(c))))
114 #define ap_islower(c) (islower(((unsigned char)(c))))
117 * NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions
119 * XXX: this is a magic number; do not decrease it
121 #define NUM_BUF_SIZE 512
124 * cvt.c - IEEE floating point formatting routines for FreeBSD
125 * from GNU libc-4.6.27. Modified to be thread safe.
129 * ap_ecvt converts to decimal
130 * the number of digits is specified by ndigit
131 * decpt is set to the position of the decimal point
132 * sign is set to 0 for positive, 1 for negative
137 /* buf must have at least NDIG bytes */
139 ap_cvt(double arg, int ndigits, int *decpt, int *sign, int eflag, char *buf)
143 register char *p, *p1;
145 if (ndigits >= NDIG - 1)
154 arg = modf(arg, &fi);
162 fj = modf(fi / 10, &fi);
163 *--p1 = (int) ((fj + .03) * 10) + '0';
166 while (p1 < &buf[NDIG])
168 } else if (arg > 0) {
169 while ((fj = arg * 10) < 1) {
182 while (p <= p1 && p < &buf[NDIG]) {
184 arg = modf(arg, &fj);
185 *p++ = (int) fj + '0';
187 if (p1 >= &buf[NDIG]) {
188 buf[NDIG - 1] = '\0';
212 ap_ecvt(double arg, int ndigits, int *decpt, int *sign, char *buf)
214 return (ap_cvt(arg, ndigits, decpt, sign, 1, buf));
218 ap_fcvt(double arg, int ndigits, int *decpt, int *sign, char *buf)
220 return (ap_cvt(arg, ndigits, decpt, sign, 0, buf));
224 * ap_gcvt - Floating output conversion to
225 * minimal length string
229 ap_gcvt(double number, int ndigit, char *buf, boolean_e altform)
232 register char *p1, *p2;
236 p1 = ap_ecvt(number, ndigit, &decpt, &sign, buf1);
240 for (i = ndigit - 1; i > 0 && p1[i] == '0'; i--)
242 if ((decpt >= 0 && decpt - ndigit > 4)
243 || (decpt < 0 && decpt < -3)) { /* use E-style */
247 for (i = 1; i < ndigit; i++)
256 *p2++ = decpt / 100 + '0';
258 *p2++ = (decpt % 100) / 10 + '0';
259 *p2++ = decpt % 10 + '0';
269 for (i = 1; i <= ndigit; i++) {
274 if (ndigit < decpt) {
275 while (ndigit++ < decpt)
280 if (p2[-1] == '.' && !altform)
287 * The INS_CHAR macro inserts a character in the buffer and writes
288 * the buffer back to disk if necessary
289 * It uses the char pointers sp and bep:
290 * sp points to the next available character in the buffer
291 * bep points to the end-of-buffer+1
292 * While using this macro, note that the nextb pointer is NOT updated.
294 * NOTE: Evaluation of the c argument should not have any side-effects
296 #define INS_CHAR(c, sp, bep, cc) \
299 vbuff->curpos = sp; \
300 if (flush_func(vbuff)) \
302 sp = vbuff->curpos; \
303 bep = vbuff->endpos; \
309 #define NUM( c ) ( c - '0' )
311 #define STR_TO_DEC( str, num ) \
312 num = NUM( *str++ ) ; \
313 while ( ap_isdigit( *str ) ) \
316 num += NUM( *str++ ) ; \
320 * This macro does zero padding so that the precision
321 * requirement is satisfied. The padding is done by
322 * adding '0's to the left of the string that is going
325 #define FIX_PRECISION( adjust, precision, s, s_len ) \
327 while ( s_len < precision ) \
334 * Macro that does padding. The padding is done by printing
337 #define PAD( width, len, ch ) do \
339 INS_CHAR( ch, sp, bep, cc ) ; \
342 while ( width > len )
345 * Prefix the character ch to the string str
347 * Set the has_prefix flag
349 #define PREFIX( str, length, ch ) *--str = ch ; length++ ; has_prefix = YES
353 * Convert num to its decimal format.
355 * - a pointer to a string containing the number (no sign)
356 * - len contains the length of the string
357 * - is_negative is set to TRUE or FALSE depending on the sign
358 * of the number (always set to FALSE if is_unsigned is TRUE)
360 * The caller provides a buffer for the string: that is the buf_end argument
361 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
362 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
365 conv_10(register wide_int num, register bool_int is_unsigned,
366 register bool_int *is_negative, char *buf_end,
369 register char *p = buf_end;
370 register u_wide_int magnitude;
373 magnitude = (u_wide_int) num;
374 *is_negative = FALSE;
376 *is_negative = (num < 0);
379 * On a 2's complement machine, negating the most negative integer
380 * results in a number that cannot be represented as a signed integer.
381 * Here is what we do to obtain the number's magnitude:
382 * a. add 1 to the number
383 * b. negate it (becomes positive)
384 * c. convert it to unsigned
388 wide_int t = num + 1;
390 magnitude = ((u_wide_int) -t) + 1;
392 magnitude = (u_wide_int) num;
396 * We use a do-while loop so that we write at least 1 digit
399 register u_wide_int new_magnitude = magnitude / 10;
401 *--p = (char) (magnitude - new_magnitude * 10 + '0');
402 magnitude = new_magnitude;
413 conv_in_addr(struct in_addr *ia, char *buf_end, int *len)
415 unsigned addr = ntohl(ia->s_addr);
417 bool_int is_negative;
420 p = conv_10((addr & 0x000000FF) , TRUE, &is_negative, p, &sub_len);
422 p = conv_10((addr & 0x0000FF00) >> 8, TRUE, &is_negative, p, &sub_len);
424 p = conv_10((addr & 0x00FF0000) >> 16, TRUE, &is_negative, p, &sub_len);
426 p = conv_10((addr & 0xFF000000) >> 24, TRUE, &is_negative, p, &sub_len);
435 conv_sockaddr_in(struct sockaddr_in *si, char *buf_end, int *len)
438 bool_int is_negative;
441 p = conv_10(ntohs(si->sin_port), TRUE, &is_negative, p, &sub_len);
443 p = conv_in_addr(&si->sin_addr, p, &sub_len);
452 * Convert a floating point number to a string formats 'f', 'e' or 'E'.
453 * The result is placed in buf, and len denotes the length of the string
454 * The sign is returned in the is_negative argument (and is not placed
458 conv_fp(register char format, register double num,
459 boolean_e add_dp, int precision, bool_int *is_negative,
462 register char *s = buf;
468 p = ap_fcvt(num, precision, &decimal_point, is_negative, buf1);
469 else /* either e or E format */
470 p = ap_ecvt(num, precision + 1, &decimal_point, is_negative, buf1);
473 * Check for Infinity and NaN
475 if (ap_isalpha(*p)) {
476 *len = strlen(strcpy(buf, p));
477 *is_negative = FALSE;
482 if (decimal_point <= 0) {
486 while (decimal_point++ < 0)
491 while (decimal_point-- > 0)
493 if (precision > 0 || add_dp)
498 if (precision > 0 || add_dp)
503 * copy the rest of p, the NUL is NOT copied
509 char temp[EXPONENT_LENGTH]; /* for exponent conversion */
511 bool_int exponent_is_negative;
513 *s++ = format; /* either e or E */
515 if (decimal_point != 0) {
516 p = conv_10((wide_int) decimal_point, FALSE,
517 &exponent_is_negative, &temp[EXPONENT_LENGTH],
519 *s++ = exponent_is_negative ? '-' : '+';
522 * Make sure the exponent has at least 2 digits
541 * Convert num to a base X number where X is a power of 2. nbits determines X.
542 * For example, if nbits is 3, we do base 8 conversion
544 * a pointer to a string containing the number
546 * The caller provides a buffer for the string: that is the buf_end argument
547 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
548 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
551 conv_p2(register u_wide_int num, register int nbits,
552 char format, char *buf_end, register int *len)
554 register int mask = (1 << nbits) - 1;
555 register char *p = buf_end;
556 static const char low_digits[] = "0123456789abcdef";
557 static const char upper_digits[] = "0123456789ABCDEF";
558 register const char *digits = (format == 'X') ? upper_digits : low_digits;
561 *--p = digits[num & mask];
572 * Do format conversion placing the output in buffer
575 ap_vformatter(int (*flush_func)(ap_vformatter_buff *),
576 ap_vformatter_buff *vbuff, const char *fmt, va_list ap)
583 register char *s = NULL;
587 register int min_width = 0;
596 wide_int i_num = (wide_int) 0;
599 char num_buf[NUM_BUF_SIZE];
600 char char_buf[2]; /* for printing %% and %<unknown> */
606 boolean_e alternate_form;
607 boolean_e print_sign;
608 boolean_e print_blank;
609 boolean_e adjust_precision;
610 boolean_e adjust_width;
611 bool_int is_negative;
618 INS_CHAR(*fmt, sp, bep, cc);
621 * Default variable settings
624 alternate_form = print_sign = print_blank = NO;
631 * Try to avoid checking for flags, width or precision
633 if (!ap_islower(*fmt)) {
635 * Recognize flags: -, #, BLANK, +
640 else if (*fmt == '+')
642 else if (*fmt == '#')
643 alternate_form = YES;
644 else if (*fmt == ' ')
646 else if (*fmt == '0')
653 * Check if a width was specified
655 if (ap_isdigit(*fmt)) {
656 STR_TO_DEC(fmt, min_width);
658 } else if (*fmt == '*') {
659 min_width = va_arg(ap, int);
664 min_width = -min_width;
670 * Check if a precision was specified
672 * XXX: an unreasonable amount of precision may be specified
673 * resulting in overflow of num_buf. Currently we
674 * ignore this possibility.
677 adjust_precision = YES;
679 if (ap_isdigit(*fmt)) {
680 STR_TO_DEC(fmt, precision);
681 } else if (*fmt == '*') {
682 precision = va_arg(ap, int);
689 adjust_precision = NO;
691 adjust_precision = adjust_width = NO;
700 if (*fmt == 'h') /* "short" backward compatibility */
706 * Argument extraction and printing.
707 * First we determine the argument type.
708 * Then, we convert the argument to a string.
709 * On exit from the switch, s points to the string that
710 * must be printed, s_len has the length of the string
711 * The precision requirements, if any, are reflected in s_len.
713 * NOTE: pad_char may be set to '0' because of the 0 flag.
714 * It is reset to ' ' by non-numeric formats
719 i_num = va_arg(ap, u_wide_int);
721 i_num = (wide_int) va_arg(ap, unsigned int);
722 s = conv_10(i_num, 1, &is_negative,
723 &num_buf[NUM_BUF_SIZE], &s_len);
724 FIX_PRECISION(adjust_precision, precision, s, s_len);
730 i_num = va_arg(ap, wide_int);
732 i_num = (wide_int) va_arg(ap, int);
733 s = conv_10(i_num, 0, &is_negative,
734 &num_buf[NUM_BUF_SIZE], &s_len);
735 FIX_PRECISION(adjust_precision, precision, s, s_len);
741 else if (print_blank)
748 ui_num = va_arg(ap, u_wide_int);
750 ui_num = (u_wide_int) va_arg(ap, unsigned int);
751 s = conv_p2(ui_num, 3, *fmt,
752 &num_buf[NUM_BUF_SIZE], &s_len);
753 FIX_PRECISION(adjust_precision, precision, s, s_len);
754 if (alternate_form && *s != '0') {
764 ui_num = (u_wide_int) va_arg(ap, u_wide_int);
766 ui_num = (u_wide_int) va_arg(ap, unsigned int);
767 s = conv_p2(ui_num, 4, *fmt,
768 &num_buf[NUM_BUF_SIZE], &s_len);
769 FIX_PRECISION(adjust_precision, precision, s, s_len);
770 if (alternate_form && i_num != 0) {
771 *--s = *fmt; /* 'x' or 'X' */
779 s = va_arg(ap, char *);
782 if (adjust_precision && precision < s_len)
796 fp_num = va_arg(ap, double);
798 * * We use &num_buf[ 1 ], so that we have room for the sign
800 s = conv_fp(*fmt, fp_num, alternate_form,
801 (adjust_precision == NO) ? FLOAT_DIGITS : precision,
802 &is_negative, &num_buf[1], &s_len);
807 else if (print_blank)
814 if (adjust_precision == NO)
815 precision = FLOAT_DIGITS;
816 else if (precision == 0)
819 * * We use &num_buf[ 1 ], so that we have room for the sign
821 s = ap_gcvt(va_arg(ap, double), precision, &num_buf[1],
827 else if (print_blank)
832 if (alternate_form && (q = strchr(s, '.')) == NULL) {
834 s[s_len] = '\0'; /* delimit for following strchr() */
836 if (*fmt == 'G' && (q = strchr(s, 'e')) != NULL)
842 char_buf[0] = (char) (va_arg(ap, int));
858 *(va_arg(ap, int *)) = cc;
862 * This is where we extend the printf format, with a second
868 * If the pointer size is equal to the size of an unsigned
869 * integer we convert the pointer to a hex number, otherwise
870 * we print "%p" to indicate that we don't handle "%p".
873 ui_num = (u_wide_int) va_arg(ap, void *);
875 if (sizeof(char *) <= sizeof(u_wide_int))
876 s = conv_p2(ui_num, 4, 'x',
877 &num_buf[NUM_BUF_SIZE], &s_len);
886 /* print a struct sockaddr_in as a.b.c.d:port */
889 struct sockaddr_in *si;
891 si = va_arg(ap, struct sockaddr_in *);
893 s = conv_sockaddr_in(si, &num_buf[NUM_BUF_SIZE], &s_len);
894 if (adjust_precision && precision < s_len)
905 /* print a struct in_addr as a.b.c.d */
910 ia = va_arg(ap, struct in_addr *);
912 s = conv_in_addr(ia, &num_buf[NUM_BUF_SIZE], &s_len);
913 if (adjust_precision && precision < s_len)
925 /* if %p ends the string, oh well ignore it */
938 * The last character of the format string was %.
945 * The default case is for unrecognized %'s.
946 * We print %<char> to help the user identify what
947 * option is not understood.
948 * This is also useful in case the user wants to pass
949 * the output of format_converter to another function
950 * that understands some other %<char> (like syslog).
951 * Note that we can't point s inside fmt because the
952 * unknown <char> could be preceded by width etc.
963 if (prefix_char != NUL && s != S_NULL && s != char_buf) {
968 if (adjust_width && adjust == RIGHT && min_width > s_len) {
969 if (pad_char == '0' && prefix_char != NUL) {
970 INS_CHAR(*s, sp, bep, cc);
975 PAD(min_width, s_len, pad_char);
979 * Print the string s.
981 for (i = s_len; i != 0; i--) {
982 INS_CHAR(*s, sp, bep, cc);
986 if (adjust_width && adjust == LEFT && min_width > s_len)
987 PAD(min_width, s_len, pad_char);
997 snprintf_flush(ap_vformatter_buff *vbuff)
999 /* if the buffer fills we have to abort immediately, there is no way
1000 * to "flush" a snprintf... there's nowhere to flush it to.
1007 snprintf(char *buf, size_t len, const char *format,...)
1011 ap_vformatter_buff vbuff;
1016 /* save one byte for nul terminator */
1018 vbuff.endpos = buf + len - 1;
1019 va_start(ap, format);
1020 cc = ap_vformatter(snprintf_flush, &vbuff, format, ap);
1022 *vbuff.curpos = '\0';
1023 return (cc == -1) ? len : cc;
1028 vsnprintf(char *buf, size_t len, const char *format, va_list ap)
1031 ap_vformatter_buff vbuff;
1036 /* save one byte for nul terminator */
1038 vbuff.endpos = buf + len - 1;
1039 cc = ap_vformatter(snprintf_flush, &vbuff, format, ap);
1040 *vbuff.curpos = '\0';
1041 return (cc == -1) ? len : cc;