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