Ruby: vsnprintf.c Source File

Ruby 3.2.5p208 (2024-07-26 revision 31d0f1a2e7dbfb60731d1f05b868e1d578cda493)

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