Ruby  2.5.0dev(2017-10-22revision60238)
vsnprintf.c
Go to the documentation of this file.
1 /*-
2  * Copyright (c) 1990, 1993
3  * The Regents of the University of California. All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Torek.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in the
15  * documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  * may be used to endorse or promote products derived from this software
18  * without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * IMPORTANT NOTE:
35  * --------------
36  * From ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
37  * paragraph 3 above is now null and void.
38  */
39 
40 /* SNPRINTF.C
41  * fjc 7-31-97 Modified by Mib Software to be a standalone snprintf.c module.
42  * http://www.mibsoftware.com
43  * Mib Software does not warrant this software any differently than the
44  * University of California, Berkeley as described above. All warranties
45  * are disclaimed. Use this software at your own risk.
46  *
47  * All code referencing FILE * functions was eliminated, since it could
48  * never be called. All header files and necessary files are collapsed
49  * into one file, internal functions are declared static. This should
50  * allow inclusion into libraries with less chance of namespace collisions.
51  *
52  * snprintf should be the only externally visible item.
53  *
54  * As of 7-31-97 FLOATING_POINT is NOT provided. The code is somewhat
55  * non-portable, so it is disabled.
56  */
57 
58 /* Define FLOATING_POINT to get floating point. */
59 /*
60 #define FLOATING_POINT
61 */
62 
63 #include <sys/types.h>
64 #define u_long unsigned long
65 #define u_short unsigned short
66 #define u_int unsigned int
67 
68 #if !defined(HAVE_STDARG_PROTOTYPES)
69 #if defined(__STDC__)
70 #define HAVE_STDARG_PROTOTYPES 1
71 #endif
72 #endif
73 
74 #undef __P
75 #if defined(HAVE_STDARG_PROTOTYPES)
76 # include <stdarg.h>
77 # if !defined(__P)
78 # define __P(x) x
79 # endif
80 #else
81 # define __P(x) ()
82 # if !defined(const)
83 # define const
84 # endif
85 # include <varargs.h>
86 #endif
87 #ifndef _BSD_VA_LIST_
88 #define _BSD_VA_LIST_ va_list
89 #endif
90 
91 #ifdef __STDC__
92 # include <limits.h>
93 #else
94 # ifndef LONG_MAX
95 # ifdef HAVE_LIMITS_H
96 # include <limits.h>
97 # else
98  /* assuming 32bit(2's complement) long */
99 # define LONG_MAX 2147483647
100 # endif
101 # endif
102 #endif
103 
104 #if defined(__hpux) && !defined(__GNUC__) && !defined(__STDC__)
105 #define const
106 #endif
107 
108 #if defined(sgi)
109 #undef __const
110 #define __const
111 #endif /* People who don't like const sys_error */
112 
113 #include <stddef.h>
114 #if defined(__hpux) && !defined(__GNUC__) || defined(__DECC)
115 #include <string.h>
116 #endif
117 
118 #if !defined(__CYGWIN32__) && defined(__hpux) && !defined(__GNUC__)
119 #include <stdlib.h>
120 #endif
121 
122 #ifndef NULL
123 #define NULL 0
124 #endif
125 
126 #if SIZEOF_LONG > SIZEOF_INT
127 # include <errno.h>
128 #endif
129 
130 /*
131  * NB: to fit things in six character monocase externals, the stdio
132  * code uses the prefix `__s' for stdio objects, typically followed
133  * by a three-character attempt at a mnemonic.
134  */
135 
136 /* stdio buffers */
137 struct __sbuf {
138  unsigned char *_base;
139  size_t _size;
140 };
141 
142 
143 /*
144  * stdio state variables.
145  *
146  * The following always hold:
147  *
148  * if (_flags&(__SLBF|__SWR)) == (__SLBF|__SWR),
149  * _lbfsize is -_bf._size, else _lbfsize is 0
150  * if _flags&__SRD, _w is 0
151  * if _flags&__SWR, _r is 0
152  *
153  * This ensures that the getc and putc macros (or inline functions) never
154  * try to write or read from a file that is in `read' or `write' mode.
155  * (Moreover, they can, and do, automatically switch from read mode to
156  * write mode, and back, on "r+" and "w+" files.)
157  *
158  * _lbfsize is used only to make the inline line-buffered output stream
159  * code as compact as possible.
160  *
161  * _ub, _up, and _ur are used when ungetc() pushes back more characters
162  * than fit in the current _bf, or when ungetc() pushes back a character
163  * that does not match the previous one in _bf. When this happens,
164  * _ub._base becomes non-nil (i.e., a stream has ungetc() data iff
165  * _ub._base!=NULL) and _up and _ur save the current values of _p and _r.
166  *
167  * NB: see WARNING above before changing the layout of this structure!
168  */
169 typedef struct __sFILE {
170  unsigned char *_p; /* current position in (some) buffer */
171 #if 0
172  size_t _r; /* read space left for getc() */
173 #endif
174  size_t _w; /* write space left for putc() */
175  short _flags; /* flags, below; this FILE is free if 0 */
176  short _file; /* fileno, if Unix descriptor, else -1 */
177  struct __sbuf _bf; /* the buffer (at least 1 byte, if !NULL) */
178 #if 0
179  size_t _lbfsize; /* 0 or -_bf._size, for inline putc */
180 #endif
181  int (*vwrite)(/* struct __sFILE*, struct __suio * */);
182  const char *(*vextra)(/* struct __sFILE*, size_t, void*, long*, int */);
183 } FILE;
184 
185 
186 #define __SLBF 0x0001 /* line buffered */
187 #define __SNBF 0x0002 /* unbuffered */
188 #define __SRD 0x0004 /* OK to read */
189 #define __SWR 0x0008 /* OK to write */
190  /* RD and WR are never simultaneously asserted */
191 #define __SRW 0x0010 /* open for reading & writing */
192 #define __SEOF 0x0020 /* found EOF */
193 #define __SERR 0x0040 /* found error */
194 #define __SMBF 0x0080 /* _buf is from malloc */
195 #define __SAPP 0x0100 /* fdopen()ed in append mode */
196 #define __SSTR 0x0200 /* this is an sprintf/snprintf string */
197 #define __SOPT 0x0400 /* do fseek() optimisation */
198 #define __SNPT 0x0800 /* do not do fseek() optimisation */
199 #define __SOFF 0x1000 /* set iff _offset is in fact correct */
200 #define __SMOD 0x2000 /* true => fgetln modified _p text */
201 
202 
203 #define EOF (-1)
204 
205 
206 #define BSD__sfeof(p) (((p)->_flags & __SEOF) != 0)
207 #define BSD__sferror(p) (((p)->_flags & __SERR) != 0)
208 #define BSD__sclearerr(p) ((void)((p)->_flags &= ~(__SERR|__SEOF)))
209 #define BSD__sfileno(p) ((p)->_file)
210 
211 #undef feof
212 #undef ferror
213 #undef clearerr
214 #define feof(p) BSD__sfeof(p)
215 #define ferror(p) BSD__sferror(p)
216 #define clearerr(p) BSD__sclearerr(p)
217 
218 #ifndef _ANSI_SOURCE
219 #define fileno(p) BSD__sfileno(p)
220 #endif
221 
222 
223 /*
224  * I/O descriptors for __sfvwrite().
225  */
226 struct __siov {
227  const void *iov_base;
228  size_t iov_len;
229 };
230 struct __suio {
231  struct __siov *uio_iov;
233  size_t uio_resid;
234 };
235 
236 /*
237  * Write some memory regions. Return zero on success, EOF on error.
238  *
239  * This routine is large and unsightly, but most of the ugliness due
240  * to the three different kinds of output buffering is handled here.
241  */
242 static int
243 BSD__sfvwrite(register FILE *fp, register struct __suio *uio)
244 {
245  register size_t len;
246  register const char *p;
247  register struct __siov *iov;
248  register size_t w;
249 
250  if ((len = uio->uio_resid) == 0)
251  return (0);
252 #ifndef __hpux
253 #define MIN(a, b) ((a) < (b) ? (a) : (b))
254 #endif
255 #define COPY(n) (void)memcpy((void *)fp->_p, (void *)p, (size_t)(n))
256 
257  iov = uio->uio_iov;
258  p = iov->iov_base;
259  len = iov->iov_len;
260  iov++;
261 #define GETIOV(extra_work) \
262  while (len == 0) { \
263  extra_work; \
264  p = iov->iov_base; \
265  len = iov->iov_len; \
266  iov++; \
267  }
268  if (fp->_flags & __SNBF) {
269  /* fjc 7-31-97 Will never happen. We are working with
270  strings only
271  */
272  } else if ((fp->_flags & __SLBF) == 0) {
273  /*
274  * Fully buffered: fill partially full buffer, if any,
275  * and then flush. If there is no partial buffer, write
276  * one _bf._size byte chunk directly (without copying).
277  *
278  * String output is a special case: write as many bytes
279  * as fit, but pretend we wrote everything. This makes
280  * snprintf() return the number of bytes needed, rather
281  * than the number used, and avoids its write function
282  * (so that the write function can be invalid).
283  */
284  do {
285  GETIOV(;);
286  w = fp->_w;
287  if (fp->_flags & __SSTR) {
288  if (len < w)
289  w = len;
290  COPY(w); /* copy MIN(fp->_w,len), */
291  fp->_w -= w;
292  fp->_p += w;
293  w = len; /* but pretend copied all */
294  } else {
295  /* fjc 7-31-97 Will never happen. We are working with
296  strings only
297  */
298  }
299  p += w;
300  len -= w;
301  } while ((uio->uio_resid -= w) != 0);
302  } else {
303  /* fjc 7-31-97 Will never happen. We are working with
304  strings only
305  */
306  }
307  return (0);
308 }
309 
310 /*
311  * Actual printf innards.
312  *
313  * This code is large and complicated...
314  */
315 
316 /*
317  * Flush out all the vectors defined by the given uio,
318  * then reset it so that it can be reused.
319  */
320 static int
321 BSD__sprint(FILE *fp, register struct __suio *uio)
322 {
323  register int err;
324 
325  if (uio->uio_resid == 0) {
326  uio->uio_iovcnt = 0;
327  return (0);
328  }
329  err = (*fp->vwrite)(fp, uio);
330  uio->uio_resid = 0;
331  uio->uio_iovcnt = 0;
332  return (err);
333 }
334 
335 
336 /*
337  * Helper function for `fprintf to unbuffered unix file': creates a
338  * temporary buffer. We only work on write-only files; this avoids
339  * worries about ungetc buffers and so forth.
340  */
341 static int
342 BSD__sbprintf(register FILE *fp, const char *fmt, va_list ap)
343 {
344 /* We don't support files. */
345  return 0;
346 }
347 
348 
349 /*
350  * Macros for converting digits to letters and vice versa
351  */
352 #define to_digit(c) ((c) - '0')
353 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
354 #define to_char(n) (char)((n) + '0')
355 
356 #ifdef _HAVE_SANE_QUAD_
357 /*
358  * Convert an unsigned long long to ASCII for printf purposes, returning
359  * a pointer to the first character of the string representation.
360  * Octal numbers can be forced to have a leading zero; hex numbers
361  * use the given digits.
362  */
363 static char *
364 BSD__uqtoa(register u_quad_t val, char *endp, int base, int octzero, const char *xdigs)
365 {
366  register char *cp = endp;
367  register quad_t sval;
368 
369  /*
370  * Handle the three cases separately, in the hope of getting
371  * better/faster code.
372  */
373  switch (base) {
374  case 10:
375  if (val < 10) { /* many numbers are 1 digit */
376  *--cp = to_char(val);
377  return (cp);
378  }
379  /*
380  * On many machines, unsigned arithmetic is harder than
381  * signed arithmetic, so we do at most one unsigned mod and
382  * divide; this is sufficient to reduce the range of
383  * the incoming value to where signed arithmetic works.
384  */
385  if (val > LLONG_MAX) {
386  *--cp = to_char(val % 10);
387  sval = val / 10;
388  } else
389  sval = val;
390  do {
391  *--cp = to_char(sval % 10);
392  sval /= 10;
393  } while (sval != 0);
394  break;
395 
396  case 8:
397  do {
398  *--cp = to_char(val & 7);
399  val >>= 3;
400  } while (val);
401  if (octzero && *cp != '0')
402  *--cp = '0';
403  break;
404 
405  case 16:
406  do {
407  *--cp = xdigs[val & 15];
408  val >>= 4;
409  } while (val);
410  break;
411 
412  default: /* oops */
413  /*
414  abort();
415  */
416  break; /* fjc 7-31-97. Don't reference abort() here */
417  }
418  return (cp);
419 }
420 #endif /* _HAVE_SANE_QUAD_ */
421 
422 /*
423  * Convert an unsigned long to ASCII for printf purposes, returning
424  * a pointer to the first character of the string representation.
425  * Octal numbers can be forced to have a leading zero; hex numbers
426  * use the given digits.
427  */
428 static char *
429 BSD__ultoa(register u_long val, char *endp, int base, int octzero, const char *xdigs)
430 {
431  register char *cp = endp;
432  register long sval;
433 
434  /*
435  * Handle the three cases separately, in the hope of getting
436  * better/faster code.
437  */
438  switch (base) {
439  case 10:
440  if (val < 10) { /* many numbers are 1 digit */
441  *--cp = to_char(val);
442  return (cp);
443  }
444  /*
445  * On many machines, unsigned arithmetic is harder than
446  * signed arithmetic, so we do at most one unsigned mod and
447  * divide; this is sufficient to reduce the range of
448  * the incoming value to where signed arithmetic works.
449  */
450  if (val > LONG_MAX) {
451  *--cp = to_char(val % 10);
452  sval = val / 10;
453  } else
454  sval = val;
455  do {
456  *--cp = to_char(sval % 10);
457  sval /= 10;
458  } while (sval != 0);
459  break;
460 
461  case 8:
462  do {
463  *--cp = to_char(val & 7);
464  val >>= 3;
465  } while (val);
466  if (octzero && *cp != '0')
467  *--cp = '0';
468  break;
469 
470  case 16:
471  do {
472  *--cp = xdigs[val & 15];
473  val >>= 4;
474  } while (val);
475  break;
476 
477  default: /* oops */
478  /*
479  abort();
480  */
481  break; /* fjc 7-31-97. Don't reference abort() here */
482  }
483  return (cp);
484 }
485 
486 #ifdef FLOATING_POINT
487 #include <math.h>
488 #include <float.h>
489 /* #include "floatio.h" */
490 
491 #ifndef MAXEXP
492 # if DBL_MAX_10_EXP > -DBL_MIN_10_EXP
493 # define MAXEXP (DBL_MAX_10_EXP)
494 # else
495 # define MAXEXP (-DBL_MIN_10_EXP)
496 # endif
497 #endif
498 
499 #ifndef MAXFRACT
500 # define MAXFRACT (MAXEXP*10/3)
501 #endif
502 
503 #define BUF (MAXEXP+MAXFRACT+1) /* + decimal point */
504 #define DEFPREC 6
505 
506 static char *cvt(double, int, int, char *, int *, int, int *, char *);
507 static int exponent(char *, int, int);
508 
509 #else /* no FLOATING_POINT */
510 
511 #define BUF 68
512 
513 #endif /* FLOATING_POINT */
514 
515 #ifndef lower_hexdigits
516 # define lower_hexdigits "0123456789abcdef"
517 #endif
518 #ifndef upper_hexdigits
519 # define upper_hexdigits "0123456789ABCDEF"
520 #endif
521 
522 /*
523  * Flags used during conversion.
524  */
525 #define ALT 0x001 /* alternate form */
526 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
527 #define LADJUST 0x004 /* left adjustment */
528 #define LONGDBL 0x008 /* long double; unimplemented */
529 #define LONGINT 0x010 /* long integer */
530 
531 #ifdef _HAVE_SANE_QUAD_
532 #define QUADINT 0x020 /* quad integer */
533 #endif /* _HAVE_SANE_QUAD_ */
534 
535 #define SHORTINT 0x040 /* short integer */
536 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
537 #define FPT 0x100 /* Floating point number */
538 static ssize_t
539 BSD_vfprintf(FILE *fp, const char *fmt0, va_list ap)
540 {
541 #ifdef PRI_EXTRA_MARK
543 #endif
544  register const char *fmt; /* format string */
545  register int ch; /* character from fmt */
546  register int n; /* handy integer (short term usage) */
547  register const char *cp;/* handy char pointer (short term usage) */
548  register struct __siov *iovp;/* for PRINT macro */
549  register int flags; /* flags as above */
550  ssize_t ret; /* return value accumulator */
551  int width; /* width from format (%8d), or 0 */
552  int prec; /* precision from format (%.3d), or -1 */
553  char sign; /* sign prefix (' ', '+', '-', or \0) */
554 #ifdef FLOATING_POINT
555  char softsign; /* temporary negative sign for floats */
556  double _double = 0; /* double precision arguments %[eEfgG] */
557  int expt; /* integer value of exponent */
558  int expsize = 0; /* character count for expstr */
559  int ndig = 0; /* actual number of digits returned by cvt */
560  int fprec = 0; /* floating point precision */
561  char expstr[7]; /* buffer for exponent string */
562 #endif
563  u_long MAYBE_UNUSED(ulval); /* integer arguments %[diouxX] */
564 #ifdef _HAVE_SANE_QUAD_
565  u_quad_t MAYBE_UNUSED(uqval); /* %q integers */
566 #endif /* _HAVE_SANE_QUAD_ */
567  int base; /* base for [diouxX] conversion */
568  int dprec; /* a copy of prec if [diouxX], 0 otherwise */
569  long fieldsz; /* field size expanded by sign, etc */
570  long realsz; /* field size expanded by dprec */
571  int size; /* size of converted field or string */
572  const char *xdigs = 0; /* digits for [xX] conversion */
573 #define NIOV 8
574  struct __suio uio; /* output information: summary */
575  struct __siov iov[NIOV];/* ... and individual io vectors */
576  char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
577  char ox[4]; /* space for 0x hex-prefix, hexadecimal's 1. */
578  char *const ebuf = buf + sizeof(buf);
579 #if SIZEOF_LONG > SIZEOF_INT
580  long ln;
581 #endif
582 
583  /*
584  * Choose PADSIZE to trade efficiency vs. size. If larger printf
585  * fields occur frequently, increase PADSIZE and make the initializers
586  * below longer.
587  */
588 #define PADSIZE 16 /* pad chunk size */
589  static const char blanks[PADSIZE] =
590  {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
591  static const char zeroes[PADSIZE] =
592  {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
593 
594  /*
595  * BEWARE, these `goto error' on error, and PAD uses `n'.
596  */
597 #define PRINT(ptr, len) { \
598  iovp->iov_base = (ptr); \
599  iovp->iov_len = (len); \
600  uio.uio_resid += (len); \
601  iovp++; \
602  if (++uio.uio_iovcnt >= NIOV) { \
603  if (BSD__sprint(fp, &uio)) \
604  goto error; \
605  iovp = iov; \
606  } \
607 }
608 #define PAD(howmany, with) { \
609  if ((n = (howmany)) > 0) { \
610  while (n > PADSIZE) { \
611  PRINT((with), PADSIZE); \
612  n -= PADSIZE; \
613  } \
614  PRINT((with), n); \
615  } \
616 }
617 #if SIZEOF_LONG > SIZEOF_INT
618  /* abandon if too larger padding */
619 #define PAD_L(howmany, with) { \
620  ln = (howmany); \
621  if ((long)((int)ln) != ln) { \
622  errno = ENOMEM; \
623  goto error; \
624  } \
625  if (ln > 0) PAD((int)ln, (with)); \
626 }
627 #else
628 #define PAD_L(howmany, with) PAD((howmany), (with))
629 #endif
630 #define FLUSH() { \
631  if (uio.uio_resid && BSD__sprint(fp, &uio)) \
632  goto error; \
633  uio.uio_iovcnt = 0; \
634  iovp = iov; \
635 }
636 
637  /*
638  * To extend shorts properly, we need both signed and unsigned
639  * argument extraction methods.
640  */
641 #define SARG() \
642  (flags&LONGINT ? va_arg(ap, long) : \
643  flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
644  (long)va_arg(ap, int))
645 #define UARG() \
646  (flags&LONGINT ? va_arg(ap, u_long) : \
647  flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
648  (u_long)va_arg(ap, u_int))
649 
650  /* optimize fprintf(stderr) (and other unbuffered Unix files) */
651  if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
652  fp->_file >= 0)
653  return (BSD__sbprintf(fp, fmt0, ap));
654 
655  fmt = fmt0;
656  uio.uio_iov = iovp = iov;
657  uio.uio_resid = 0;
658  uio.uio_iovcnt = 0;
659  ret = 0;
660  xdigs = 0;
661 
662  /*
663  * Scan the format for conversions (`%' character).
664  */
665  for (;;) {
666  size_t nc;
667  for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
668  /* void */;
669  if ((nc = fmt - cp) != 0) {
670  PRINT(cp, nc);
671  ret += nc;
672  }
673  if (ch == '\0')
674  goto done;
675  fmt++; /* skip over '%' */
676 
677  flags = 0;
678  dprec = 0;
679  width = 0;
680  prec = -1;
681  sign = '\0';
682 
683 rflag: ch = *fmt++;
684 reswitch: switch (ch) {
685  case ' ':
686  /*
687  * ``If the space and + flags both appear, the space
688  * flag will be ignored.''
689  * -- ANSI X3J11
690  */
691  if (!sign)
692  sign = ' ';
693  goto rflag;
694  case '#':
695  flags |= ALT;
696  goto rflag;
697  case '*':
698  /*
699  * ``A negative field width argument is taken as a
700  * - flag followed by a positive field width.''
701  * -- ANSI X3J11
702  * They don't exclude field widths read from args.
703  */
704  if ((width = va_arg(ap, int)) >= 0)
705  goto rflag;
706  width = -width;
707  /* FALLTHROUGH */
708  case '-':
709  flags |= LADJUST;
710  goto rflag;
711  case '+':
712  sign = '+';
713  goto rflag;
714  case '.':
715  if ((ch = *fmt++) == '*') {
716  n = va_arg(ap, int);
717  prec = n < 0 ? -1 : n;
718  goto rflag;
719  }
720  n = 0;
721  while (is_digit(ch)) {
722  n = 10 * n + to_digit(ch);
723  ch = *fmt++;
724  }
725  prec = n < 0 ? -1 : n;
726  goto reswitch;
727  case '0':
728  /*
729  * ``Note that 0 is taken as a flag, not as the
730  * beginning of a field width.''
731  * -- ANSI X3J11
732  */
733  flags |= ZEROPAD;
734  goto rflag;
735  case '1': case '2': case '3': case '4':
736  case '5': case '6': case '7': case '8': case '9':
737  n = 0;
738  do {
739  n = 10 * n + to_digit(ch);
740  ch = *fmt++;
741  } while (is_digit(ch));
742  width = n;
743  goto reswitch;
744 #ifdef FLOATING_POINT
745  case 'L':
746  flags |= LONGDBL;
747  goto rflag;
748 #endif
749  case 'h':
750  flags |= SHORTINT;
751  goto rflag;
752 #if SIZEOF_PTRDIFF_T == SIZEOF_LONG
753  case 't':
754 #endif
755 #if SIZEOF_SIZE_T == SIZEOF_LONG
756  case 'z':
757 #endif
758  case 'l':
759 #ifdef _HAVE_SANE_QUAD_
760  if (*fmt == 'l') {
761  fmt++;
762  flags |= QUADINT;
763  } else {
764  flags |= LONGINT;
765  }
766 #else
767  flags |= LONGINT;
768 #endif
769  goto rflag;
770 #ifdef _HAVE_SANE_QUAD_
771 #if SIZEOF_PTRDIFF_T == SIZEOF_LONG_LONG
772  case 't':
773 #endif
774 #if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
775  case 'z':
776 #endif
777  case 'q':
778  flags |= QUADINT;
779  goto rflag;
780 #endif /* _HAVE_SANE_QUAD_ */
781 #ifdef _WIN32
782  case 'I':
783  if (*fmt == '3' && *(fmt + 1) == '2') {
784  fmt += 2;
785  flags |= LONGINT;
786  }
787 #ifdef _HAVE_SANE_QUAD_
788  else if (*fmt == '6' && *(fmt + 1) == '4') {
789  fmt += 2;
790  flags |= QUADINT;
791  }
792 #endif
793  else
794 #if defined(_HAVE_SANE_QUAD_) && SIZEOF_SIZE_T == SIZEOF_LONG_LONG
795  flags |= QUADINT;
796 #else
797  flags |= LONGINT;
798 #endif
799  goto rflag;
800 #endif
801  case 'c':
802  cp = buf;
803  *buf = (char)va_arg(ap, int);
804  size = 1;
805  sign = '\0';
806  break;
807  case 'i':
808 #ifdef _HAVE_SANE_QUAD_
809 # define INTPTR_MASK (QUADINT|LONGINT|SHORTINT)
810 #else
811 # define INTPTR_MASK (LONGINT|SHORTINT)
812 #endif
813 #if defined _HAVE_SANE_QUAD_ && SIZEOF_VOIDP == SIZEOF_LONG_LONG
814 # define INTPTR_FLAG QUADINT
815 #elif SIZEOF_VOIDP == SIZEOF_LONG
816 # define INTPTR_FLAG LONGINT
817 #else
818 # define INTPTR_FLAG 0
819 #endif
820 #ifdef PRI_EXTRA_MARK
821 # define IS_PRI_EXTRA_MARK(s) \
822  (PRI_EXTRA_MARK_LEN < 1 || \
823  (*(s) == PRI_EXTRA_MARK[0] && \
824  (PRI_EXTRA_MARK_LEN == 1 || \
825  strncmp((s)+1, PRI_EXTRA_MARK+1, \
826  PRI_EXTRA_MARK_LEN-1) == 0)))
827 #else
828 # define PRI_EXTRA_MARK_LEN 0
829 # define IS_PRI_EXTRA_MARK(s) 1
830 #endif
831  if (fp->vextra && (flags & INTPTR_MASK) == INTPTR_FLAG &&
832  IS_PRI_EXTRA_MARK(fmt)) {
833  fmt += PRI_EXTRA_MARK_LEN;
834  FLUSH();
835 #if defined _HAVE_SANE_QUAD_ && SIZEOF_VOIDP == SIZEOF_LONG_LONG
836  uqval = va_arg(ap, u_quad_t);
837  cp = (*fp->vextra)(fp, sizeof(uqval), &uqval, &fieldsz, sign);
838 #else
839  ulval = va_arg(ap, u_long);
840  cp = (*fp->vextra)(fp, sizeof(ulval), &ulval, &fieldsz, sign);
841 #endif
842  sign = '\0';
843  if (!cp) goto error;
844  if (prec < 0) goto long_len;
845  size = fieldsz < prec ? (int)fieldsz : prec;
846  break;
847  }
848  goto decimal;
849  case 'D':
850  flags |= LONGINT;
851  /*FALLTHROUGH*/
852  case 'd':
853  decimal:
854 #ifdef _HAVE_SANE_QUAD_
855  if (flags & QUADINT) {
856  uqval = va_arg(ap, quad_t);
857  if ((quad_t)uqval < 0) {
858  uqval = -(quad_t)uqval;
859  sign = '-';
860  }
861  } else
862 #endif /* _HAVE_SANE_QUAD_ */
863  {
864  ulval = SARG();
865  if ((long)ulval < 0) {
866  ulval = (u_long)(-(long)ulval);
867  sign = '-';
868  }
869  }
870  base = 10;
871  goto number;
872 #ifdef FLOATING_POINT
873  case 'a':
874  case 'A':
875  if (prec > 0) {
876  flags |= ALT;
877  prec++;
878  fprec = prec;
879  }
880  goto fp_begin;
881  case 'e': /* anomalous precision */
882  case 'E':
883  if (prec != 0)
884  flags |= ALT;
885  prec = (prec == -1) ?
886  DEFPREC + 1 : (fprec = prec + 1);
887  /* FALLTHROUGH */
888  goto fp_begin;
889  case 'f': /* always print trailing zeroes */
890  if (prec != 0)
891  flags |= ALT;
892  case 'g':
893  case 'G':
894  if (prec == -1)
895  prec = DEFPREC;
896  else
897  fprec = prec;
898 fp_begin: _double = va_arg(ap, double);
899  /* do this before tricky precision changes */
900  if (isinf(_double)) {
901  if (_double < 0)
902  sign = '-';
903  cp = "Inf";
904  size = 3;
905  break;
906  }
907  if (isnan(_double)) {
908  cp = "NaN";
909  size = 3;
910  break;
911  }
912  flags |= FPT;
913  cp = cvt(_double, (prec < MAXFRACT ? prec : MAXFRACT), flags, &softsign,
914  &expt, ch, &ndig, buf);
915  if (ch == 'g' || ch == 'G') {
916  if (expt <= -4 || (expt > prec && expt > 1))
917  ch = (ch == 'g') ? 'e' : 'E';
918  else
919  ch = 'g';
920  }
921  if (ch == 'a' || ch == 'A') {
922  flags |= HEXPREFIX;
923  --expt;
924  expsize = exponent(expstr, expt, ch + 'p' - 'a');
925  ch += 'x' - 'a';
926  size = expsize + ndig;
927  if (ndig > 1 || flags & ALT)
928  ++size; /* floating point */
929  }
930  else if (ch <= 'e') { /* 'e' or 'E' fmt */
931  --expt;
932  expsize = exponent(expstr, expt, ch);
933  size = expsize + ndig;
934  if (ndig > 1 || flags & ALT)
935  ++fprec, ++size;
936  } else if (ch == 'f') { /* f fmt */
937  if (expt > 0) {
938  size = expt;
939  if (prec || flags & ALT)
940  size += prec + 1;
941  } else if (!prec) { /* "0" */
942  size = 1;
943  if (flags & ALT)
944  size += 1;
945  } else /* "0.X" */
946  size = prec + 2;
947  } else if (expt >= ndig) { /* fixed g fmt */
948  size = expt;
949  if (flags & ALT)
950  ++size;
951  } else
952  size = ndig + (expt > 0 ?
953  1 : 2 - expt);
954 
955  if (softsign)
956  sign = '-';
957  break;
958 #endif /* FLOATING_POINT */
959  case 'n':
960 #ifdef _HAVE_SANE_QUAD_
961  if (flags & QUADINT)
962  *va_arg(ap, quad_t *) = ret;
963  else if (flags & LONGINT)
964 #else /* _HAVE_SANE_QUAD_ */
965  if (flags & LONGINT)
966 #endif /* _HAVE_SANE_QUAD_ */
967  *va_arg(ap, long *) = ret;
968  else if (flags & SHORTINT)
969  *va_arg(ap, short *) = (short)ret;
970  else
971  *va_arg(ap, int *) = (int)ret;
972  continue; /* no output */
973  case 'O':
974  flags |= LONGINT;
975  /*FALLTHROUGH*/
976  case 'o':
977 #ifdef _HAVE_SANE_QUAD_
978  if (flags & QUADINT)
979  uqval = va_arg(ap, u_quad_t);
980  else
981 #endif /* _HAVE_SANE_QUAD_ */
982  ulval = UARG();
983  base = 8;
984  goto nosign;
985  case 'p':
986  /*
987  * ``The argument shall be a pointer to void. The
988  * value of the pointer is converted to a sequence
989  * of printable characters, in an implementation-
990  * defined manner.''
991  * -- ANSI X3J11
992  */
993  prec = (int)(sizeof(void*)*CHAR_BIT/4);
994 #ifdef _HAVE_LLP64_
995  uqval = (u_quad_t)va_arg(ap, void *);
996  flags = (flags) | QUADINT | HEXPREFIX;
997 #else
998  ulval = (u_long)va_arg(ap, void *);
999 #ifdef _HAVE_SANE_QUAD_
1000  flags = (flags & ~QUADINT) | HEXPREFIX;
1001 #else /* _HAVE_SANE_QUAD_ */
1002  flags = (flags) | HEXPREFIX;
1003 #endif /* _HAVE_SANE_QUAD_ */
1004 #endif
1005  base = 16;
1006  xdigs = lower_hexdigits;
1007  ch = 'x';
1008  goto nosign;
1009  case 's':
1010  if ((cp = va_arg(ap, char *)) == NULL)
1011  cp = "(null)";
1012  if (prec >= 0) {
1013  /*
1014  * can't use strlen; can only look for the
1015  * NUL in the first `prec' characters, and
1016  * strlen() will go further.
1017  */
1018  const char *p = (char *)memchr(cp, 0, prec);
1019 
1020  if (p != NULL && (p - cp) < prec)
1021  size = (int)(p - cp);
1022  else
1023  size = prec;
1024  }
1025  else {
1026  fieldsz = strlen(cp);
1027  goto long_len;
1028  }
1029  sign = '\0';
1030  break;
1031  case 'U':
1032  flags |= LONGINT;
1033  /*FALLTHROUGH*/
1034  case 'u':
1035 #ifdef _HAVE_SANE_QUAD_
1036  if (flags & QUADINT)
1037  uqval = va_arg(ap, u_quad_t);
1038  else
1039 #endif /* _HAVE_SANE_QUAD_ */
1040  ulval = UARG();
1041  base = 10;
1042  goto nosign;
1043  case 'X':
1044  xdigs = upper_hexdigits;
1045  goto hex;
1046  case 'x':
1047  xdigs = lower_hexdigits;
1048 hex:
1049 #ifdef _HAVE_SANE_QUAD_
1050  if (flags & QUADINT)
1051  uqval = va_arg(ap, u_quad_t);
1052  else
1053 #endif /* _HAVE_SANE_QUAD_ */
1054  ulval = UARG();
1055  base = 16;
1056  /* leading 0x/X only if non-zero */
1057  if (flags & ALT &&
1058 #ifdef _HAVE_SANE_QUAD_
1059  (flags & QUADINT ? uqval != 0 : ulval != 0)
1060 #else /* _HAVE_SANE_QUAD_ */
1061  ulval != 0
1062 #endif /* _HAVE_SANE_QUAD_ */
1063  )
1064  flags |= HEXPREFIX;
1065 
1066  /* unsigned conversions */
1067 nosign: sign = '\0';
1068  /*
1069  * ``... diouXx conversions ... if a precision is
1070  * specified, the 0 flag will be ignored.''
1071  * -- ANSI X3J11
1072  */
1073 number: if ((dprec = prec) >= 0)
1074  flags &= ~ZEROPAD;
1075 
1076  /*
1077  * ``The result of converting a zero value with an
1078  * explicit precision of zero is no characters.''
1079  * -- ANSI X3J11
1080  */
1081  cp = ebuf;
1082 #ifdef _HAVE_SANE_QUAD_
1083  if (flags & QUADINT) {
1084  if (uqval != 0 || prec != 0)
1085  cp = BSD__uqtoa(uqval, ebuf, base,
1086  flags & ALT, xdigs);
1087  } else
1088 #else /* _HAVE_SANE_QUAD_ */
1089 #endif /* _HAVE_SANE_QUAD_ */
1090  {
1091  if (ulval != 0 || prec != 0)
1092  cp = BSD__ultoa(ulval, ebuf, base,
1093  flags & ALT, xdigs);
1094  }
1095  size = (int)(ebuf - cp);
1096  break;
1097  default: /* "%?" prints ?, unless ? is NUL */
1098  if (ch == '\0')
1099  goto done;
1100  /* pretend it was %c with argument ch */
1101  cp = buf;
1102  *buf = ch;
1103  size = 1;
1104  sign = '\0';
1105  break;
1106  }
1107 
1108  /*
1109  * All reasonable formats wind up here. At this point, `cp'
1110  * points to a string which (if not flags&LADJUST) should be
1111  * padded out to `width' places. If flags&ZEROPAD, it should
1112  * first be prefixed by any sign or other prefix; otherwise,
1113  * it should be blank padded before the prefix is emitted.
1114  * After any left-hand padding and prefixing, emit zeroes
1115  * required by a decimal [diouxX] precision, then print the
1116  * string proper, then emit zeroes required by any leftover
1117  * floating precision; finally, if LADJUST, pad with blanks.
1118  *
1119  * Compute actual size, so we know how much to pad.
1120  * fieldsz excludes decimal prec; realsz includes it.
1121  */
1122  fieldsz = size;
1123 long_len:
1124  realsz = dprec > fieldsz ? dprec : fieldsz;
1125  if (sign)
1126  realsz++;
1127  if (flags & HEXPREFIX)
1128  realsz += 2;
1129 
1130  /* right-adjusting blank padding */
1131  if ((flags & (LADJUST|ZEROPAD)) == 0)
1132  PAD_L(width - realsz, blanks);
1133 
1134  /* prefix */
1135  if (sign) {
1136  PRINT(&sign, 1);
1137  }
1138  if (flags & HEXPREFIX) {
1139  ox[0] = '0';
1140  ox[1] = ch;
1141  PRINT(ox, 2);
1142  }
1143 
1144  /* right-adjusting zero padding */
1145  if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1146  PAD_L(width - realsz, zeroes);
1147 
1148  /* leading zeroes from decimal precision */
1149  PAD_L(dprec - fieldsz, zeroes);
1150 
1151  /* the string or number proper */
1152 #ifdef FLOATING_POINT
1153  if ((flags & FPT) == 0) {
1154  PRINT(cp, fieldsz);
1155  } else { /* glue together f_p fragments */
1156  if (flags & HEXPREFIX) {
1157  if (ndig > 1 || flags & ALT) {
1158  ox[2] = *cp++;
1159  ox[3] = '.';
1160  PRINT(ox+2, 2);
1161  if (ndig > 0) PRINT(cp, ndig-1);
1162  } else /* XpYYY */
1163  PRINT(cp, 1);
1164  PAD(fprec-ndig, zeroes);
1165  PRINT(expstr, expsize);
1166  }
1167  else if (ch >= 'f') { /* 'f' or 'g' */
1168  if (_double == 0) {
1169  /* kludge for __dtoa irregularity */
1170  if (ndig <= 1 &&
1171  (flags & ALT) == 0) {
1172  PRINT("0", 1);
1173  } else {
1174  PRINT("0.", 2);
1175  PAD((ndig >= fprec ? ndig - 1 : fprec - (ch != 'f')),
1176  zeroes);
1177  }
1178  } else if (expt == 0 && ndig == 0 && (flags & ALT) == 0) {
1179  PRINT("0", 1);
1180  } else if (expt <= 0) {
1181  PRINT("0.", 2);
1182  PAD(-expt, zeroes);
1183  PRINT(cp, ndig);
1184  if (flags & ALT)
1185  PAD(fprec - ndig + (ch == 'f' ? expt : 0), zeroes);
1186  } else if (expt >= ndig) {
1187  PRINT(cp, ndig);
1188  PAD(expt - ndig, zeroes);
1189  if (flags & ALT)
1190  PRINT(".", 1);
1191  } else {
1192  PRINT(cp, expt);
1193  cp += expt;
1194  PRINT(".", 1);
1195  PRINT(cp, ndig-expt);
1196  if (flags & ALT)
1197  PAD(fprec - ndig + (ch == 'f' ? expt : 0), zeroes);
1198  }
1199  } else { /* 'e' or 'E' */
1200  if (ndig > 1 || flags & ALT) {
1201  ox[0] = *cp++;
1202  ox[1] = '.';
1203  PRINT(ox, 2);
1204  if (_double /*|| flags & ALT == 0*/) {
1205  PRINT(cp, ndig-1);
1206  } else /* 0.[0..] */
1207  /* __dtoa irregularity */
1208  PAD(ndig - 1, zeroes);
1209  if (flags & ALT) PAD(fprec - ndig - 1, zeroes);
1210  } else /* XeYYY */
1211  PRINT(cp, 1);
1212  PRINT(expstr, expsize);
1213  }
1214  }
1215 #else
1216  PRINT(cp, fieldsz);
1217 #endif
1218  /* left-adjusting padding (always blank) */
1219  if (flags & LADJUST)
1220  PAD_L(width - realsz, blanks);
1221 
1222  /* finally, adjust ret */
1223  ret += width > realsz ? width : realsz;
1224 
1225  FLUSH(); /* copy out the I/O vectors */
1226  }
1227 done:
1228  FLUSH();
1229 error:
1230  return (BSD__sferror(fp) ? EOF : ret);
1231  /* NOTREACHED */
1232 }
1233 
1234 #ifdef FLOATING_POINT
1235 
1236 extern char *BSD__dtoa(double, int, int, int *, int *, char **);
1237 extern char *BSD__hdtoa(double, const char *, int, int *, int *, char **);
1238 
1239 static char *
1240 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch, int *length, char *buf)
1241 {
1242  int mode, dsgn;
1243  char *digits, *bp, *rve;
1244 
1245  if (ch == 'f')
1246  mode = 3;
1247  else {
1248  mode = 2;
1249  }
1250  if (value < 0) {
1251  value = -value;
1252  *sign = '-';
1253  } else if (value == 0.0 && 1.0/value < 0) {
1254  *sign = '-';
1255  } else {
1256  *sign = '\000';
1257  }
1258  if (ch == 'a' || ch =='A') {
1259  digits = BSD__hdtoa(value,
1260  ch == 'a' ? lower_hexdigits : upper_hexdigits,
1261  ndigits, decpt, &dsgn, &rve);
1262  }
1263  else {
1264  digits = BSD__dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1265  }
1266  buf[0] = 0; /* rve - digits may be 0 */
1267  memcpy(buf, digits, rve - digits);
1268  xfree(digits);
1269  rve = buf + (rve - digits);
1270  digits = buf;
1271  if (flags & ALT) { /* Print trailing zeros */
1272  bp = digits + ndigits;
1273  if (ch == 'f') {
1274  if (*digits == '0' && value)
1275  *decpt = -ndigits + 1;
1276  bp += *decpt;
1277  }
1278  while (rve < bp)
1279  *rve++ = '0';
1280  }
1281  *length = (int)(rve - digits);
1282  return (digits);
1283 }
1284 
1285 static int
1286 exponent(char *p0, int exp, int fmtch)
1287 {
1288  register char *p, *t;
1289  char expbuf[2 + (MAXEXP < 1000 ? 3 : MAXEXP < 10000 ? 4 : 5)]; /* >= 2 + ceil(log10(MAXEXP)) */
1290 
1291  p = p0;
1292  *p++ = fmtch;
1293  if (exp < 0) {
1294  exp = -exp;
1295  *p++ = '-';
1296  }
1297  else
1298  *p++ = '+';
1299  t = expbuf + sizeof(expbuf);
1300  if (exp > 9) {
1301  do {
1302  *--t = to_char(exp % 10);
1303  } while ((exp /= 10) > 9);
1304  *--t = to_char(exp);
1305  for (; t < expbuf + sizeof(expbuf); *p++ = *t++);
1306  }
1307  else {
1308  if (fmtch & 15) *p++ = '0'; /* other than p or P */
1309  *p++ = to_char(exp);
1310  }
1311  return (int)(p - p0);
1312 }
1313 #endif /* FLOATING_POINT */
size_t strlen(const char *)
unsigned char * _base
Definition: vsnprintf.c:138
#define __SSTR
Definition: vsnprintf.c:196
#define to_digit(c)
Definition: vsnprintf.c:352
#define BSD__hdtoa
Definition: sprintf.c:1244
#define HEXPREFIX
Definition: vsnprintf.c:526
#define IS_PRI_EXTRA_MARK(s)
short _file
Definition: vsnprintf.c:176
#define MAYBE_UNUSED(x)
Definition: internal.h:46
#define ZEROPAD
Definition: vsnprintf.c:536
#define LONGDBL
Definition: vsnprintf.c:528
#define upper_hexdigits
Definition: vsnprintf.c:519
const void * iov_base
Definition: vsnprintf.c:227
int uio_iovcnt
Definition: vsnprintf.c:232
#define NULL
Definition: vsnprintf.c:123
#define to_char(n)
Definition: vsnprintf.c:354
#define FLUSH()
#define LONG_MAX
Definition: vsnprintf.c:99
unsigned char * _p
Definition: vsnprintf.c:170
#define LONGINT
Definition: vsnprintf.c:529
#define SARG()
#define val
#define INTPTR_MASK
#define __SWR
Definition: vsnprintf.c:189
#define PAD(howmany, with)
#define PRI_EXTRA_MARK
Definition: sprintf.c:1246
RUBY_EXTERN int isinf(double)
Definition: isinf.c:56
short _flags
Definition: vsnprintf.c:175
int err
Definition: win32.c:135
#define __SLBF
Definition: vsnprintf.c:186
#define EOF
Definition: vsnprintf.c:203
#define PAD_L(howmany, with)
#define LADJUST
Definition: vsnprintf.c:527
#define rb_strlen_lit(str)
Definition: intern.h:845
#define PADSIZE
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4309
size_t uio_resid
Definition: vsnprintf.c:233
#define GETIOV(extra_work)
struct __siov * uio_iov
Definition: vsnprintf.c:231
#define isnan(x)
Definition: win32.h:346
struct __sFILE FILE
#define CHAR_BIT
Definition: ruby.h:196
register unsigned int len
Definition: zonetab.h:51
int size
Definition: encoding.c:57
#define BUF
Definition: vsnprintf.c:511
size_t _size
Definition: vsnprintf.c:139
#define is_digit(c)
Definition: vsnprintf.c:353
size_t _w
Definition: vsnprintf.c:174
#define FPT
Definition: vsnprintf.c:537
#define PRI_EXTRA_MARK_LEN
#define lower_hexdigits
Definition: vsnprintf.c:516
#define BSD__dtoa
Definition: sprintf.c:1243
#define ALT
Definition: vsnprintf.c:525
#define u_long
Definition: vsnprintf.c:64
#define PRINT(ptr, len)
void void xfree(void *)
#define __SNBF
Definition: vsnprintf.c:187
#define UARG()
#define INTPTR_FLAG
int(* vwrite)()
Definition: vsnprintf.c:181
#define SHORTINT
Definition: vsnprintf.c:535
const char *(* vextra)()
Definition: vsnprintf.c:182
#define BSD__sferror(p)
Definition: vsnprintf.c:207
#define bp()
Definition: vm_debug.h:25
#define COPY(n)
#define __SRW
Definition: vsnprintf.c:191
size_t iov_len
Definition: vsnprintf.c:228