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