Add snprintf and vsnprintf.
[dragonfly.git] / lib / libstand / printf.c
1 /*-
2  * Copyright (c) 1986, 1988, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)subr_prf.c  8.3 (Berkeley) 1/21/94
39  * $FreeBSD: src/lib/libstand/printf.c,v 1.4 1999/12/27 08:45:14 peter Exp $
40  * $DragonFly: src/lib/libstand/printf.c,v 1.5 2005/04/18 07:55:09 joerg Exp $
41  */
42
43 /*
44  * Standaloneified version of the FreeBSD kernel printf family.
45  */
46
47 #include <sys/types.h>
48 #include <string.h>
49 #include "stand.h"
50
51 /*
52  * Note that stdarg.h and the ANSI style va_start macro is used for both
53  * ANSI and traditional C compilers.
54  */
55 #include <stdarg.h>
56
57 struct snprintf_arg {
58         char    *buf;
59         size_t  remain;
60 };
61
62 static char     *ksprintn(u_long, int, int *);
63 static int      kvprintf(const char *, void (*)(int, void *), void *, int,
64                          va_list);
65 static void     putchar_wrapper(int, void *);
66 static void     snprintf_func(int, void *);
67
68 static void
69 putchar_wrapper(int ch, void *arg __unused)
70 {
71         putchar(ch);
72 }
73
74 int
75 printf(const char *fmt, ...)
76 {
77         va_list ap;
78         int retval;
79
80         va_start(ap, fmt);
81         retval = kvprintf(fmt, putchar_wrapper, NULL, 10, ap);
82         va_end(ap);
83         return retval;
84 }
85
86 void
87 vprintf(const char *fmt, va_list ap)
88 {
89
90         kvprintf(fmt, putchar_wrapper, NULL, 10, ap);
91 }
92
93 int
94 sprintf(char *buf, const char *cfmt, ...)
95 {
96         int retval;
97         va_list ap;
98
99         va_start(ap, cfmt);
100         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
101         buf[retval] = '\0';
102         va_end(ap);
103         return retval;
104 }
105
106 void
107 vsprintf(char *buf, const char *cfmt, va_list ap)
108 {
109         int     retval;
110         
111         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
112         buf[retval] = '\0';
113 }
114
115 int
116 snprintf(char *buf, size_t size, const char *cfmt, ...)
117 {
118         int retval;
119         va_list ap;
120
121         va_start(ap, cfmt);
122         retval = vsnprintf(buf, size, cfmt, ap);
123         __va_end(ap);
124         return(retval);
125 }
126
127 int
128 vsnprintf(char *buf, size_t size, const char *cfmt, va_list ap)
129 {
130         struct snprintf_arg info;
131         int retval;
132
133         info.buf = buf;
134         info.remain = size;
135         retval = kvprintf(cfmt, snprintf_func, &info, 10, ap);
136         if (info.remain >= 1)
137                 *info.buf++ = '\0';
138         return(retval);
139 }
140
141 static void
142 snprintf_func(int ch, void *arg)
143 {
144         struct snprintf_arg * const info = arg;
145
146         if (info->remain >= 2) {
147                 *info->buf++ = ch;
148                 info->remain--;
149         }
150 }
151
152 /*
153  * Put a number (base <= 16) in a buffer in reverse order; return an
154  * optional length and a pointer to the NULL terminated (preceded?)
155  * buffer.
156  */
157 static char *
158 ksprintn(ul, base, lenp)
159         u_long ul;
160         int base, *lenp;
161 {                                       /* A long in base 8, plus NULL. */
162         static char buf[sizeof(long) * NBBY / 3 + 2];
163         char *p;
164
165         p = buf;
166         do {
167                 *++p = hex2ascii(ul % base);
168         } while (ul /= base);
169         if (lenp)
170                 *lenp = p - buf;
171         return (p);
172 }
173
174 /*
175  * Scaled down version of printf(3).
176  *
177  * Two additional formats:
178  *
179  * The format %b is supported to decode error registers.
180  * Its usage is:
181  *
182  *      printf("reg=%b\n", regval, "<base><arg>*");
183  *
184  * where <base> is the output base expressed as a control character, e.g.
185  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
186  * the first of which gives the bit number to be inspected (origin 1), and
187  * the next characters (up to a control character, i.e. a character <= 32),
188  * give the name of the register.  Thus:
189  *
190  *      kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
191  *
192  * would produce output:
193  *
194  *      reg=3<BITTWO,BITONE>
195  *
196  * XXX:  %D  -- Hexdump, takes pointer and separator string:
197  *              ("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
198  *              ("%*D", len, ptr, " " -> XX XX XX XX ...
199  */
200 static int
201 kvprintf(char const *fmt, void (*func)(int, void *), void *arg, int radix,
202          va_list ap)
203 {
204 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc, arg); else *d++ = cc; retval++; }
205         char *p, *q, *d;
206         u_char *up;
207         int ch, n;
208         u_long ul;
209         int base, lflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
210         int dwidth;
211         char padc;
212         int retval = 0;
213
214         if (!func)
215                 d = (char *) arg;
216         else
217                 d = NULL;
218
219         if (fmt == NULL)
220                 fmt = "(fmt null)\n";
221
222         if (radix < 2 || radix > 36)
223                 radix = 10;
224
225         for (;;) {
226                 padc = ' ';
227                 width = 0;
228                 while ((ch = (u_char)*fmt++) != '%') {
229                         if (ch == '\0') 
230                                 return retval;
231                         PCHAR(ch);
232                 }
233                 lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
234                 sign = 0; dot = 0; dwidth = 0;
235 reswitch:       switch (ch = (u_char)*fmt++) {
236                 case '.':
237                         dot = 1;
238                         goto reswitch;
239                 case '#':
240                         sharpflag = 1;
241                         goto reswitch;
242                 case '+':
243                         sign = 1;
244                         goto reswitch;
245                 case '-':
246                         ladjust = 1;
247                         goto reswitch;
248                 case '%':
249                         PCHAR(ch);
250                         break;
251                 case '*':
252                         if (!dot) {
253                                 width = va_arg(ap, int);
254                                 if (width < 0) {
255                                         ladjust = !ladjust;
256                                         width = -width;
257                                 }
258                         } else {
259                                 dwidth = va_arg(ap, int);
260                         }
261                         goto reswitch;
262                 case '0':
263                         if (!dot) {
264                                 padc = '0';
265                                 goto reswitch;
266                         }
267                 case '1': case '2': case '3': case '4':
268                 case '5': case '6': case '7': case '8': case '9':
269                                 for (n = 0;; ++fmt) {
270                                         n = n * 10 + ch - '0';
271                                         ch = *fmt;
272                                         if (ch < '0' || ch > '9')
273                                                 break;
274                                 }
275                         if (dot)
276                                 dwidth = n;
277                         else
278                                 width = n;
279                         goto reswitch;
280                 case 'b':
281                         ul = va_arg(ap, int);
282                         p = va_arg(ap, char *);
283                         for (q = ksprintn(ul, *p++, NULL); *q;)
284                                 PCHAR(*q--);
285
286                         if (!ul)
287                                 break;
288
289                         for (tmp = 0; *p;) {
290                                 n = *p++;
291                                 if (ul & (1 << (n - 1))) {
292                                         PCHAR(tmp ? ',' : '<');
293                                         for (; (n = *p) > ' '; ++p)
294                                                 PCHAR(n);
295                                         tmp = 1;
296                                 } else
297                                         for (; *p > ' '; ++p)
298                                                 continue;
299                         }
300                         if (tmp)
301                                 PCHAR('>');
302                         break;
303                 case 'c':
304                         PCHAR(va_arg(ap, int));
305                         break;
306                 case 'D':
307                         up = va_arg(ap, u_char *);
308                         p = va_arg(ap, char *);
309                         if (!width)
310                                 width = 16;
311                         while(width--) {
312                                 PCHAR(hex2ascii(*up >> 4));
313                                 PCHAR(hex2ascii(*up & 0x0f));
314                                 up++;
315                                 if (width)
316                                         for (q=p;*q;q++)
317                                                 PCHAR(*q);
318                         }
319                         break;
320                 case 'd':
321                         ul = lflag ? va_arg(ap, long) : va_arg(ap, int);
322                         sign = 1;
323                         base = 10;
324                         goto number;
325                 case 'l':
326                         lflag = 1;
327                         goto reswitch;
328                 case 'n':
329                         ul = lflag ? va_arg(ap, u_long) : va_arg(ap, u_int);
330                         base = radix;
331                         goto number;
332                 case 'o':
333                         ul = lflag ? va_arg(ap, u_long) : va_arg(ap, u_int);
334                         base = 8;
335                         goto number;
336                 case 'p':
337                         ul = (u_long)va_arg(ap, void *);
338                         base = 16;
339                         sharpflag = 1;
340                         goto number;
341                 case 's':
342                         p = va_arg(ap, char *);
343                         if (p == NULL)
344                                 p = "(null)";
345                         if (!dot)
346                                 n = strlen (p);
347                         else
348                                 for (n = 0; n < dwidth && p[n]; n++)
349                                         continue;
350
351                         width -= n;
352
353                         if (!ladjust && width > 0)
354                                 while (width--)
355                                         PCHAR(padc);
356                         while (n--)
357                                 PCHAR(*p++);
358                         if (ladjust && width > 0)
359                                 while (width--)
360                                         PCHAR(padc);
361                         break;
362                 case 'u':
363                         ul = lflag ? va_arg(ap, u_long) : va_arg(ap, u_int);
364                         base = 10;
365                         goto number;
366                 case 'x':
367                         ul = lflag ? va_arg(ap, u_long) : va_arg(ap, u_int);
368                         base = 16;
369 number:                 if (sign && (long)ul < 0L) {
370                                 neg = 1;
371                                 ul = -(long)ul;
372                         }
373                         p = ksprintn(ul, base, &tmp);
374                         if (sharpflag && ul != 0) {
375                                 if (base == 8)
376                                         tmp++;
377                                 else if (base == 16)
378                                         tmp += 2;
379                         }
380                         if (neg)
381                                 tmp++;
382
383                         if (!ladjust && width && (width -= tmp) > 0)
384                                 while (width--)
385                                         PCHAR(padc);
386                         if (neg)
387                                 PCHAR('-');
388                         if (sharpflag && ul != 0) {
389                                 if (base == 8) {
390                                         PCHAR('0');
391                                 } else if (base == 16) {
392                                         PCHAR('0');
393                                         PCHAR('x');
394                                 }
395                         }
396
397                         while (*p)
398                                 PCHAR(*p--);
399
400                         if (ladjust && width && (width -= tmp) > 0)
401                                 while (width--)
402                                         PCHAR(padc);
403
404                         break;
405                 default:
406                         PCHAR('%');
407                         if (lflag)
408                                 PCHAR('l');
409                         PCHAR(ch);
410                         break;
411                 }
412         }
413 #undef PCHAR
414 }
415