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
108 ** These macros allow correct support of 8-bit characters on systems which
109 ** support 8-bit characters. Pretty dumb how the cast is required, but
110 ** that's legacy libc for ya. These new macros do not support EOF like
111 ** the standard macros do. Tough.
113 #define ap_isalpha(c) (isalpha(((unsigned char)(c))))
114 #define ap_isdigit(c) (isdigit(((unsigned char)(c))))
115 #define ap_islower(c) (islower(((unsigned char)(c))))
118 ** NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions
120 ** XXX: this is a magic number; do not decrease it
122 #define NUM_BUF_SIZE 512
125 ** cvt.c - IEEE floating point formatting routines for FreeBSD
126 ** from GNU libc-4.6.27. Modified to be thread safe.
130 ** ap_ecvt converts to decimal
131 ** the number of digits is specified by ndigit
132 ** decpt is set to the position of the decimal point
133 ** sign is set to 0 for positive, 1 for negative
138 /* buf must have at least NDIG bytes */
140 ap_cvt(double arg, int ndigits, int *decpt, int *sign, int eflag, char *buf)
144 register char *p, *p1;
146 if (ndigits >= NDIG - 1)
155 arg = modf(arg, &fi);
163 fj = modf(fi / 10, &fi);
164 *--p1 = (int) ((fj + .03) * 10) + '0';
167 while (p1 < &buf[NDIG])
169 } else if (arg > 0) {
170 while ((fj = arg * 10) < 1) {
183 while (p <= p1 && p < &buf[NDIG]) {
185 arg = modf(arg, &fj);
186 *p++ = (int) fj + '0';
188 if (p1 >= &buf[NDIG]) {
189 buf[NDIG - 1] = '\0';
213 ap_ecvt(double arg, int ndigits, int *decpt, int *sign, char *buf)
215 return (ap_cvt(arg, ndigits, decpt, sign, 1, buf));
219 ap_fcvt(double arg, int ndigits, int *decpt, int *sign, char *buf)
221 return (ap_cvt(arg, ndigits, decpt, sign, 0, buf));
225 ** ap_gcvt - Floating output conversion to
226 ** minimal length string
230 ap_gcvt(double number, int ndigit, char *buf, boolean_e altform)
233 register char *p1, *p2;
237 p1 = ap_ecvt(number, ndigit, &decpt, &sign, buf1);
241 for (i = ndigit - 1; i > 0 && p1[i] == '0'; i--)
243 if ((decpt >= 0 && decpt - ndigit > 4)
244 || (decpt < 0 && decpt < -3)) { /* use E-style */
248 for (i = 1; i < ndigit; i++)
257 *p2++ = decpt / 100 + '0';
259 *p2++ = (decpt % 100) / 10 + '0';
260 *p2++ = decpt % 10 + '0';
270 for (i = 1; i <= ndigit; i++) {
275 if (ndigit < decpt) {
276 while (ndigit++ < decpt)
281 if (p2[-1] == '.' && !altform)
288 ** The INS_CHAR macro inserts a character in the buffer and writes
289 ** the buffer back to disk if necessary
290 ** It uses the char pointers sp and bep:
291 ** sp points to the next available character in the buffer
292 ** bep points to the end-of-buffer+1
293 ** While using this macro, note that the nextb pointer is NOT updated.
295 ** NOTE: Evaluation of the c argument should not have any side-effects
297 #define INS_CHAR(c, sp, bep, cc) \
300 vbuff->curpos = sp; \
301 if (flush_func(vbuff)) \
303 sp = vbuff->curpos; \
304 bep = vbuff->endpos; \
310 #define NUM( c ) ( c - '0' )
312 #define STR_TO_DEC( str, num ) \
313 num = NUM( *str++ ) ; \
314 while ( ap_isdigit( *str ) ) \
317 num += NUM( *str++ ) ; \
321 ** This macro does zero padding so that the precision
322 ** requirement is satisfied. The padding is done by
323 ** adding '0's to the left of the string that is going
326 #define FIX_PRECISION( adjust, precision, s, s_len ) \
328 while ( s_len < precision ) \
335 ** Macro that does padding. The padding is done by printing
338 #define PAD( width, len, ch ) do \
340 INS_CHAR( ch, sp, bep, cc ) ; \
343 while ( width > len )
346 ** Prefix the character ch to the string str
348 ** Set the has_prefix flag
350 #define PREFIX( str, length, ch ) *--str = ch ; length++ ; has_prefix = YES
354 ** Convert num to its decimal format.
356 ** - a pointer to a string containing the number (no sign)
357 ** - len contains the length of the string
358 ** - is_negative is set to TRUE or FALSE depending on the sign
359 ** of the number (always set to FALSE if is_unsigned is TRUE)
361 ** The caller provides a buffer for the string: that is the buf_end argument
362 ** which is a pointer to the END of the buffer + 1 (i.e. if the buffer
363 ** is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
366 conv_10(register wide_int num, register bool_int is_unsigned,
367 register bool_int *is_negative, char *buf_end,
370 register char *p = buf_end;
371 register u_wide_int magnitude;
374 magnitude = (u_wide_int) num;
375 *is_negative = FALSE;
377 *is_negative = (num < 0);
380 ** On a 2's complement machine, negating the most negative
381 ** integer results in a number that cannot be represented
382 ** as a signed integer.
383 ** Here is what we do to obtain the number's magnitude:
384 ** a. add 1 to the number
385 ** b. negate it (becomes positive)
386 ** c. convert it to unsigned
390 wide_int t = num + 1;
392 magnitude = ((u_wide_int) -t) + 1;
394 magnitude = (u_wide_int) num;
398 ** We use a do-while loop so that we write at least 1 digit
401 register u_wide_int new_magnitude = magnitude / 10;
403 *--p = (char) (magnitude - new_magnitude * 10 + '0');
404 magnitude = new_magnitude;
415 conv_in_addr(struct in_addr *ia, char *buf_end, int *len)
417 unsigned addr = ntohl(ia->s_addr);
419 bool_int is_negative;
422 p = conv_10((addr & 0x000000FF) , TRUE, &is_negative, p, &sub_len);
424 p = conv_10((addr & 0x0000FF00) >> 8, TRUE, &is_negative, p, &sub_len);
426 p = conv_10((addr & 0x00FF0000) >> 16, TRUE, &is_negative, p, &sub_len);
428 p = conv_10((addr & 0xFF000000) >> 24, TRUE, &is_negative, p, &sub_len);
437 conv_sockaddr_in(struct sockaddr_in *si, char *buf_end, int *len)
440 bool_int is_negative;
443 p = conv_10(ntohs(si->sin_port), TRUE, &is_negative, p, &sub_len);
445 p = conv_in_addr(&si->sin_addr, p, &sub_len);
454 ** Convert a floating point number to a string formats 'f', 'e' or 'E'.
455 ** The result is placed in buf, and len denotes the length of the string
456 ** The sign is returned in the is_negative argument (and is not placed
460 conv_fp(register char format, register double num,
461 boolean_e add_dp, int precision, bool_int *is_negative,
464 register char *s = buf;
470 p = ap_fcvt(num, precision, &decimal_point, is_negative, buf1);
471 else /* either e or E format */
472 p = ap_ecvt(num, precision + 1, &decimal_point, is_negative, buf1);
475 ** Check for Infinity and NaN
477 if (ap_isalpha(*p)) {
478 *len = strlen(strcpy(buf, p));
479 *is_negative = FALSE;
484 if (decimal_point <= 0) {
488 while (decimal_point++ < 0)
493 while (decimal_point-- > 0)
495 if (precision > 0 || add_dp)
500 if (precision > 0 || add_dp)
505 ** copy the rest of p, the NUL is NOT copied
511 char temp[EXPONENT_LENGTH]; /* for exponent conversion */
513 bool_int exponent_is_negative;
515 *s++ = format; /* either e or E */
517 if (decimal_point != 0) {
518 p = conv_10((wide_int) decimal_point, FALSE,
519 &exponent_is_negative, &temp[EXPONENT_LENGTH],
521 *s++ = exponent_is_negative ? '-' : '+';
524 ** Make sure the exponent has at least 2 digits
543 ** Convert num to a base X number where X is a power of 2. nbits determines X.
544 ** For example, if nbits is 3, we do base 8 conversion
546 ** a pointer to a string containing the number
548 ** The caller provides a buffer for the string: that is the buf_end argument
549 ** which is a pointer to the END of the buffer + 1 (i.e. if the buffer
550 ** is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
553 conv_p2(register u_wide_int num, register int nbits,
554 char format, char *buf_end, register int *len)
556 register int mask = (1 << nbits) - 1;
557 register char *p = buf_end;
558 static const char low_digits[] = "0123456789abcdef";
559 static const char upper_digits[] = "0123456789ABCDEF";
560 register const char *digits = (format == 'X') ? upper_digits : low_digits;
563 *--p = digits[num & mask];
574 ** Do format conversion placing the output in buffer
577 ap_vformatter(int (*flush_func)(ap_vformatter_buff *),
578 ap_vformatter_buff *vbuff, const char *fmt, va_list ap)
585 register char *s = NULL;
589 register int min_width = 0;
598 wide_int i_num = (wide_int) 0;
601 char num_buf[NUM_BUF_SIZE];
602 char char_buf[2]; /* for printing %% and %<unknown> */
608 boolean_e alternate_form;
609 boolean_e print_sign;
610 boolean_e print_blank;
611 boolean_e adjust_precision;
612 boolean_e adjust_width;
613 bool_int is_negative;
620 INS_CHAR(*fmt, sp, bep, cc);
623 ** Default variable settings
626 alternate_form = print_sign = print_blank = NO;
633 ** Try to avoid checking for flags, width or precision
635 if (!ap_islower(*fmt)) {
637 ** Recognize flags: -, #, BLANK, +
642 else if (*fmt == '+')
644 else if (*fmt == '#')
645 alternate_form = YES;
646 else if (*fmt == ' ')
648 else if (*fmt == '0')
655 ** Check if a width was specified
657 if (ap_isdigit(*fmt)) {
658 STR_TO_DEC(fmt, min_width);
660 } else if (*fmt == '*') {
661 min_width = va_arg(ap, int);
666 min_width = -min_width;
672 ** Check if a precision was specified
674 ** XXX: an unreasonable amount of precision
675 ** may be specified resulting in overflow of
676 ** num_buf. Currently we ignore this
680 adjust_precision = YES;
682 if (ap_isdigit(*fmt)) {
683 STR_TO_DEC(fmt, precision);
684 } else if (*fmt == '*') {
685 precision = va_arg(ap, int);
692 adjust_precision = NO;
694 adjust_precision = adjust_width = NO;
703 if (*fmt == 'h') /* "short" backward compatibility */
709 ** Argument extraction and printing.
710 ** First we determine the argument type.
711 ** Then, we convert the argument to a string.
712 ** On exit from the switch, s points to the string that
713 ** must be printed, s_len has the length of the string
714 ** The precision requirements, if any, are reflected
717 ** NOTE: pad_char may be set to '0' because of the
719 ** It is reset to ' ' by non-numeric formats
724 i_num = va_arg(ap, u_wide_int);
726 i_num = (wide_int) va_arg(ap, unsigned int);
727 s = conv_10(i_num, 1, &is_negative,
728 &num_buf[NUM_BUF_SIZE], &s_len);
729 FIX_PRECISION(adjust_precision, precision, s, s_len);
735 i_num = va_arg(ap, wide_int);
737 i_num = (wide_int) va_arg(ap, int);
738 s = conv_10(i_num, 0, &is_negative,
739 &num_buf[NUM_BUF_SIZE], &s_len);
740 FIX_PRECISION(adjust_precision, precision, s, s_len);
746 else if (print_blank)
753 ui_num = va_arg(ap, u_wide_int);
755 ui_num = (u_wide_int) va_arg(ap, unsigned int);
756 s = conv_p2(ui_num, 3, *fmt,
757 &num_buf[NUM_BUF_SIZE], &s_len);
758 FIX_PRECISION(adjust_precision, precision, s, s_len);
759 if (alternate_form && *s != '0') {
769 ui_num = (u_wide_int) va_arg(ap, u_wide_int);
771 ui_num = (u_wide_int) va_arg(ap, unsigned int);
772 s = conv_p2(ui_num, 4, *fmt,
773 &num_buf[NUM_BUF_SIZE], &s_len);
774 FIX_PRECISION(adjust_precision, precision, s, s_len);
775 if (alternate_form && i_num != 0) {
776 *--s = *fmt; /* 'x' or 'X' */
784 s = va_arg(ap, char *);
787 if (adjust_precision && precision < s_len)
801 fp_num = va_arg(ap, double);
803 ** We use &num_buf[ 1 ], so that we have
806 s = conv_fp(*fmt, fp_num, alternate_form,
807 (adjust_precision == NO) ? FLOAT_DIGITS : precision,
808 &is_negative, &num_buf[1], &s_len);
813 else if (print_blank)
820 if (adjust_precision == NO)
821 precision = FLOAT_DIGITS;
822 else if (precision == 0)
825 ** We use &num_buf[ 1 ], so that we have
828 s = ap_gcvt(va_arg(ap, double), precision, &num_buf[1],
834 else if (print_blank)
839 if (alternate_form && (q = strchr(s, '.')) == NULL) {
841 s[s_len] = '\0'; /* delimit for following strchr() */
843 if (*fmt == 'G' && (q = strchr(s, 'e')) != NULL)
849 char_buf[0] = (char) (va_arg(ap, int));
865 *(va_arg(ap, int *)) = cc;
869 ** This is where we extend the printf format,
870 ** with a second type specifier
875 ** If the pointer size is equal to
876 ** the size of an unsigned integer
877 ** we convert the pointer to a hex
878 ** number, otherwise we print "%p"
879 ** to indicate that we don't handle
883 ui_num = (u_wide_int) va_arg(ap, void *);
885 if (sizeof(char *) <= sizeof(u_wide_int))
886 s = conv_p2(ui_num, 4, 'x',
887 &num_buf[NUM_BUF_SIZE], &s_len);
897 ** print a struct sockaddr_in as
902 struct sockaddr_in *si;
904 si = va_arg(ap, struct sockaddr_in *);
906 s = conv_sockaddr_in(si, &num_buf[NUM_BUF_SIZE], &s_len);
907 if (adjust_precision && precision < s_len)
917 /* print a struct in_addr as a.b.c.d */
922 ia = va_arg(ap, struct in_addr *);
924 s = conv_in_addr(ia, &num_buf[NUM_BUF_SIZE], &s_len);
925 if (adjust_precision && precision < s_len)
936 /* if %p ends the string, oh well ignore it */
949 ** The last character of the format string
950 ** was %. We ignore it.
956 ** The default case is for unrecognized %'s.
957 ** We print %<char> to help the user identify
958 ** what option is not understood. This is
959 ** also useful in case the user wants to
960 ** pass the output of format_converter
961 ** to another function that understands
962 ** some other %<char> (like syslog).
963 ** Note that we can't point s inside fmt
964 ** because the unknown <char> could be
965 ** preceded by width etc.
976 if (prefix_char != NUL && s != S_NULL && s != char_buf) {
981 if (adjust_width && adjust == RIGHT && min_width > s_len) {
982 if (pad_char == '0' && prefix_char != NUL) {
983 INS_CHAR(*s, sp, bep, cc);
988 PAD(min_width, s_len, pad_char);
992 ** Print the string s.
994 for (i = s_len; i != 0; i--) {
995 INS_CHAR(*s, sp, bep, cc);
999 if (adjust_width && adjust == LEFT && min_width > s_len)
1000 PAD(min_width, s_len, pad_char);
1010 snprintf_flush(ap_vformatter_buff *vbuff)
1013 ** if the buffer fills we have to abort immediately, there is no way
1014 ** to "flush" a snprintf... there's nowhere to flush it to.
1021 snprintf(char *buf, size_t len, const char *format,...)
1025 ap_vformatter_buff vbuff;
1030 /* save one byte for nul terminator */
1032 vbuff.endpos = buf + len - 1;
1033 va_start(ap, format);
1034 cc = ap_vformatter(snprintf_flush, &vbuff, format, ap);
1036 *vbuff.curpos = '\0';
1037 return (cc == -1) ? len : cc;
1042 vsnprintf(char *buf, size_t len, const char *format, va_list ap)
1045 ap_vformatter_buff vbuff;
1050 /* save one byte for nul terminator */
1052 vbuff.endpos = buf + len - 1;
1053 cc = ap_vformatter(snprintf_flush, &vbuff, format, ap);
1054 *vbuff.curpos = '\0';
1055 return (cc == -1) ? len : cc;