]> granicus.if.org Git - postgresql/blob - src/port/snprintf.c
8.4 pgindent run, with new combined Linux/FreeBSD/MinGW typedef list
[postgresql] / src / port / snprintf.c
1 /*
2  * Copyright (c) 1983, 1995, 1996 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *        notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *        notice, this list of conditions and the following disclaimer in the
13  *        documentation and/or other materials provided with the distribution.
14  * 3. Neither the name of the University nor the names of its contributors
15  *        may be used to endorse or promote products derived from this software
16  *        without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.      IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * $PostgreSQL: pgsql/src/port/snprintf.c,v 1.35 2008/03/18 01:49:44 tgl Exp $
31  */
32
33 #include "c.h"
34
35 #include <limits.h>
36 #ifndef WIN32
37 #include <sys/ioctl.h>
38 #endif
39 #include <sys/param.h>
40
41 #ifndef NL_ARGMAX
42 #define NL_ARGMAX 16
43 #endif
44
45
46 /*
47  *      SNPRINTF, VSNPRINTF and friends
48  *
49  * These versions have been grabbed off the net.  They have been
50  * cleaned up to compile properly and support for most of the Single Unix
51  * Specification has been added.  Remaining unimplemented features are:
52  *
53  * 1. No locale support: the radix character is always '.' and the '
54  * (single quote) format flag is ignored.
55  *
56  * 2. No support for the "%n" format specification.
57  *
58  * 3. No support for wide characters ("lc" and "ls" formats).
59  *
60  * 4. No support for "long double" ("Lf" and related formats).
61  *
62  * 5. Space and '#' flags are not implemented.
63  *
64  *
65  * The result values of these functions are not the same across different
66  * platforms.  This implementation is compatible with the Single Unix Spec:
67  *
68  * 1. -1 is returned only if processing is abandoned due to an invalid
69  * parameter, such as incorrect format string.  (Although not required by
70  * the spec, this happens only when no characters have yet been transmitted
71  * to the destination.)
72  *
73  * 2. For snprintf and sprintf, 0 is returned if str == NULL or count == 0;
74  * no data has been stored.
75  *
76  * 3. Otherwise, the number of bytes actually transmitted to the destination
77  * is returned (excluding the trailing '\0' for snprintf and sprintf).
78  *
79  * For snprintf with nonzero count, the result cannot be more than count-1
80  * (a trailing '\0' is always stored); it is not possible to distinguish
81  * buffer overrun from exact fit.  This is unlike some implementations that
82  * return the number of bytes that would have been needed for the complete
83  * result string.
84  */
85
86 /**************************************************************
87  * Original:
88  * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
89  * A bombproof version of doprnt (dopr) included.
90  * Sigh.  This sort of thing is always nasty do deal with.      Note that
91  * the version here does not include floating point. (now it does ... tgl)
92  **************************************************************/
93
94 /* Prevent recursion */
95 #undef  vsnprintf
96 #undef  snprintf
97 #undef  sprintf
98 #undef  vfprintf
99 #undef  fprintf
100 #undef  printf
101
102 /* Info about where the formatted output is going */
103 typedef struct
104 {
105         char       *bufptr;                     /* next buffer output position */
106         char       *bufstart;           /* first buffer element */
107         char       *bufend;                     /* last buffer element, or NULL */
108         /* bufend == NULL is for sprintf, where we assume buf is big enough */
109         FILE       *stream;                     /* eventual output destination, or NULL */
110         int                     nchars;                 /* # chars already sent to stream */
111 } PrintfTarget;
112
113 /*
114  * Info about the type and value of a formatting parameter.  Note that we
115  * don't currently support "long double", "wint_t", or "wchar_t *" data,
116  * nor the '%n' formatting code; else we'd need more types.  Also, at this
117  * level we need not worry about signed vs unsigned values.
118  */
119 typedef enum
120 {
121         ATYPE_NONE = 0,
122         ATYPE_INT,
123         ATYPE_LONG,
124         ATYPE_LONGLONG,
125         ATYPE_DOUBLE,
126         ATYPE_CHARPTR
127 } PrintfArgType;
128
129 typedef union
130 {
131         int                     i;
132         long            l;
133         int64           ll;
134         double          d;
135         char       *cptr;
136 } PrintfArgValue;
137
138
139 static void flushbuffer(PrintfTarget *target);
140 static int      dopr(PrintfTarget *target, const char *format, va_list args);
141
142
143 int
144 pg_vsnprintf(char *str, size_t count, const char *fmt, va_list args)
145 {
146         PrintfTarget target;
147
148         if (str == NULL || count == 0)
149                 return 0;
150         target.bufstart = target.bufptr = str;
151         target.bufend = str + count - 1;
152         target.stream = NULL;
153         /* target.nchars is unused in this case */
154         if (dopr(&target, fmt, args))
155         {
156                 *(target.bufptr) = '\0';
157                 errno = EINVAL;                 /* bad format */
158                 return -1;
159         }
160         *(target.bufptr) = '\0';
161         return target.bufptr - target.bufstart;
162 }
163
164 int
165 pg_snprintf(char *str, size_t count, const char *fmt,...)
166 {
167         int                     len;
168         va_list         args;
169
170         va_start(args, fmt);
171         len = pg_vsnprintf(str, count, fmt, args);
172         va_end(args);
173         return len;
174 }
175
176 static int
177 pg_vsprintf(char *str, const char *fmt, va_list args)
178 {
179         PrintfTarget target;
180
181         if (str == NULL)
182                 return 0;
183         target.bufstart = target.bufptr = str;
184         target.bufend = NULL;
185         target.stream = NULL;
186         /* target.nchars is unused in this case */
187         if (dopr(&target, fmt, args))
188         {
189                 *(target.bufptr) = '\0';
190                 errno = EINVAL;                 /* bad format */
191                 return -1;
192         }
193         *(target.bufptr) = '\0';
194         return target.bufptr - target.bufstart;
195 }
196
197 int
198 pg_sprintf(char *str, const char *fmt,...)
199 {
200         int                     len;
201         va_list         args;
202
203         va_start(args, fmt);
204         len = pg_vsprintf(str, fmt, args);
205         va_end(args);
206         return len;
207 }
208
209 int
210 pg_vfprintf(FILE *stream, const char *fmt, va_list args)
211 {
212         PrintfTarget target;
213         char            buffer[1024];   /* size is arbitrary */
214
215         if (stream == NULL)
216         {
217                 errno = EINVAL;
218                 return -1;
219         }
220         target.bufstart = target.bufptr = buffer;
221         target.bufend = buffer + sizeof(buffer) - 1;
222         target.stream = stream;
223         target.nchars = 0;
224         if (dopr(&target, fmt, args))
225         {
226                 errno = EINVAL;                 /* bad format */
227                 return -1;
228         }
229         /* dump any remaining buffer contents */
230         flushbuffer(&target);
231         return target.nchars;
232 }
233
234 int
235 pg_fprintf(FILE *stream, const char *fmt,...)
236 {
237         int                     len;
238         va_list         args;
239
240         va_start(args, fmt);
241         len = pg_vfprintf(stream, fmt, args);
242         va_end(args);
243         return len;
244 }
245
246 int
247 pg_printf(const char *fmt,...)
248 {
249         int                     len;
250         va_list         args;
251
252         va_start(args, fmt);
253         len = pg_vfprintf(stdout, fmt, args);
254         va_end(args);
255         return len;
256 }
257
258 /* call this only when stream is defined */
259 static void
260 flushbuffer(PrintfTarget *target)
261 {
262         size_t          nc = target->bufptr - target->bufstart;
263
264         if (nc > 0)
265                 target->nchars += fwrite(target->bufstart, 1, nc, target->stream);
266         target->bufptr = target->bufstart;
267 }
268
269
270 static void fmtstr(char *value, int leftjust, int minlen, int maxwidth,
271            int pointflag, PrintfTarget *target);
272 static void fmtptr(void *value, PrintfTarget *target);
273 static void fmtint(int64 value, char type, int forcesign,
274            int leftjust, int minlen, int zpad, int precision, int pointflag,
275            PrintfTarget *target);
276 static void fmtchar(int value, int leftjust, int minlen, PrintfTarget *target);
277 static void fmtfloat(double value, char type, int forcesign,
278                  int leftjust, int minlen, int zpad, int precision, int pointflag,
279                  PrintfTarget *target);
280 static void dostr(const char *str, int slen, PrintfTarget *target);
281 static void dopr_outch(int c, PrintfTarget *target);
282 static int      adjust_sign(int is_negative, int forcesign, int *signvalue);
283 static void adjust_padlen(int minlen, int vallen, int leftjust, int *padlen);
284 static void leading_pad(int zpad, int *signvalue, int *padlen,
285                         PrintfTarget *target);
286 static void trailing_pad(int *padlen, PrintfTarget *target);
287
288
289 /*
290  * dopr(): poor man's version of doprintf
291  */
292 static int
293 dopr(PrintfTarget *target, const char *format, va_list args)
294 {
295         const char *format_start = format;
296         int                     ch;
297         bool            have_dollar;
298         bool            have_non_dollar;
299         bool            have_star;
300         bool            afterstar;
301         int                     accum;
302         int                     longlongflag;
303         int                     longflag;
304         int                     pointflag;
305         int                     leftjust;
306         int                     fieldwidth;
307         int                     precision;
308         int                     zpad;
309         int                     forcesign;
310         int                     last_dollar;
311         int                     fmtpos;
312         int                     cvalue;
313         int64           numvalue;
314         double          fvalue;
315         char       *strvalue;
316         int                     i;
317         PrintfArgType argtypes[NL_ARGMAX + 1];
318         PrintfArgValue argvalues[NL_ARGMAX + 1];
319
320         /*
321          * Parse the format string to determine whether there are %n$ format
322          * specs, and identify the types and order of the format parameters.
323          */
324         have_dollar = have_non_dollar = false;
325         last_dollar = 0;
326         MemSet(argtypes, 0, sizeof(argtypes));
327
328         while ((ch = *format++) != '\0')
329         {
330                 if (ch != '%')
331                         continue;
332                 longflag = longlongflag = pointflag = 0;
333                 fmtpos = accum = 0;
334                 afterstar = false;
335 nextch1:
336                 ch = *format++;
337                 if (ch == '\0')
338                         break;                          /* illegal, but we don't complain */
339                 switch (ch)
340                 {
341                         case '-':
342                         case '+':
343                                 goto nextch1;
344                         case '0':
345                         case '1':
346                         case '2':
347                         case '3':
348                         case '4':
349                         case '5':
350                         case '6':
351                         case '7':
352                         case '8':
353                         case '9':
354                                 accum = accum * 10 + (ch - '0');
355                                 goto nextch1;
356                         case '.':
357                                 pointflag = 1;
358                                 accum = 0;
359                                 goto nextch1;
360                         case '*':
361                                 if (afterstar)
362                                         have_non_dollar = true;         /* multiple stars */
363                                 afterstar = true;
364                                 accum = 0;
365                                 goto nextch1;
366                         case '$':
367                                 have_dollar = true;
368                                 if (accum <= 0 || accum > NL_ARGMAX)
369                                         return -1;
370                                 if (afterstar)
371                                 {
372                                         if (argtypes[accum] &&
373                                                 argtypes[accum] != ATYPE_INT)
374                                                 return -1;
375                                         argtypes[accum] = ATYPE_INT;
376                                         last_dollar = Max(last_dollar, accum);
377                                         afterstar = false;
378                                 }
379                                 else
380                                         fmtpos = accum;
381                                 accum = 0;
382                                 goto nextch1;
383                         case 'l':
384                                 if (longflag)
385                                         longlongflag = 1;
386                                 else
387                                         longflag = 1;
388                                 goto nextch1;
389                         case 'h':
390                         case '\'':
391                                 /* ignore these */
392                                 goto nextch1;
393                         case 'd':
394                         case 'i':
395                         case 'o':
396                         case 'u':
397                         case 'x':
398                         case 'X':
399                                 if (fmtpos)
400                                 {
401                                         PrintfArgType atype;
402
403                                         if (longlongflag)
404                                                 atype = ATYPE_LONGLONG;
405                                         else if (longflag)
406                                                 atype = ATYPE_LONG;
407                                         else
408                                                 atype = ATYPE_INT;
409                                         if (argtypes[fmtpos] &&
410                                                 argtypes[fmtpos] != atype)
411                                                 return -1;
412                                         argtypes[fmtpos] = atype;
413                                         last_dollar = Max(last_dollar, fmtpos);
414                                 }
415                                 else
416                                         have_non_dollar = true;
417                                 break;
418                         case 'c':
419                                 if (fmtpos)
420                                 {
421                                         if (argtypes[fmtpos] &&
422                                                 argtypes[fmtpos] != ATYPE_INT)
423                                                 return -1;
424                                         argtypes[fmtpos] = ATYPE_INT;
425                                         last_dollar = Max(last_dollar, fmtpos);
426                                 }
427                                 else
428                                         have_non_dollar = true;
429                                 break;
430                         case 's':
431                         case 'p':
432                                 if (fmtpos)
433                                 {
434                                         if (argtypes[fmtpos] &&
435                                                 argtypes[fmtpos] != ATYPE_CHARPTR)
436                                                 return -1;
437                                         argtypes[fmtpos] = ATYPE_CHARPTR;
438                                         last_dollar = Max(last_dollar, fmtpos);
439                                 }
440                                 else
441                                         have_non_dollar = true;
442                                 break;
443                         case 'e':
444                         case 'E':
445                         case 'f':
446                         case 'g':
447                         case 'G':
448                                 if (fmtpos)
449                                 {
450                                         if (argtypes[fmtpos] &&
451                                                 argtypes[fmtpos] != ATYPE_DOUBLE)
452                                                 return -1;
453                                         argtypes[fmtpos] = ATYPE_DOUBLE;
454                                         last_dollar = Max(last_dollar, fmtpos);
455                                 }
456                                 else
457                                         have_non_dollar = true;
458                                 break;
459                         case '%':
460                                 break;
461                 }
462
463                 /*
464                  * If we finish the spec with afterstar still set, there's a
465                  * non-dollar star in there.
466                  */
467                 if (afterstar)
468                         have_non_dollar = true;
469         }
470
471         /* Per spec, you use either all dollar or all not. */
472         if (have_dollar && have_non_dollar)
473                 return -1;
474
475         /*
476          * In dollar mode, collect the arguments in physical order.
477          */
478         for (i = 1; i <= last_dollar; i++)
479         {
480                 switch (argtypes[i])
481                 {
482                         case ATYPE_NONE:
483                                 return -1;              /* invalid format */
484                         case ATYPE_INT:
485                                 argvalues[i].i = va_arg(args, int);
486                                 break;
487                         case ATYPE_LONG:
488                                 argvalues[i].l = va_arg(args, long);
489                                 break;
490                         case ATYPE_LONGLONG:
491                                 argvalues[i].ll = va_arg(args, int64);
492                                 break;
493                         case ATYPE_DOUBLE:
494                                 argvalues[i].d = va_arg(args, double);
495                                 break;
496                         case ATYPE_CHARPTR:
497                                 argvalues[i].cptr = va_arg(args, char *);
498                                 break;
499                 }
500         }
501
502         /*
503          * At last we can parse the format for real.
504          */
505         format = format_start;
506         while ((ch = *format++) != '\0')
507         {
508                 if (ch != '%')
509                 {
510                         dopr_outch(ch, target);
511                         continue;
512                 }
513                 fieldwidth = precision = zpad = leftjust = forcesign = 0;
514                 longflag = longlongflag = pointflag = 0;
515                 fmtpos = accum = 0;
516                 have_star = afterstar = false;
517 nextch2:
518                 ch = *format++;
519                 if (ch == '\0')
520                         break;                          /* illegal, but we don't complain */
521                 switch (ch)
522                 {
523                         case '-':
524                                 leftjust = 1;
525                                 goto nextch2;
526                         case '+':
527                                 forcesign = 1;
528                                 goto nextch2;
529                         case '0':
530                                 /* set zero padding if no nonzero digits yet */
531                                 if (accum == 0 && !pointflag)
532                                         zpad = '0';
533                                 /* FALL THRU */
534                         case '1':
535                         case '2':
536                         case '3':
537                         case '4':
538                         case '5':
539                         case '6':
540                         case '7':
541                         case '8':
542                         case '9':
543                                 accum = accum * 10 + (ch - '0');
544                                 goto nextch2;
545                         case '.':
546                                 if (have_star)
547                                         have_star = false;
548                                 else
549                                         fieldwidth = accum;
550                                 pointflag = 1;
551                                 accum = 0;
552                                 goto nextch2;
553                         case '*':
554                                 if (have_dollar)
555                                 {
556                                         /* process value after reading n$ */
557                                         afterstar = true;
558                                 }
559                                 else
560                                 {
561                                         /* fetch and process value now */
562                                         int                     starval = va_arg(args, int);
563
564                                         if (pointflag)
565                                         {
566                                                 precision = starval;
567                                                 if (precision < 0)
568                                                 {
569                                                         precision = 0;
570                                                         pointflag = 0;
571                                                 }
572                                         }
573                                         else
574                                         {
575                                                 fieldwidth = starval;
576                                                 if (fieldwidth < 0)
577                                                 {
578                                                         leftjust = 1;
579                                                         fieldwidth = -fieldwidth;
580                                                 }
581                                         }
582                                 }
583                                 have_star = true;
584                                 accum = 0;
585                                 goto nextch2;
586                         case '$':
587                                 if (afterstar)
588                                 {
589                                         /* fetch and process star value */
590                                         int                     starval = argvalues[accum].i;
591
592                                         if (pointflag)
593                                         {
594                                                 precision = starval;
595                                                 if (precision < 0)
596                                                 {
597                                                         precision = 0;
598                                                         pointflag = 0;
599                                                 }
600                                         }
601                                         else
602                                         {
603                                                 fieldwidth = starval;
604                                                 if (fieldwidth < 0)
605                                                 {
606                                                         leftjust = 1;
607                                                         fieldwidth = -fieldwidth;
608                                                 }
609                                         }
610                                         afterstar = false;
611                                 }
612                                 else
613                                         fmtpos = accum;
614                                 accum = 0;
615                                 goto nextch2;
616                         case 'l':
617                                 if (longflag)
618                                         longlongflag = 1;
619                                 else
620                                         longflag = 1;
621                                 goto nextch2;
622                         case 'h':
623                         case '\'':
624                                 /* ignore these */
625                                 goto nextch2;
626                         case 'd':
627                         case 'i':
628                                 if (!have_star)
629                                 {
630                                         if (pointflag)
631                                                 precision = accum;
632                                         else
633                                                 fieldwidth = accum;
634                                 }
635                                 if (have_dollar)
636                                 {
637                                         if (longlongflag)
638                                                 numvalue = argvalues[fmtpos].ll;
639                                         else if (longflag)
640                                                 numvalue = argvalues[fmtpos].l;
641                                         else
642                                                 numvalue = argvalues[fmtpos].i;
643                                 }
644                                 else
645                                 {
646                                         if (longlongflag)
647                                                 numvalue = va_arg(args, int64);
648                                         else if (longflag)
649                                                 numvalue = va_arg(args, long);
650                                         else
651                                                 numvalue = va_arg(args, int);
652                                 }
653                                 fmtint(numvalue, ch, forcesign, leftjust, fieldwidth, zpad,
654                                            precision, pointflag, target);
655                                 break;
656                         case 'o':
657                         case 'u':
658                         case 'x':
659                         case 'X':
660                                 if (!have_star)
661                                 {
662                                         if (pointflag)
663                                                 precision = accum;
664                                         else
665                                                 fieldwidth = accum;
666                                 }
667                                 if (have_dollar)
668                                 {
669                                         if (longlongflag)
670                                                 numvalue = (uint64) argvalues[fmtpos].ll;
671                                         else if (longflag)
672                                                 numvalue = (unsigned long) argvalues[fmtpos].l;
673                                         else
674                                                 numvalue = (unsigned int) argvalues[fmtpos].i;
675                                 }
676                                 else
677                                 {
678                                         if (longlongflag)
679                                                 numvalue = (uint64) va_arg(args, int64);
680                                         else if (longflag)
681                                                 numvalue = (unsigned long) va_arg(args, long);
682                                         else
683                                                 numvalue = (unsigned int) va_arg(args, int);
684                                 }
685                                 fmtint(numvalue, ch, forcesign, leftjust, fieldwidth, zpad,
686                                            precision, pointflag, target);
687                                 break;
688                         case 'c':
689                                 if (!have_star)
690                                 {
691                                         if (pointflag)
692                                                 precision = accum;
693                                         else
694                                                 fieldwidth = accum;
695                                 }
696                                 if (have_dollar)
697                                         cvalue = (unsigned char) argvalues[fmtpos].i;
698                                 else
699                                         cvalue = (unsigned char) va_arg(args, int);
700                                 fmtchar(cvalue, leftjust, fieldwidth, target);
701                                 break;
702                         case 's':
703                                 if (!have_star)
704                                 {
705                                         if (pointflag)
706                                                 precision = accum;
707                                         else
708                                                 fieldwidth = accum;
709                                 }
710                                 if (have_dollar)
711                                         strvalue = argvalues[fmtpos].cptr;
712                                 else
713                                         strvalue = va_arg(args, char *);
714                                 fmtstr(strvalue, leftjust, fieldwidth, precision, pointflag,
715                                            target);
716                                 break;
717                         case 'p':
718                                 /* fieldwidth/leftjust are ignored ... */
719                                 if (have_dollar)
720                                         strvalue = argvalues[fmtpos].cptr;
721                                 else
722                                         strvalue = va_arg(args, char *);
723                                 fmtptr((void *) strvalue, target);
724                                 break;
725                         case 'e':
726                         case 'E':
727                         case 'f':
728                         case 'g':
729                         case 'G':
730                                 if (!have_star)
731                                 {
732                                         if (pointflag)
733                                                 precision = accum;
734                                         else
735                                                 fieldwidth = accum;
736                                 }
737                                 if (have_dollar)
738                                         fvalue = argvalues[fmtpos].d;
739                                 else
740                                         fvalue = va_arg(args, double);
741                                 fmtfloat(fvalue, ch, forcesign, leftjust,
742                                                  fieldwidth, zpad,
743                                                  precision, pointflag,
744                                                  target);
745                                 break;
746                         case '%':
747                                 dopr_outch('%', target);
748                                 break;
749                 }
750         }
751
752         return 0;
753 }
754
755 static size_t
756 pg_strnlen(const char *str, size_t maxlen)
757 {
758         const char *p = str;
759
760         while (maxlen-- > 0 && *p)
761                 p++;
762         return p - str;
763 }
764
765 static void
766 fmtstr(char *value, int leftjust, int minlen, int maxwidth,
767            int pointflag, PrintfTarget *target)
768 {
769         int                     padlen,
770                                 vallen;                 /* amount to pad */
771
772         /*
773          * If a maxwidth (precision) is specified, we must not fetch more bytes
774          * than that.
775          */
776         if (pointflag)
777                 vallen = pg_strnlen(value, maxwidth);
778         else
779                 vallen = strlen(value);
780
781         adjust_padlen(minlen, vallen, leftjust, &padlen);
782
783         while (padlen > 0)
784         {
785                 dopr_outch(' ', target);
786                 --padlen;
787         }
788
789         dostr(value, vallen, target);
790
791         trailing_pad(&padlen, target);
792 }
793
794 static void
795 fmtptr(void *value, PrintfTarget *target)
796 {
797         int                     vallen;
798         char            convert[64];
799
800         /* we rely on regular C library's sprintf to do the basic conversion */
801         vallen = sprintf(convert, "%p", value);
802
803         dostr(convert, vallen, target);
804 }
805
806 static void
807 fmtint(int64 value, char type, int forcesign, int leftjust,
808            int minlen, int zpad, int precision, int pointflag,
809            PrintfTarget *target)
810 {
811         uint64          base;
812         int                     dosign;
813         const char *cvt = "0123456789abcdef";
814         int                     signvalue = 0;
815         char            convert[64];
816         int                     vallen = 0;
817         int                     padlen = 0;             /* amount to pad */
818         int                     zeropad;                /* extra leading zeroes */
819
820         switch (type)
821         {
822                 case 'd':
823                 case 'i':
824                         base = 10;
825                         dosign = 1;
826                         break;
827                 case 'o':
828                         base = 8;
829                         dosign = 0;
830                         break;
831                 case 'u':
832                         base = 10;
833                         dosign = 0;
834                         break;
835                 case 'x':
836                         base = 16;
837                         dosign = 0;
838                         break;
839                 case 'X':
840                         cvt = "0123456789ABCDEF";
841                         base = 16;
842                         dosign = 0;
843                         break;
844                 default:
845                         return;                         /* keep compiler quiet */
846         }
847
848         /* Handle +/- */
849         if (dosign && adjust_sign((value < 0), forcesign, &signvalue))
850                 value = -value;
851
852         /*
853          * SUS: the result of converting 0 with an explicit precision of 0 is no
854          * characters
855          */
856         if (value == 0 && pointflag && precision == 0)
857                 vallen = 0;
858         else
859         {
860                 /* make integer string */
861                 uint64          uvalue = (uint64) value;
862
863                 do
864                 {
865                         convert[vallen++] = cvt[uvalue % base];
866                         uvalue = uvalue / base;
867                 } while (uvalue);
868         }
869
870         zeropad = Max(0, precision - vallen);
871
872         adjust_padlen(minlen, vallen + zeropad, leftjust, &padlen);
873
874         leading_pad(zpad, &signvalue, &padlen, target);
875
876         while (zeropad-- > 0)
877                 dopr_outch('0', target);
878
879         while (vallen > 0)
880                 dopr_outch(convert[--vallen], target);
881
882         trailing_pad(&padlen, target);
883 }
884
885 static void
886 fmtchar(int value, int leftjust, int minlen, PrintfTarget *target)
887 {
888         int                     padlen = 0;             /* amount to pad */
889
890         adjust_padlen(minlen, 1, leftjust, &padlen);
891
892         while (padlen > 0)
893         {
894                 dopr_outch(' ', target);
895                 --padlen;
896         }
897
898         dopr_outch(value, target);
899
900         trailing_pad(&padlen, target);
901 }
902
903 static void
904 fmtfloat(double value, char type, int forcesign, int leftjust,
905                  int minlen, int zpad, int precision, int pointflag,
906                  PrintfTarget *target)
907 {
908         int                     signvalue = 0;
909         int                     vallen;
910         char            fmt[32];
911         char            convert[512];
912         int                     padlen = 0;             /* amount to pad */
913
914         /* we rely on regular C library's sprintf to do the basic conversion */
915         if (pointflag)
916                 sprintf(fmt, "%%.%d%c", precision, type);
917         else
918                 sprintf(fmt, "%%%c", type);
919
920         if (adjust_sign((value < 0), forcesign, &signvalue))
921                 value = -value;
922
923         vallen = sprintf(convert, fmt, value);
924
925         adjust_padlen(minlen, vallen, leftjust, &padlen);
926
927         leading_pad(zpad, &signvalue, &padlen, target);
928
929         dostr(convert, vallen, target);
930
931         trailing_pad(&padlen, target);
932 }
933
934 static void
935 dostr(const char *str, int slen, PrintfTarget *target)
936 {
937         while (slen > 0)
938         {
939                 int                     avail;
940
941                 if (target->bufend != NULL)
942                         avail = target->bufend - target->bufptr;
943                 else
944                         avail = slen;
945                 if (avail <= 0)
946                 {
947                         /* buffer full, can we dump to stream? */
948                         if (target->stream == NULL)
949                                 return;                 /* no, lose the data */
950                         flushbuffer(target);
951                         continue;
952                 }
953                 avail = Min(avail, slen);
954                 memmove(target->bufptr, str, avail);
955                 target->bufptr += avail;
956                 str += avail;
957                 slen -= avail;
958         }
959 }
960
961 static void
962 dopr_outch(int c, PrintfTarget *target)
963 {
964         if (target->bufend != NULL && target->bufptr >= target->bufend)
965         {
966                 /* buffer full, can we dump to stream? */
967                 if (target->stream == NULL)
968                         return;                         /* no, lose the data */
969                 flushbuffer(target);
970         }
971         *(target->bufptr++) = c;
972 }
973
974
975 static int
976 adjust_sign(int is_negative, int forcesign, int *signvalue)
977 {
978         if (is_negative)
979         {
980                 *signvalue = '-';
981                 return true;
982         }
983         else if (forcesign)
984                 *signvalue = '+';
985         return false;
986 }
987
988
989 static void
990 adjust_padlen(int minlen, int vallen, int leftjust, int *padlen)
991 {
992         *padlen = minlen - vallen;
993         if (*padlen < 0)
994                 *padlen = 0;
995         if (leftjust)
996                 *padlen = -(*padlen);
997 }
998
999
1000 static void
1001 leading_pad(int zpad, int *signvalue, int *padlen, PrintfTarget *target)
1002 {
1003         if (*padlen > 0 && zpad)
1004         {
1005                 if (*signvalue)
1006                 {
1007                         dopr_outch(*signvalue, target);
1008                         --(*padlen);
1009                         *signvalue = 0;
1010                 }
1011                 while (*padlen > 0)
1012                 {
1013                         dopr_outch(zpad, target);
1014                         --(*padlen);
1015                 }
1016         }
1017         while (*padlen > (*signvalue != 0))
1018         {
1019                 dopr_outch(' ', target);
1020                 --(*padlen);
1021         }
1022         if (*signvalue)
1023         {
1024                 dopr_outch(*signvalue, target);
1025                 if (*padlen > 0)
1026                         --(*padlen);
1027                 else if (*padlen < 0)
1028                         ++(*padlen);
1029         }
1030 }
1031
1032
1033 static void
1034 trailing_pad(int *padlen, PrintfTarget *target)
1035 {
1036         while (*padlen < 0)
1037         {
1038                 dopr_outch(' ', target);
1039                 ++(*padlen);
1040         }
1041 }