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