1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * This code is based on, and used with the permission of, the
19 * SIO stdio-replacement strx_* functions by Panos Tsirigotis
20 * <panos@alumni.cs.colorado.edu> for xinetd.
22 #define BUILD_STANDALONE
24 #ifndef BUILD_STANDALONE
27 #include "ap_snprintf.h"
33 #include <sys/types.h>
53 #ifndef AP_LONGEST_LONG
54 #define AP_LONGEST_LONG long
58 #define WIDEST_INT AP_LONGEST_LONG
60 typedef WIDE_INT wide_int;
61 typedef unsigned WIDE_INT u_wide_int;
62 typedef WIDEST_INT widest_int;
64 /* Although Tandem supports "long long" there is no unsigned variant. */
65 typedef unsigned long u_widest_int;
67 typedef unsigned WIDEST_INT u_widest_int;
71 #define S_NULL "(null)"
74 #define FLOAT_DIGITS 6
75 #define EXPONENT_LENGTH 10
78 * NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions
80 * XXX: this is a magic number; do not decrease it
82 #define NUM_BUF_SIZE 512
85 * cvt - IEEE floating point formatting routines.
86 * Derived from UNIX V7, Copyright(C) Caldera International Inc.
90 * ap_ecvt converts to decimal
91 * the number of digits is specified by ndigit
92 * decpt is set to the position of the decimal point
93 * sign is set to 0 for positive, 1 for negative
98 /* buf must have at least NDIG bytes */
99 static char *ap_cvt(double arg, int ndigits, int *decpt, int *sign, int eflag, char *buf)
103 register char *p, *p1;
105 if (ndigits >= NDIG - 1)
114 arg = modf(arg, &fi);
121 while (p1 > &buf[0] && fi != 0) {
122 fj = modf(fi / 10, &fi);
123 *--p1 = (int) ((fj + .03) * 10) + '0';
126 while (p1 < &buf[NDIG])
130 while ((fj = arg * 10) < 1) {
143 while (p <= p1 && p < &buf[NDIG]) {
145 arg = modf(arg, &fj);
146 *p++ = (int) fj + '0';
148 if (p1 >= &buf[NDIG]) {
149 buf[NDIG - 1] = '\0';
172 static char *ap_ecvt(double arg, int ndigits, int *decpt, int *sign, char *buf)
174 return (ap_cvt(arg, ndigits, decpt, sign, 1, buf));
177 static char *ap_fcvt(double arg, int ndigits, int *decpt, int *sign, char *buf)
179 return (ap_cvt(arg, ndigits, decpt, sign, 0, buf));
183 * ap_gcvt - Floating output conversion to
184 * minimal length string
187 static char *ap_gcvt(double number, int ndigit, char *buf, boolean_e altform)
190 register char *p1, *p2;
194 p1 = ap_ecvt(number, ndigit, &decpt, &sign, buf1);
198 for (i = ndigit - 1; i > 0 && p1[i] == '0'; i--)
200 if ((decpt >= 0 && decpt - ndigit > 4)
201 || (decpt < 0 && decpt < -3)) { /* use E-style */
205 for (i = 1; i < ndigit; i++)
215 *p2++ = decpt / 100 + '0';
217 *p2++ = (decpt % 100) / 10 + '0';
218 *p2++ = decpt % 10 + '0';
229 for (i = 1; i <= ndigit; i++) {
234 if (ndigit < decpt) {
235 while (ndigit++ < decpt)
240 if (p2[-1] == '.' && !altform)
247 * The INS_CHAR macro inserts a character in the buffer and writes
248 * the buffer back to disk if necessary
249 * It uses the char pointers sp and bep:
250 * sp points to the next available character in the buffer
251 * bep points to the end-of-buffer+1
252 * While using this macro, note that the nextb pointer is NOT updated.
254 * NOTE: Evaluation of the c argument should not have any side-effects
256 #define INS_CHAR(c, sp, bep, cc) \
259 vbuff->curpos = sp; \
260 if (flush_func(vbuff)) \
262 sp = vbuff->curpos; \
263 bep = vbuff->endpos; \
269 #define NUM( c ) ( c - '0' )
271 #define STR_TO_DEC( str, num ) \
272 num = NUM( *str++ ) ; \
273 while ( ap_isdigit( *str ) ) \
276 num += NUM( *str++ ) ; \
280 * This macro does zero padding so that the precision
281 * requirement is satisfied. The padding is done by
282 * adding '0's to the left of the string that is going
283 * to be printed. We don't allow precision to be large
284 * enough that we continue past the start of s.
286 * NOTE: this makes use of the magic info that s is
287 * always based on num_buf with a size of NUM_BUF_SIZE.
289 #define FIX_PRECISION( adjust, precision, s, s_len ) \
291 int p = precision < NUM_BUF_SIZE - 1 ? precision : NUM_BUF_SIZE - 1; \
292 while ( s_len < p ) \
300 * Macro that does padding. The padding is done by printing
303 #define PAD( width, len, ch ) do \
305 INS_CHAR( ch, sp, bep, cc ) ; \
308 while ( width > len )
311 * Prefix the character ch to the string str
313 * Set the has_prefix flag
315 #define PREFIX( str, length, ch ) *--str = ch ; length++ ; has_prefix = YES
319 * Convert num to its decimal format.
321 * - a pointer to a string containing the number (no sign)
322 * - len contains the length of the string
323 * - is_negative is set to TRUE or FALSE depending on the sign
324 * of the number (always set to FALSE if is_unsigned is TRUE)
326 * The caller provides a buffer for the string: that is the buf_end argument
327 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
328 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
330 * Note: we have 2 versions. One is used when we need to use quads
331 * (conv_10_quad), the other when we don't (conv_10). We're assuming the
334 static char *conv_10(register wide_int num, register bool_int is_unsigned,
335 register bool_int *is_negative, char *buf_end,
338 register char *p = buf_end;
339 register u_wide_int magnitude;
342 magnitude = (u_wide_int) num;
343 *is_negative = FALSE;
346 *is_negative = (num < 0);
349 * On a 2's complement machine, negating the most negative integer
350 * results in a number that cannot be represented as a signed integer.
351 * Here is what we do to obtain the number's magnitude:
352 * a. add 1 to the number
353 * b. negate it (becomes positive)
354 * c. convert it to unsigned
358 wide_int t = num + 1;
360 magnitude = ((u_wide_int) -t) + 1;
363 magnitude = (u_wide_int) num;
367 * We use a do-while loop so that we write at least 1 digit
370 register u_wide_int new_magnitude = magnitude / 10;
372 *--p = (char) (magnitude - new_magnitude * 10 + '0');
373 magnitude = new_magnitude;
381 static char *conv_10_quad(widest_int num, register bool_int is_unsigned,
382 register bool_int *is_negative, char *buf_end,
385 register char *p = buf_end;
386 u_widest_int magnitude;
389 * We see if we can use the faster non-quad version by checking the
390 * number against the largest long value it can be. If <=, we
391 * punt to the quicker version.
393 if ((num <= ULONG_MAX && is_unsigned) || (num <= LONG_MAX && !is_unsigned))
394 return(conv_10( (wide_int)num, is_unsigned, is_negative,
398 magnitude = (u_widest_int) num;
399 *is_negative = FALSE;
402 *is_negative = (num < 0);
405 * On a 2's complement machine, negating the most negative integer
406 * results in a number that cannot be represented as a signed integer.
407 * Here is what we do to obtain the number's magnitude:
408 * a. add 1 to the number
409 * b. negate it (becomes positive)
410 * c. convert it to unsigned
414 widest_int t = num + 1;
416 magnitude = ((u_widest_int) -t) + 1;
419 magnitude = (u_widest_int) num;
423 * We use a do-while loop so that we write at least 1 digit
426 u_widest_int new_magnitude = magnitude / 10;
428 *--p = (char) (magnitude - new_magnitude * 10 + '0');
429 magnitude = new_magnitude;
439 #ifndef BUILD_STANDALONE
440 static char *conv_in_addr(struct in_addr *ia, char *buf_end, int *len)
442 unsigned addr = ntohl(ia->s_addr);
444 bool_int is_negative;
447 p = conv_10((addr & 0x000000FF) , TRUE, &is_negative, p, &sub_len);
449 p = conv_10((addr & 0x0000FF00) >> 8, TRUE, &is_negative, p, &sub_len);
451 p = conv_10((addr & 0x00FF0000) >> 16, TRUE, &is_negative, p, &sub_len);
453 p = conv_10((addr & 0xFF000000) >> 24, TRUE, &is_negative, p, &sub_len);
461 static char *conv_sockaddr_in(struct sockaddr_in *si, char *buf_end, int *len)
464 bool_int is_negative;
467 p = conv_10(ntohs(si->sin_port), TRUE, &is_negative, p, &sub_len);
469 p = conv_in_addr(&si->sin_addr, p, &sub_len);
478 * Convert a floating point number to a string formats 'f', 'e' or 'E'.
479 * The result is placed in buf, and len denotes the length of the string
480 * The sign is returned in the is_negative argument (and is not placed
483 static char *conv_fp(register char format, register double num,
484 boolean_e add_dp, int precision, bool_int *is_negative,
487 register char *s = buf;
493 p = ap_fcvt(num, precision, &decimal_point, is_negative, buf1);
494 else /* either e or E format */
495 p = ap_ecvt(num, precision + 1, &decimal_point, is_negative, buf1);
498 * Check for Infinity and NaN
500 if (ap_isalpha(*p)) {
501 *len = strlen(strcpy(buf, p));
502 *is_negative = FALSE;
507 if (decimal_point <= 0) {
511 while (decimal_point++ < 0)
518 while (decimal_point-- > 0)
520 if (precision > 0 || add_dp)
526 if (precision > 0 || add_dp)
531 * copy the rest of p, the NUL is NOT copied
537 char temp[EXPONENT_LENGTH]; /* for exponent conversion */
539 bool_int exponent_is_negative;
541 *s++ = format; /* either e or E */
543 if (decimal_point != 0) {
544 p = conv_10((wide_int) decimal_point, FALSE, &exponent_is_negative,
545 &temp[EXPONENT_LENGTH], &t_len);
546 *s++ = exponent_is_negative ? '-' : '+';
549 * Make sure the exponent has at least 2 digits
569 * Convert num to a base X number where X is a power of 2. nbits determines X.
570 * For example, if nbits is 3, we do base 8 conversion
572 * a pointer to a string containing the number
574 * The caller provides a buffer for the string: that is the buf_end argument
575 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
576 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
578 * As with conv_10, we have a faster version which is used when
579 * the number isn't quad size.
581 static char *conv_p2(register u_wide_int num, register int nbits,
582 char format, char *buf_end, register int *len)
584 register int mask = (1 << nbits) - 1;
585 register char *p = buf_end;
586 static const char low_digits[] = "0123456789abcdef";
587 static const char upper_digits[] = "0123456789ABCDEF";
588 register const char *digits = (format == 'X') ? upper_digits : low_digits;
591 *--p = digits[num & mask];
600 static char *conv_p2_quad(u_widest_int num, register int nbits,
601 char format, char *buf_end, register int *len)
603 register int mask = (1 << nbits) - 1;
604 register char *p = buf_end;
605 static const char low_digits[] = "0123456789abcdef";
606 static const char upper_digits[] = "0123456789ABCDEF";
607 register const char *digits = (format == 'X') ? upper_digits : low_digits;
609 if (num <= ULONG_MAX)
610 return(conv_p2( (u_wide_int)num, nbits, format, buf_end, len));
613 *--p = digits[num & mask];
624 * Do format conversion placing the output in buffer
626 API_EXPORT(int) ap_vformatter(int (*flush_func)(ap_vformatter_buff *),
627 ap_vformatter_buff *vbuff, const char *fmt, va_list ap)
634 register char *s = NULL;
638 register int min_width = 0;
647 widest_int i_quad = (widest_int) 0;
648 u_widest_int ui_quad;
649 wide_int i_num = (wide_int) 0;
652 char num_buf[NUM_BUF_SIZE];
653 char char_buf[2]; /* for printing %% and %<unknown> */
656 IS_QUAD, IS_LONG, IS_SHORT, IS_INT
658 enum var_type_enum var_type = IS_INT;
663 boolean_e alternate_form;
664 boolean_e print_sign;
665 boolean_e print_blank;
666 boolean_e adjust_precision;
667 boolean_e adjust_width;
668 bool_int is_negative;
675 INS_CHAR(*fmt, sp, bep, cc);
679 * Default variable settings
682 alternate_form = print_sign = print_blank = NO;
689 * Try to avoid checking for flags, width or precision
691 if (!ap_islower(*fmt)) {
693 * Recognize flags: -, #, BLANK, +
698 else if (*fmt == '+')
700 else if (*fmt == '#')
701 alternate_form = YES;
702 else if (*fmt == ' ')
704 else if (*fmt == '0')
711 * Check if a width was specified
713 if (ap_isdigit(*fmt)) {
714 STR_TO_DEC(fmt, min_width);
717 else if (*fmt == '*') {
718 min_width = va_arg(ap, int);
723 min_width = -min_width;
730 * Check if a precision was specified
733 adjust_precision = YES;
735 if (ap_isdigit(*fmt)) {
736 STR_TO_DEC(fmt, precision);
738 else if (*fmt == '*') {
739 precision = va_arg(ap, int);
748 adjust_precision = NO;
751 adjust_precision = adjust_width = NO;
760 else if (*fmt == 'l') {
764 else if (*fmt == 'h') {
773 * Argument extraction and printing.
774 * First we determine the argument type.
775 * Then, we convert the argument to a string.
776 * On exit from the switch, s points to the string that
777 * must be printed, s_len has the length of the string
778 * The precision requirements, if any, are reflected in s_len.
780 * NOTE: pad_char may be set to '0' because of the 0 flag.
781 * It is reset to ' ' by non-numeric formats
785 if (var_type == IS_QUAD) {
786 i_quad = va_arg(ap, u_widest_int);
787 s = conv_10_quad(i_quad, 1, &is_negative,
788 &num_buf[NUM_BUF_SIZE], &s_len);
791 if (var_type == IS_LONG)
792 i_num = (wide_int) va_arg(ap, u_wide_int);
793 else if (var_type == IS_SHORT)
794 i_num = (wide_int) (unsigned short) va_arg(ap, unsigned int);
796 i_num = (wide_int) va_arg(ap, unsigned int);
797 s = conv_10(i_num, 1, &is_negative,
798 &num_buf[NUM_BUF_SIZE], &s_len);
800 FIX_PRECISION(adjust_precision, precision, s, s_len);
805 if (var_type == IS_QUAD) {
806 i_quad = va_arg(ap, widest_int);
807 s = conv_10_quad(i_quad, 0, &is_negative,
808 &num_buf[NUM_BUF_SIZE], &s_len);
811 if (var_type == IS_LONG)
812 i_num = (wide_int) va_arg(ap, wide_int);
813 else if (var_type == IS_SHORT)
814 i_num = (wide_int) (short) va_arg(ap, int);
816 i_num = (wide_int) va_arg(ap, int);
817 s = conv_10(i_num, 0, &is_negative,
818 &num_buf[NUM_BUF_SIZE], &s_len);
820 FIX_PRECISION(adjust_precision, precision, s, s_len);
826 else if (print_blank)
832 if (var_type == IS_QUAD) {
833 ui_quad = va_arg(ap, u_widest_int);
834 s = conv_p2_quad(ui_quad, 3, *fmt,
835 &num_buf[NUM_BUF_SIZE], &s_len);
838 if (var_type == IS_LONG)
839 ui_num = (u_wide_int) va_arg(ap, u_wide_int);
840 else if (var_type == IS_SHORT)
841 ui_num = (u_wide_int) (unsigned short) va_arg(ap, unsigned int);
843 ui_num = (u_wide_int) va_arg(ap, unsigned int);
844 s = conv_p2(ui_num, 3, *fmt,
845 &num_buf[NUM_BUF_SIZE], &s_len);
847 FIX_PRECISION(adjust_precision, precision, s, s_len);
848 if (alternate_form && *s != '0') {
857 if (var_type == IS_QUAD) {
858 ui_quad = va_arg(ap, u_widest_int);
859 s = conv_p2_quad(ui_quad, 4, *fmt,
860 &num_buf[NUM_BUF_SIZE], &s_len);
863 if (var_type == IS_LONG)
864 ui_num = (u_wide_int) va_arg(ap, u_wide_int);
865 else if (var_type == IS_SHORT)
866 ui_num = (u_wide_int) (unsigned short) va_arg(ap, unsigned int);
868 ui_num = (u_wide_int) va_arg(ap, unsigned int);
869 s = conv_p2(ui_num, 4, *fmt,
870 &num_buf[NUM_BUF_SIZE], &s_len);
872 FIX_PRECISION(adjust_precision, precision, s, s_len);
873 if (alternate_form && i_num != 0) {
874 *--s = *fmt; /* 'x' or 'X' */
882 s = va_arg(ap, char *);
885 if (adjust_precision && precision < s_len)
899 fp_num = va_arg(ap, double);
901 * * We use &num_buf[ 1 ], so that we have room for the sign
918 s = conv_fp(*fmt, fp_num, alternate_form,
919 (adjust_precision == NO) ? FLOAT_DIGITS : precision,
920 &is_negative, &num_buf[1], &s_len);
925 else if (print_blank)
933 if (adjust_precision == NO)
934 precision = FLOAT_DIGITS;
935 else if (precision == 0)
938 * * We use &num_buf[ 1 ], so that we have room for the sign
940 s = ap_gcvt(va_arg(ap, double), precision, &num_buf[1],
946 else if (print_blank)
951 if (alternate_form && (q = strchr(s, '.')) == NULL) {
953 s[s_len] = '\0'; /* delimit for following strchr() */
955 if (*fmt == 'G' && (q = strchr(s, 'e')) != NULL)
961 char_buf[0] = (char) (va_arg(ap, int));
977 if (var_type == IS_QUAD)
978 *(va_arg(ap, widest_int *)) = cc;
979 else if (var_type == IS_LONG)
980 *(va_arg(ap, long *)) = cc;
981 else if (var_type == IS_SHORT)
982 *(va_arg(ap, short *)) = cc;
984 *(va_arg(ap, int *)) = cc;
988 * This is where we extend the printf format, with a second
994 * If the pointer size is equal to or smaller than the size
995 * of the largest unsigned int, we convert the pointer to a
996 * hex number, otherwise we print "%p" to indicate that we
1000 #ifdef AP_VOID_P_IS_QUAD
1001 if (sizeof(void *) <= sizeof(u_widest_int)) {
1002 ui_quad = (u_widest_int) va_arg(ap, void *);
1003 s = conv_p2_quad(ui_quad, 4, 'x',
1004 &num_buf[NUM_BUF_SIZE], &s_len);
1007 if (sizeof(void *) <= sizeof(u_wide_int)) {
1008 ui_num = (u_wide_int) va_arg(ap, void *);
1009 s = conv_p2(ui_num, 4, 'x',
1010 &num_buf[NUM_BUF_SIZE], &s_len);
1021 #ifndef BUILD_STANDALONE
1022 /* print a struct sockaddr_in as a.b.c.d:port */
1025 struct sockaddr_in *si;
1027 si = va_arg(ap, struct sockaddr_in *);
1029 s = conv_sockaddr_in(si, &num_buf[NUM_BUF_SIZE], &s_len);
1030 if (adjust_precision && precision < s_len)
1041 /* print a struct in_addr as a.b.c.d */
1046 ia = va_arg(ap, struct in_addr *);
1048 s = conv_in_addr(ia, &num_buf[NUM_BUF_SIZE], &s_len);
1049 if (adjust_precision && precision < s_len)
1062 /* if %p ends the string, oh well ignore it */
1075 * The last character of the format string was %.
1082 * The default case is for unrecognized %'s.
1083 * We print %<char> to help the user identify what
1084 * option is not understood.
1085 * This is also useful in case the user wants to pass
1086 * the output of format_converter to another function
1087 * that understands some other %<char> (like syslog).
1088 * Note that we can't point s inside fmt because the
1089 * unknown <char> could be preceded by width etc.
1100 if (prefix_char != NUL && s != S_NULL && s != char_buf) {
1105 if (adjust_width && adjust == RIGHT && min_width > s_len) {
1106 if (pad_char == '0' && prefix_char != NUL) {
1107 INS_CHAR(*s, sp, bep, cc);
1112 PAD(min_width, s_len, pad_char);
1116 * Print the string s.
1118 for (i = s_len; i != 0; i--) {
1119 INS_CHAR(*s, sp, bep, cc);
1123 if (adjust_width && adjust == LEFT && min_width > s_len)
1124 PAD(min_width, s_len, pad_char);
1134 static int snprintf_flush(ap_vformatter_buff *vbuff)
1136 /* if the buffer fills we have to abort immediately, there is no way
1137 * to "flush" an ap_snprintf... there's nowhere to flush it to.
1143 API_EXPORT_NONSTD(int) ap_snprintf(char *buf, size_t len, const char *format,...)
1147 ap_vformatter_buff vbuff;
1152 /* save one byte for nul terminator */
1154 vbuff.endpos = buf + len - 1;
1155 va_start(ap, format);
1156 cc = ap_vformatter(snprintf_flush, &vbuff, format, ap);
1158 *vbuff.curpos = '\0';
1159 return (cc == -1) ? len : cc;
1163 API_EXPORT(int) ap_vsnprintf(char *buf, size_t len, const char *format,
1167 ap_vformatter_buff vbuff;
1172 /* save one byte for nul terminator */
1174 vbuff.endpos = buf + len - 1;
1175 cc = ap_vformatter(snprintf_flush, &vbuff, format, ap);
1176 *vbuff.curpos = '\0';
1177 return (cc == -1) ? len : cc;