r18029: More C++ stuff
[Samba/nascimento.git] / source / lib / snprintf.c
blob1cede3b27c9b1377589771f4a29c3933e7b5e92f
1 /*
2 * NOTE: If you change this file, please merge it into rsync, samba, etc.
3 */
5 /*
6 * Copyright Patrick Powell 1995
7 * This code is based on code written by Patrick Powell (papowell@astart.com)
8 * It may be used for any purpose as long as this notice remains intact
9 * on all source code distributions
12 /**************************************************************
13 * Original:
14 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
15 * A bombproof version of doprnt (dopr) included.
16 * Sigh. This sort of thing is always nasty do deal with. Note that
17 * the version here does not include floating point...
19 * snprintf() is used instead of sprintf() as it does limit checks
20 * for string length. This covers a nasty loophole.
22 * The other functions are there to prevent NULL pointers from
23 * causing nast effects.
25 * More Recently:
26 * Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
27 * This was ugly. It is still ugly. I opted out of floating point
28 * numbers, but the formatter understands just about everything
29 * from the normal C string format, at least as far as I can tell from
30 * the Solaris 2.5 printf(3S) man page.
32 * Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
33 * Ok, added some minimal floating point support, which means this
34 * probably requires libm on most operating systems. Don't yet
35 * support the exponent (e,E) and sigfig (g,G). Also, fmtint()
36 * was pretty badly broken, it just wasn't being exercised in ways
37 * which showed it, so that's been fixed. Also, formated the code
38 * to mutt conventions, and removed dead code left over from the
39 * original. Also, there is now a builtin-test, just compile with:
40 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
41 * and run snprintf for results.
43 * Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
44 * The PGP code was using unsigned hexadecimal formats.
45 * Unfortunately, unsigned formats simply didn't work.
47 * Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
48 * The original code assumed that both snprintf() and vsnprintf() were
49 * missing. Some systems only have snprintf() but not vsnprintf(), so
50 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
52 * Andrew Tridgell (tridge@samba.org) Oct 1998
53 * fixed handling of %.0f
54 * added test for HAVE_LONG_DOUBLE
56 * tridge@samba.org, idra@samba.org, April 2001
57 * got rid of fcvt code (twas buggy and made testing harder)
58 * added C99 semantics
60 * date: 2002/12/19 19:56:31; author: herb; state: Exp; lines: +2 -0
61 * actually print args for %g and %e
63 * date: 2002/06/03 13:37:52; author: jmcd; state: Exp; lines: +8 -0
64 * Since includes.h isn't included here, VA_COPY has to be defined here. I don't
65 * see any include file that is guaranteed to be here, so I'm defining it
66 * locally. Fixes AIX and Solaris builds.
68 * date: 2002/06/03 03:07:24; author: tridge; state: Exp; lines: +5 -13
69 * put the ifdef for HAVE_VA_COPY in one place rather than in lots of
70 * functions
72 * date: 2002/05/17 14:51:22; author: jmcd; state: Exp; lines: +21 -4
73 * Fix usage of va_list passed as an arg. Use __va_copy before using it
74 * when it exists.
76 * date: 2002/04/16 22:38:04; author: idra; state: Exp; lines: +20 -14
77 * Fix incorrect zpadlen handling in fmtfp.
78 * Thanks to Ollie Oldham <ollie.oldham@metro-optix.com> for spotting it.
79 * few mods to make it easier to compile the tests.
80 * addedd the "Ollie" test to the floating point ones.
82 * Martin Pool (mbp@samba.org) April 2003
83 * Remove NO_CONFIG_H so that the test case can be built within a source
84 * tree with less trouble.
85 * Remove unnecessary SAFE_FREE() definition.
87 * Martin Pool (mbp@samba.org) May 2003
88 * Put in a prototype for dummy_snprintf() to quiet compiler warnings.
90 * Move #endif to make sure VA_COPY, LDOUBLE, etc are defined even
91 * if the C library has some snprintf functions already.
93 * Darren Tucker (dtucker@zip.com.au) 2005
94 * Fix bug allowing read overruns of the source string with "%.*s"
95 * Usually harmless unless the read runs outside the process' allocation
96 * (eg if your malloc does guard pages) in which case it will segfault.
97 * From OpenSSH. Also added test for same.
99 * Simo Sorce (idra@samba.org) Jan 2006
101 * Add support for position independent parameters
102 * fix fmtstr now it conforms to sprintf wrt min.max
104 **************************************************************/
106 #ifndef NO_CONFIG_H
107 #include "config.h"
108 #else
109 #define NULL 0
110 #endif
112 #ifdef TEST_SNPRINTF /* need math library headers for testing */
114 /* In test mode, we pretend that this system doesn't have any snprintf
115 * functions, regardless of what config.h says. */
116 # undef HAVE_SNPRINTF
117 # undef HAVE_VSNPRINTF
118 # undef HAVE_C99_VSNPRINTF
119 # undef HAVE_ASPRINTF
120 # undef HAVE_VASPRINTF
121 # include <math.h>
122 #endif /* TEST_SNPRINTF */
124 #ifdef HAVE_STRING_H
125 #include <string.h>
126 #endif
128 #ifdef HAVE_STRINGS_H
129 #include <strings.h>
130 #endif
131 #ifdef HAVE_CTYPE_H
132 #include <ctype.h>
133 #endif
134 #include <sys/types.h>
135 #include <stdarg.h>
136 #ifdef HAVE_STDLIB_H
137 #include <stdlib.h>
138 #endif
140 #if defined(HAVE_SNPRINTF) && defined(HAVE_VSNPRINTF) && defined(HAVE_C99_VSNPRINTF)
141 /* only include stdio.h if we are not re-defining snprintf or vsnprintf */
142 #include <stdio.h>
143 /* make the compiler happy with an empty file */
144 void dummy_snprintf(void);
145 void dummy_snprintf(void) {}
146 #endif /* HAVE_SNPRINTF, etc */
148 #ifdef HAVE_LONG_DOUBLE
149 #define LDOUBLE long double
150 #else
151 #define LDOUBLE double
152 #endif
154 #ifdef HAVE_LONG_LONG
155 #define LLONG long long
156 #else
157 #define LLONG long
158 #endif
160 #ifndef VA_COPY
161 #ifdef HAVE_VA_COPY
162 #define VA_COPY(dest, src) va_copy(dest, src)
163 #else
164 #ifdef HAVE___VA_COPY
165 #define VA_COPY(dest, src) __va_copy(dest, src)
166 #else
167 #define VA_COPY(dest, src) (dest) = (src)
168 #endif
169 #endif
172 * dopr(): poor man's version of doprintf
175 /* format read states */
176 #define DP_S_DEFAULT 0
177 #define DP_S_FLAGS 1
178 #define DP_S_MIN 2
179 #define DP_S_DOT 3
180 #define DP_S_MAX 4
181 #define DP_S_MOD 5
182 #define DP_S_CONV 6
183 #define DP_S_DONE 7
185 /* format flags - Bits */
186 #define DP_F_MINUS (1 << 0)
187 #define DP_F_PLUS (1 << 1)
188 #define DP_F_SPACE (1 << 2)
189 #define DP_F_NUM (1 << 3)
190 #define DP_F_ZERO (1 << 4)
191 #define DP_F_UP (1 << 5)
192 #define DP_F_UNSIGNED (1 << 6)
194 /* Conversion Flags */
195 #define DP_C_CHAR 1
196 #define DP_C_SHORT 2
197 #define DP_C_LONG 3
198 #define DP_C_LDOUBLE 4
199 #define DP_C_LLONG 5
201 /* Chunk types */
202 #define CNK_FMT_STR 0
203 #define CNK_INT 1
204 #define CNK_OCTAL 2
205 #define CNK_UINT 3
206 #define CNK_HEX 4
207 #define CNK_FLOAT 5
208 #define CNK_CHAR 6
209 #define CNK_STRING 7
210 #define CNK_PTR 8
211 #define CNK_NUM 9
212 #define CNK_PRCNT 10
214 #define char_to_int(p) ((p)- '0')
215 #ifndef MAX
216 #define MAX(p,q) (((p) >= (q)) ? (p) : (q))
217 #endif
219 /* yes this really must be a ||. Don't muck with this (tridge) */
220 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
222 struct pr_chunk {
223 int type; /* chunk type */
224 int num; /* parameter number */
225 int min;
226 int max;
227 int flags;
228 int cflags;
229 int start;
230 int len;
231 LLONG value;
232 LDOUBLE fvalue;
233 char *strvalue;
234 void *pnum;
235 struct pr_chunk *min_star;
236 struct pr_chunk *max_star;
237 struct pr_chunk *next;
240 struct pr_chunk_x {
241 struct pr_chunk **chunks;
242 int num;
245 static size_t dopr(char *buffer, size_t maxlen, const char *format,
246 va_list args_in);
247 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
248 char *value, int flags, int min, int max);
249 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
250 LLONG value, int base, int min, int max, int flags);
251 static void fmtfp(char *buffer, size_t *currlen, size_t maxlen,
252 LDOUBLE fvalue, int min, int max, int flags);
253 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c);
254 static struct pr_chunk *new_chunk(void);
255 static int add_cnk_list_entry(struct pr_chunk_x **list,
256 int max_num, struct pr_chunk *chunk);
258 static size_t dopr(char *buffer, size_t maxlen, const char *format, va_list args_in)
260 char ch;
261 int state;
262 int pflag;
263 int pnum;
264 int pfirst;
265 size_t currlen;
266 va_list args;
267 const char *base;
268 struct pr_chunk *chunks = NULL;
269 struct pr_chunk *cnk = NULL;
270 struct pr_chunk_x *clist = NULL;
271 int max_pos;
272 size_t ret = -1;
274 VA_COPY(args, args_in);
276 state = DP_S_DEFAULT;
277 pfirst = 1;
278 pflag = 0;
279 pnum = 0;
281 max_pos = 0;
282 base = format;
283 ch = *format++;
285 /* retrieve the string structure as chunks */
286 while (state != DP_S_DONE) {
287 if (ch == '\0')
288 state = DP_S_DONE;
290 switch(state) {
291 case DP_S_DEFAULT:
293 if (cnk) {
294 cnk->next = new_chunk();
295 cnk = cnk->next;
296 } else {
297 cnk = new_chunk();
299 if (!cnk) goto done;
300 if (!chunks) chunks = cnk;
302 if (ch == '%') {
303 state = DP_S_FLAGS;
304 ch = *format++;
305 } else {
306 cnk->type = CNK_FMT_STR;
307 cnk->start = format - base -1;
308 while ((ch != '\0') && (ch != '%')) ch = *format++;
309 cnk->len = format - base - cnk->start -1;
311 break;
312 case DP_S_FLAGS:
313 switch (ch) {
314 case '-':
315 cnk->flags |= DP_F_MINUS;
316 ch = *format++;
317 break;
318 case '+':
319 cnk->flags |= DP_F_PLUS;
320 ch = *format++;
321 break;
322 case ' ':
323 cnk->flags |= DP_F_SPACE;
324 ch = *format++;
325 break;
326 case '#':
327 cnk->flags |= DP_F_NUM;
328 ch = *format++;
329 break;
330 case '0':
331 cnk->flags |= DP_F_ZERO;
332 ch = *format++;
333 break;
334 case 'I':
335 /* internationalization not supported yet */
336 ch = *format++;
337 break;
338 default:
339 state = DP_S_MIN;
340 break;
342 break;
343 case DP_S_MIN:
344 if (isdigit((unsigned char)ch)) {
345 cnk->min = 10 * cnk->min + char_to_int (ch);
346 ch = *format++;
347 } else if (ch == '$') {
348 if (!pfirst && !pflag) {
349 /* parameters must be all positioned or none */
350 goto done;
352 if (pfirst) {
353 pfirst = 0;
354 pflag = 1;
356 if (cnk->min == 0) /* what ?? */
357 goto done;
358 cnk->num = cnk->min;
359 cnk->min = 0;
360 ch = *format++;
361 } else if (ch == '*') {
362 if (pfirst) pfirst = 0;
363 cnk->min_star = new_chunk();
364 if (!cnk->min_star) /* out of memory :-( */
365 goto done;
366 cnk->min_star->type = CNK_INT;
367 if (pflag) {
368 int num;
369 ch = *format++;
370 if (!isdigit((unsigned char)ch)) {
371 /* parameters must be all positioned or none */
372 goto done;
374 for (num = 0; isdigit((unsigned char)ch); ch = *format++) {
375 num = 10 * num + char_to_int(ch);
377 cnk->min_star->num = num;
378 if (ch != '$') /* what ?? */
379 goto done;
380 } else {
381 cnk->min_star->num = ++pnum;
383 max_pos = add_cnk_list_entry(&clist, max_pos, cnk->min_star);
384 if (max_pos == 0) /* out of memory :-( */
385 goto done;
386 ch = *format++;
387 state = DP_S_DOT;
388 } else {
389 if (pfirst) pfirst = 0;
390 state = DP_S_DOT;
392 break;
393 case DP_S_DOT:
394 if (ch == '.') {
395 state = DP_S_MAX;
396 ch = *format++;
397 } else {
398 state = DP_S_MOD;
400 break;
401 case DP_S_MAX:
402 if (isdigit((unsigned char)ch)) {
403 if (cnk->max < 0)
404 cnk->max = 0;
405 cnk->max = 10 * cnk->max + char_to_int (ch);
406 ch = *format++;
407 } else if (ch == '$') {
408 if (!pfirst && !pflag) {
409 /* parameters must be all positioned or none */
410 goto done;
412 if (cnk->max <= 0) /* what ?? */
413 goto done;
414 cnk->num = cnk->max;
415 cnk->max = -1;
416 ch = *format++;
417 } else if (ch == '*') {
418 cnk->max_star = new_chunk();
419 if (!cnk->max_star) /* out of memory :-( */
420 goto done;
421 cnk->max_star->type = CNK_INT;
422 if (pflag) {
423 int num;
424 ch = *format++;
425 if (!isdigit((unsigned char)ch)) {
426 /* parameters must be all positioned or none */
427 goto done;
429 for (num = 0; isdigit((unsigned char)ch); ch = *format++) {
430 num = 10 * num + char_to_int(ch);
432 cnk->max_star->num = num;
433 if (ch != '$') /* what ?? */
434 goto done;
435 } else {
436 cnk->max_star->num = ++pnum;
438 max_pos = add_cnk_list_entry(&clist, max_pos, cnk->max_star);
439 if (max_pos == 0) /* out of memory :-( */
440 goto done;
442 ch = *format++;
443 state = DP_S_MOD;
444 } else {
445 state = DP_S_MOD;
447 break;
448 case DP_S_MOD:
449 switch (ch) {
450 case 'h':
451 cnk->cflags = DP_C_SHORT;
452 ch = *format++;
453 if (ch == 'h') {
454 cnk->cflags = DP_C_CHAR;
455 ch = *format++;
457 break;
458 case 'l':
459 cnk->cflags = DP_C_LONG;
460 ch = *format++;
461 if (ch == 'l') { /* It's a long long */
462 cnk->cflags = DP_C_LLONG;
463 ch = *format++;
465 break;
466 case 'L':
467 cnk->cflags = DP_C_LDOUBLE;
468 ch = *format++;
469 break;
470 default:
471 break;
473 state = DP_S_CONV;
474 break;
475 case DP_S_CONV:
476 if (cnk->num == 0) cnk->num = ++pnum;
477 max_pos = add_cnk_list_entry(&clist, max_pos, cnk);
478 if (max_pos == 0) /* out of memory :-( */
479 goto done;
481 switch (ch) {
482 case 'd':
483 case 'i':
484 cnk->type = CNK_INT;
485 break;
486 case 'o':
487 cnk->type = CNK_OCTAL;
488 cnk->flags |= DP_F_UNSIGNED;
489 break;
490 case 'u':
491 cnk->type = CNK_UINT;
492 cnk->flags |= DP_F_UNSIGNED;
493 break;
494 case 'X':
495 cnk->flags |= DP_F_UP;
496 case 'x':
497 cnk->type = CNK_HEX;
498 cnk->flags |= DP_F_UNSIGNED;
499 break;
500 case 'A':
501 /* hex float not supported yet */
502 case 'E':
503 case 'G':
504 case 'F':
505 cnk->flags |= DP_F_UP;
506 case 'a':
507 /* hex float not supported yet */
508 case 'e':
509 case 'f':
510 case 'g':
511 cnk->type = CNK_FLOAT;
512 break;
513 case 'c':
514 cnk->type = CNK_CHAR;
515 break;
516 case 's':
517 cnk->type = CNK_STRING;
518 break;
519 case 'p':
520 cnk->type = CNK_PTR;
521 break;
522 case 'n':
523 cnk->type = CNK_NUM;
524 break;
525 case '%':
526 cnk->type = CNK_PRCNT;
527 break;
528 default:
529 /* Unknown, bail out*/
530 goto done;
532 ch = *format++;
533 state = DP_S_DEFAULT;
534 break;
535 case DP_S_DONE:
536 break;
537 default:
538 /* hmm? */
539 break; /* some picky compilers need this */
543 /* retieve the format arguments */
544 for (pnum = 0; pnum < max_pos; pnum++) {
545 int i;
547 if (clist[pnum].num == 0) {
548 /* ignoring a parameter should not be permitted
549 * all parameters must be matched at least once
550 * BUT seem some system ignore this rule ...
551 * at least my glibc based system does --SSS
553 #ifdef DEBUG_SNPRINTF
554 printf("parameter at position %d not used\n", pnum+1);
555 #endif
556 /* eat the parameter */
557 va_arg (args, int);
558 continue;
560 for (i = 1; i < clist[pnum].num; i++) {
561 if (clist[pnum].chunks[0]->type != clist[pnum].chunks[i]->type) {
562 /* nooo noo no!
563 * all the references to a parameter
564 * must be of the same type
566 goto done;
569 cnk = clist[pnum].chunks[0];
570 switch (cnk->type) {
571 case CNK_INT:
572 if (cnk->cflags == DP_C_SHORT)
573 cnk->value = va_arg (args, int);
574 else if (cnk->cflags == DP_C_LONG)
575 cnk->value = va_arg (args, long int);
576 else if (cnk->cflags == DP_C_LLONG)
577 cnk->value = va_arg (args, LLONG);
578 else
579 cnk->value = va_arg (args, int);
581 for (i = 1; i < clist[pnum].num; i++) {
582 clist[pnum].chunks[i]->value = cnk->value;
584 break;
586 case CNK_OCTAL:
587 case CNK_UINT:
588 case CNK_HEX:
589 if (cnk->cflags == DP_C_SHORT)
590 cnk->value = va_arg (args, unsigned int);
591 else if (cnk->cflags == DP_C_LONG)
592 cnk->value = (unsigned long int)va_arg (args, unsigned long int);
593 else if (cnk->cflags == DP_C_LLONG)
594 cnk->value = (LLONG)va_arg (args, unsigned LLONG);
595 else
596 cnk->value = (unsigned int)va_arg (args, unsigned int);
598 for (i = 1; i < clist[pnum].num; i++) {
599 clist[pnum].chunks[i]->value = cnk->value;
601 break;
603 case CNK_FLOAT:
604 if (cnk->cflags == DP_C_LDOUBLE)
605 cnk->fvalue = va_arg (args, LDOUBLE);
606 else
607 cnk->fvalue = va_arg (args, double);
609 for (i = 1; i < clist[pnum].num; i++) {
610 clist[pnum].chunks[i]->fvalue = cnk->fvalue;
612 break;
614 case CNK_CHAR:
615 cnk->value = va_arg (args, int);
617 for (i = 1; i < clist[pnum].num; i++) {
618 clist[pnum].chunks[i]->value = cnk->value;
620 break;
622 case CNK_STRING:
623 cnk->strvalue = va_arg (args, char *);
624 if (!cnk->strvalue) cnk->strvalue = "(NULL)";
626 for (i = 1; i < clist[pnum].num; i++) {
627 clist[pnum].chunks[i]->strvalue = cnk->strvalue;
629 break;
631 case CNK_PTR:
632 cnk->strvalue = (char *)va_arg (args, void *);
633 for (i = 1; i < clist[pnum].num; i++) {
634 clist[pnum].chunks[i]->strvalue = cnk->strvalue;
636 break;
638 case CNK_NUM:
639 if (cnk->cflags == DP_C_CHAR)
640 cnk->pnum = va_arg (args, char *);
641 else if (cnk->cflags == DP_C_SHORT)
642 cnk->pnum = va_arg (args, short int *);
643 else if (cnk->cflags == DP_C_LONG)
644 cnk->pnum = va_arg (args, long int *);
645 else if (cnk->cflags == DP_C_LLONG)
646 cnk->pnum = va_arg (args, LLONG *);
647 else
648 cnk->pnum = va_arg (args, int *);
650 for (i = 1; i < clist[pnum].num; i++) {
651 clist[pnum].chunks[i]->pnum = cnk->pnum;
653 break;
655 case CNK_PRCNT:
656 break;
658 default:
659 /* what ?? */
660 goto done;
663 /* print out the actual string from chunks */
664 currlen = 0;
665 cnk = chunks;
666 while (cnk) {
667 int len, min, max;
669 if (cnk->min_star) min = cnk->min_star->value;
670 else min = cnk->min;
671 if (cnk->max_star) max = cnk->max_star->value;
672 else max = cnk->max;
674 switch (cnk->type) {
676 case CNK_FMT_STR:
677 if (maxlen != 0 && maxlen > currlen) {
678 if (maxlen > (currlen + cnk->len)) len = cnk->len;
679 else len = maxlen - currlen;
681 memcpy(&(buffer[currlen]), &(base[cnk->start]), len);
683 currlen += cnk->len;
685 break;
687 case CNK_INT:
688 case CNK_UINT:
689 fmtint (buffer, &currlen, maxlen, cnk->value, 10, min, max, cnk->flags);
690 break;
692 case CNK_OCTAL:
693 fmtint (buffer, &currlen, maxlen, cnk->value, 8, min, max, cnk->flags);
694 break;
696 case CNK_HEX:
697 fmtint (buffer, &currlen, maxlen, cnk->value, 16, min, max, cnk->flags);
698 break;
700 case CNK_FLOAT:
701 fmtfp (buffer, &currlen, maxlen, cnk->fvalue, min, max, cnk->flags);
702 break;
704 case CNK_CHAR:
705 dopr_outch (buffer, &currlen, maxlen, cnk->value);
706 break;
708 case CNK_STRING:
709 if (max == -1) {
710 max = strlen(cnk->strvalue);
712 fmtstr (buffer, &currlen, maxlen, cnk->strvalue, cnk->flags, min, max);
713 break;
715 case CNK_PTR:
716 fmtint (buffer, &currlen, maxlen, (long)(cnk->strvalue), 16, min, max, cnk->flags);
717 break;
719 case CNK_NUM:
720 if (cnk->cflags == DP_C_CHAR)
721 *((char *)(cnk->pnum)) = (char)currlen;
722 else if (cnk->cflags == DP_C_SHORT)
723 *((short int *)(cnk->pnum)) = (short int)currlen;
724 else if (cnk->cflags == DP_C_LONG)
725 *((long int *)(cnk->pnum)) = (long int)currlen;
726 else if (cnk->cflags == DP_C_LLONG)
727 *((LLONG *)(cnk->pnum)) = (LLONG)currlen;
728 else
729 *((int *)(cnk->pnum)) = (int)currlen;
730 break;
732 case CNK_PRCNT:
733 dopr_outch (buffer, &currlen, maxlen, '%');
734 break;
736 default:
737 /* what ?? */
738 goto done;
740 cnk = cnk->next;
742 if (maxlen != 0) {
743 if (currlen < maxlen - 1)
744 buffer[currlen] = '\0';
745 else if (maxlen > 0)
746 buffer[maxlen - 1] = '\0';
748 ret = currlen;
750 done:
751 while (chunks) {
752 cnk = chunks->next;
753 free(chunks);
754 chunks = cnk;
756 if (clist) {
757 for (pnum = 0; pnum < max_pos; pnum++) {
758 if (clist[pnum].chunks) free(clist[pnum].chunks);
760 free(clist);
762 return ret;
765 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
766 char *value, int flags, int min, int max)
768 int padlen, strln; /* amount to pad */
769 int cnt = 0;
771 #ifdef DEBUG_SNPRINTF
772 printf("fmtstr min=%d max=%d s=[%s]\n", min, max, value);
773 #endif
774 if (value == 0) {
775 value = "<NULL>";
778 for (strln = 0; strln < max && value[strln]; ++strln); /* strlen */
779 padlen = min - strln;
780 if (padlen < 0)
781 padlen = 0;
782 if (flags & DP_F_MINUS)
783 padlen = -padlen; /* Left Justify */
785 while (padlen > 0) {
786 dopr_outch (buffer, currlen, maxlen, ' ');
787 --padlen;
789 while (*value && (cnt < max)) {
790 dopr_outch (buffer, currlen, maxlen, *value++);
791 ++cnt;
793 while (padlen < 0) {
794 dopr_outch (buffer, currlen, maxlen, ' ');
795 ++padlen;
799 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
801 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
802 LLONG value, int base, int min, int max, int flags)
804 int signvalue = 0;
805 unsigned LLONG uvalue;
806 char convert[20];
807 int place = 0;
808 int spadlen = 0; /* amount to space pad */
809 int zpadlen = 0; /* amount to zero pad */
810 int caps = 0;
812 if (max < 0)
813 max = 0;
815 uvalue = value;
817 if(!(flags & DP_F_UNSIGNED)) {
818 if( value < 0 ) {
819 signvalue = '-';
820 uvalue = -value;
821 } else {
822 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
823 signvalue = '+';
824 else if (flags & DP_F_SPACE)
825 signvalue = ' ';
829 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
831 do {
832 convert[place++] =
833 (caps? "0123456789ABCDEF":"0123456789abcdef")
834 [uvalue % (unsigned)base ];
835 uvalue = (uvalue / (unsigned)base );
836 } while(uvalue && (place < 20));
837 if (place == 20) place--;
838 convert[place] = 0;
840 zpadlen = max - place;
841 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
842 if (zpadlen < 0) zpadlen = 0;
843 if (spadlen < 0) spadlen = 0;
844 if (flags & DP_F_ZERO) {
845 zpadlen = MAX(zpadlen, spadlen);
846 spadlen = 0;
848 if (flags & DP_F_MINUS)
849 spadlen = -spadlen; /* Left Justifty */
851 #ifdef DEBUG_SNPRINTF
852 printf("zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
853 zpadlen, spadlen, min, max, place);
854 #endif
856 /* Spaces */
857 while (spadlen > 0) {
858 dopr_outch (buffer, currlen, maxlen, ' ');
859 --spadlen;
862 /* Sign */
863 if (signvalue)
864 dopr_outch (buffer, currlen, maxlen, signvalue);
866 /* Zeros */
867 if (zpadlen > 0) {
868 while (zpadlen > 0) {
869 dopr_outch (buffer, currlen, maxlen, '0');
870 --zpadlen;
874 /* Digits */
875 while (place > 0)
876 dopr_outch (buffer, currlen, maxlen, convert[--place]);
878 /* Left Justified spaces */
879 while (spadlen < 0) {
880 dopr_outch (buffer, currlen, maxlen, ' ');
881 ++spadlen;
885 static LDOUBLE abs_val(LDOUBLE value)
887 LDOUBLE result = value;
889 if (value < 0)
890 result = -value;
892 return result;
895 static LDOUBLE POW10(int exp)
897 LDOUBLE result = 1;
899 while (exp) {
900 result *= 10;
901 exp--;
904 return result;
907 static LLONG ROUND(LDOUBLE value)
909 LLONG intpart;
911 intpart = (LLONG)value;
912 value = value - intpart;
913 if (value >= 0.5) intpart++;
915 return intpart;
918 /* a replacement for modf that doesn't need the math library. Should
919 be portable, but slow */
920 static double my_modf(double x0, double *iptr)
922 int i;
923 LLONG l;
924 double x = x0;
925 double f = 1.0;
927 for (i=0;i<100;i++) {
928 l = (long)x;
929 if (l <= (x+1) && l >= (x-1)) break;
930 x *= 0.1;
931 f *= 10.0;
934 if (i == 100) {
935 /* yikes! the number is beyond what we can handle. What do we do? */
936 (*iptr) = 0;
937 return 0;
940 if (i != 0) {
941 double i2;
942 double ret;
944 ret = my_modf(x0-l*f, &i2);
945 (*iptr) = l*f + i2;
946 return ret;
949 (*iptr) = l;
950 return x - (*iptr);
954 static void fmtfp (char *buffer, size_t *currlen, size_t maxlen,
955 LDOUBLE fvalue, int min, int max, int flags)
957 int signvalue = 0;
958 double ufvalue;
959 char iconvert[311];
960 char fconvert[311];
961 int iplace = 0;
962 int fplace = 0;
963 int padlen = 0; /* amount to pad */
964 int zpadlen = 0;
965 int caps = 0;
966 int idx;
967 double intpart;
968 double fracpart;
969 double temp;
972 * AIX manpage says the default is 0, but Solaris says the default
973 * is 6, and sprintf on AIX defaults to 6
975 if (max < 0)
976 max = 6;
978 ufvalue = abs_val (fvalue);
980 if (fvalue < 0) {
981 signvalue = '-';
982 } else {
983 if (flags & DP_F_PLUS) { /* Do a sign (+/i) */
984 signvalue = '+';
985 } else {
986 if (flags & DP_F_SPACE)
987 signvalue = ' ';
991 #if 0
992 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
993 #endif
995 #if 0
996 if (max == 0) ufvalue += 0.5; /* if max = 0 we must round */
997 #endif
1000 * Sorry, we only support 9 digits past the decimal because of our
1001 * conversion method
1003 if (max > 9)
1004 max = 9;
1006 /* We "cheat" by converting the fractional part to integer by
1007 * multiplying by a factor of 10
1010 temp = ufvalue;
1011 my_modf(temp, &intpart);
1013 fracpart = ROUND((POW10(max)) * (ufvalue - intpart));
1015 if (fracpart >= POW10(max)) {
1016 intpart++;
1017 fracpart -= POW10(max);
1021 /* Convert integer part */
1022 do {
1023 temp = intpart*0.1;
1024 my_modf(temp, &intpart);
1025 idx = (int) ((temp -intpart +0.05)* 10.0);
1026 /* idx = (int) (((double)(temp*0.1) -intpart +0.05) *10.0); */
1027 /* printf ("%llf, %f, %x\n", temp, intpart, idx); */
1028 iconvert[iplace++] =
1029 (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
1030 } while (intpart && (iplace < 311));
1031 if (iplace == 311) iplace--;
1032 iconvert[iplace] = 0;
1034 /* Convert fractional part */
1035 if (fracpart)
1037 do {
1038 temp = fracpart*0.1;
1039 my_modf(temp, &fracpart);
1040 idx = (int) ((temp -fracpart +0.05)* 10.0);
1041 /* idx = (int) ((((temp/10) -fracpart) +0.05) *10); */
1042 /* printf ("%lf, %lf, %ld\n", temp, fracpart, idx ); */
1043 fconvert[fplace++] =
1044 (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
1045 } while(fracpart && (fplace < 311));
1046 if (fplace == 311) fplace--;
1048 fconvert[fplace] = 0;
1050 /* -1 for decimal point, another -1 if we are printing a sign */
1051 padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
1052 zpadlen = max - fplace;
1053 if (zpadlen < 0) zpadlen = 0;
1054 if (padlen < 0)
1055 padlen = 0;
1056 if (flags & DP_F_MINUS)
1057 padlen = -padlen; /* Left Justifty */
1059 if ((flags & DP_F_ZERO) && (padlen > 0)) {
1060 if (signvalue) {
1061 dopr_outch (buffer, currlen, maxlen, signvalue);
1062 --padlen;
1063 signvalue = 0;
1065 while (padlen > 0) {
1066 dopr_outch (buffer, currlen, maxlen, '0');
1067 --padlen;
1070 while (padlen > 0) {
1071 dopr_outch (buffer, currlen, maxlen, ' ');
1072 --padlen;
1074 if (signvalue)
1075 dopr_outch (buffer, currlen, maxlen, signvalue);
1077 while (iplace > 0)
1078 dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
1080 #ifdef DEBUG_SNPRINTF
1081 printf("fmtfp: fplace=%d zpadlen=%d\n", fplace, zpadlen);
1082 #endif
1085 * Decimal point. This should probably use locale to find the correct
1086 * char to print out.
1088 if (max > 0) {
1089 dopr_outch (buffer, currlen, maxlen, '.');
1091 while (zpadlen > 0) {
1092 dopr_outch (buffer, currlen, maxlen, '0');
1093 --zpadlen;
1096 while (fplace > 0)
1097 dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
1100 while (padlen < 0) {
1101 dopr_outch (buffer, currlen, maxlen, ' ');
1102 ++padlen;
1106 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c)
1108 if (*currlen < maxlen) {
1109 buffer[(*currlen)] = c;
1111 (*currlen)++;
1114 static struct pr_chunk *new_chunk(void) {
1115 struct pr_chunk *new_c = (struct pr_chunk *)malloc(sizeof(struct pr_chunk));
1117 if (!new_c)
1118 return NULL;
1120 new_c->type = 0;
1121 new_c->num = 0;
1122 new_c->min = 0;
1123 new_c->min_star = NULL;
1124 new_c->max = -1;
1125 new_c->max_star = NULL;
1126 new_c->flags = 0;
1127 new_c->cflags = 0;
1128 new_c->start = 0;
1129 new_c->len = 0;
1130 new_c->value = 0;
1131 new_c->fvalue = 0;
1132 new_c->strvalue = NULL;
1133 new_c->pnum = NULL;
1134 new_c->next = NULL;
1136 return new_c;
1139 static int add_cnk_list_entry(struct pr_chunk_x **list,
1140 int max_num, struct pr_chunk *chunk) {
1141 struct pr_chunk_x *l;
1142 struct pr_chunk **c;
1143 int max;
1144 int cnum;
1145 int i, pos;
1147 if (chunk->num > max_num) {
1148 max = chunk->num;
1150 if (*list == NULL) {
1151 l = (struct pr_chunk_x *)malloc(sizeof(struct pr_chunk_x) * max);
1152 pos = 0;
1153 } else {
1154 l = (struct pr_chunk_x *)realloc(*list, sizeof(struct pr_chunk_x) * max);
1155 pos = max_num;
1157 if (l == NULL) {
1158 for (i = 0; i < max; i++) {
1159 if ((*list)[i].chunks) free((*list)[i].chunks);
1161 return 0;
1163 for (i = pos; i < max; i++) {
1164 l[i].chunks = NULL;
1165 l[i].num = 0;
1167 } else {
1168 l = *list;
1169 max = max_num;
1172 i = chunk->num - 1;
1173 cnum = l[i].num + 1;
1174 if (l[i].chunks == NULL) {
1175 c = (struct pr_chunk **)malloc(sizeof(struct pr_chunk *) * cnum);
1176 } else {
1177 c = (struct pr_chunk **)realloc(l[i].chunks, sizeof(struct pr_chunk *) * cnum);
1179 if (c == NULL) {
1180 for (i = 0; i < max; i++) {
1181 if (l[i].chunks) free(l[i].chunks);
1183 return 0;
1185 c[l[i].num] = chunk;
1186 l[i].chunks = c;
1187 l[i].num = cnum;
1189 *list = l;
1190 return max;
1193 int smb_vsnprintf (char *str, size_t count, const char *fmt, va_list args)
1195 return dopr(str, count, fmt, args);
1197 #define vsnprintf smb_vsnprintf
1198 #endif
1200 /* yes this really must be a ||. Don't muck with this (tridge)
1202 * The logic for these two is that we need our own definition if the
1203 * OS *either* has no definition of *sprintf, or if it does have one
1204 * that doesn't work properly according to the autoconf test.
1206 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
1207 int smb_snprintf(char *str,size_t count,const char *fmt,...)
1209 size_t ret;
1210 va_list ap;
1212 va_start(ap, fmt);
1213 ret = vsnprintf(str, count, fmt, ap);
1214 va_end(ap);
1215 return ret;
1217 #define snprintf smb_snprintf
1218 #endif
1220 #endif
1222 #ifndef HAVE_VASPRINTF
1223 int vasprintf(char **ptr, const char *format, va_list ap)
1225 int ret;
1226 va_list ap2;
1228 VA_COPY(ap2, ap);
1230 ret = vsnprintf(NULL, 0, format, ap2);
1231 if (ret <= 0) return ret;
1233 (*ptr) = (char *)malloc(ret+1);
1234 if (!*ptr) return -1;
1236 VA_COPY(ap2, ap);
1238 ret = vsnprintf(*ptr, ret+1, format, ap2);
1240 return ret;
1242 #endif
1245 #ifndef HAVE_ASPRINTF
1246 int asprintf(char **ptr, const char *format, ...)
1248 va_list ap;
1249 int ret;
1251 *ptr = NULL;
1252 va_start(ap, format);
1253 ret = vasprintf(ptr, format, ap);
1254 va_end(ap);
1256 return ret;
1258 #endif
1260 #ifdef TEST_SNPRINTF
1262 int sprintf(char *str,const char *fmt,...);
1264 int main (void)
1266 char buf1[1024];
1267 char buf2[1024];
1268 char *buf3;
1269 char *fp_fmt[] = {
1270 "%1.1f",
1271 "%-1.5f",
1272 "%1.5f",
1273 "%123.9f",
1274 "%10.5f",
1275 "% 10.5f",
1276 "%+22.9f",
1277 "%+4.9f",
1278 "%01.3f",
1279 "%4f",
1280 "%3.1f",
1281 "%3.2f",
1282 "%.0f",
1283 "%f",
1284 "%-8.8f",
1285 "%-9.9f",
1286 NULL
1288 double fp_nums[] = { 6442452944.1234, -1.5, 134.21, 91340.2, 341.1234, 203.9, 0.96, 0.996,
1289 0.9996, 1.996, 4.136, 5.030201, 0.00205,
1290 /* END LIST */ 0};
1291 char *int_fmt[] = {
1292 "%-1.5d",
1293 "%1.5d",
1294 "%123.9d",
1295 "%5.5d",
1296 "%10.5d",
1297 "% 10.5d",
1298 "%+22.33d",
1299 "%01.3d",
1300 "%4d",
1301 "%d",
1302 NULL
1304 long int_nums[] = { -1, 134, 91340, 341, 0203, 1234567890, 0};
1305 char *str_fmt[] = {
1306 "%10.5s",
1307 "%-10.5s",
1308 "%5.10s",
1309 "%-5.10s",
1310 "%10.1s",
1311 "%0.10s",
1312 "%10.0s",
1313 "%1.10s",
1314 "%s",
1315 "%.1s",
1316 "%.10s",
1317 "%10s",
1318 NULL
1320 char *str_vals[] = {"hello", "a", "", "a longer string", NULL};
1321 #ifdef HAVE_LONG_LONG
1322 char *ll_fmt[] = {
1323 "%llu",
1324 NULL
1326 LLONG ll_nums[] = { 134, 91340, 341, 0203, 1234567890, 128006186140000000LL, 0};
1327 #endif
1328 int x, y;
1329 int fail = 0;
1330 int num = 0;
1331 int l1, l2;
1333 printf ("Testing snprintf format codes against system sprintf...\n");
1335 for (x = 0; fp_fmt[x] ; x++) {
1336 for (y = 0; fp_nums[y] != 0 ; y++) {
1337 buf1[0] = buf2[0] = '\0';
1338 l1 = snprintf(NULL, 0, fp_fmt[x], fp_nums[y]);
1339 l2 = sprintf(buf1, fp_fmt[x], fp_nums[y]);
1340 sprintf (buf2, fp_fmt[x], fp_nums[y]);
1341 buf1[1023] = buf2[1023] = '\0';
1342 if (strcmp (buf1, buf2) || (l1 != l2)) {
1343 printf("snprintf doesn't match Format: %s\n\tsnprintf(%d) = [%s]\n\t sprintf(%d) = [%s]\n",
1344 fp_fmt[x], l1, buf1, l2, buf2);
1345 fail++;
1347 num++;
1351 for (x = 0; int_fmt[x] ; x++) {
1352 for (y = 0; int_nums[y] != 0 ; y++) {
1353 buf1[0] = buf2[0] = '\0';
1354 l1 = snprintf(NULL, 0, int_fmt[x], int_nums[y]);
1355 l2 = sprintf(buf1, int_fmt[x], int_nums[y]);
1356 sprintf (buf2, int_fmt[x], int_nums[y]);
1357 buf1[1023] = buf2[1023] = '\0';
1358 if (strcmp (buf1, buf2) || (l1 != l2)) {
1359 printf("snprintf doesn't match Format: %s\n\tsnprintf(%d) = [%s]\n\t sprintf(%d) = [%s]\n",
1360 int_fmt[x], l1, buf1, l2, buf2);
1361 fail++;
1363 num++;
1367 for (x = 0; str_fmt[x] ; x++) {
1368 for (y = 0; str_vals[y] != 0 ; y++) {
1369 buf1[0] = buf2[0] = '\0';
1370 l1 = snprintf(NULL, 0, str_fmt[x], str_vals[y]);
1371 l2 = sprintf(buf1, str_fmt[x], str_vals[y]);
1372 sprintf (buf2, str_fmt[x], str_vals[y]);
1373 buf1[1023] = buf2[1023] = '\0';
1374 if (strcmp (buf1, buf2) || (l1 != l2)) {
1375 printf("snprintf doesn't match Format: %s\n\tsnprintf(%d) = [%s]\n\t sprintf(%d) = [%s]\n",
1376 str_fmt[x], l1, buf1, l2, buf2);
1377 fail++;
1379 num++;
1383 #ifdef HAVE_LONG_LONG
1384 for (x = 0; ll_fmt[x] ; x++) {
1385 for (y = 0; ll_nums[y] != 0 ; y++) {
1386 buf1[0] = buf2[0] = '\0';
1387 l1 = snprintf(NULL, 0, ll_fmt[x], ll_nums[y]);
1388 l2 = sprintf(buf1, ll_fmt[x], ll_nums[y]);
1389 sprintf (buf2, ll_fmt[x], ll_nums[y]);
1390 buf1[1023] = buf2[1023] = '\0';
1391 if (strcmp (buf1, buf2) || (l1 != l2)) {
1392 printf("snprintf doesn't match Format: %s\n\tsnprintf(%d) = [%s]\n\t sprintf(%d) = [%s]\n",
1393 ll_fmt[x], l1, buf1, l2, buf2);
1394 fail++;
1396 num++;
1399 #endif
1401 #define BUFSZ 2048
1403 buf1[0] = buf2[0] = '\0';
1404 if ((buf3 = malloc(BUFSZ)) == NULL) {
1405 fail++;
1406 } else {
1407 num++;
1408 memset(buf3, 'a', BUFSZ);
1409 snprintf(buf1, sizeof(buf1), "%.*s", 1, buf3);
1410 buf1[1023] = '\0';
1411 if (strcmp(buf1, "a") != 0) {
1412 printf("length limit buf1 '%s' expected 'a'\n", buf1);
1413 fail++;
1417 buf1[0] = buf2[0] = '\0';
1418 l1 = snprintf(buf1, sizeof(buf1), "%4$*1$d %2$s %3$*1$.*1$f", 3, "pos test", 12.3456, 9);
1419 l2 = sprintf(buf2, "%4$*1$d %2$s %3$*1$.*1$f", 3, "pos test", 12.3456, 9);
1420 buf1[1023] = buf2[1023] = '\0';
1421 if (strcmp(buf1, buf2) || (l1 != l2)) {
1422 printf("snprintf doesn't match Format: %s\n\tsnprintf(%d) = [%s]\n\t sprintf(%d) = [%s]\n",
1423 "%4$*1$d %2$s %3$*1$.*1$f", l1, buf1, l2, buf2);
1424 fail++;
1427 buf1[0] = buf2[0] = '\0';
1428 l1 = snprintf(buf1, sizeof(buf1), "%4$*4$d %2$s %3$*4$.*4$f", 3, "pos test", 12.3456, 9);
1429 l2 = sprintf(buf2, "%4$*4$d %2$s %3$*4$.*4$f", 3, "pos test", 12.3456, 9);
1430 buf1[1023] = buf2[1023] = '\0';
1431 if (strcmp(buf1, buf2)) {
1432 printf("snprintf doesn't match Format: %s\n\tsnprintf(%d) = [%s]\n\t sprintf(%d) = [%s]\n",
1433 "%4$*1$d %2$s %3$*1$.*1$f", l1, buf1, l2, buf2);
1434 fail++;
1436 #if 0
1437 buf1[0] = buf2[0] = '\0';
1438 l1 = snprintf(buf1, sizeof(buf1), "%lld", (LLONG)1234567890);
1439 l2 = sprintf(buf2, "%lld", (LLONG)1234567890);
1440 buf1[1023] = buf2[1023] = '\0';
1441 if (strcmp(buf1, buf2)) {
1442 printf("snprintf doesn't match Format: %s\n\tsnprintf(%d) = [%s]\n\t sprintf(%d) = [%s]\n",
1443 "%lld", l1, buf1, l2, buf2);
1444 fail++;
1447 buf1[0] = buf2[0] = '\0';
1448 l1 = snprintf(buf1, sizeof(buf1), "%Lf", (LDOUBLE)890.1234567890123);
1449 l2 = sprintf(buf2, "%Lf", (LDOUBLE)890.1234567890123);
1450 buf1[1023] = buf2[1023] = '\0';
1451 if (strcmp(buf1, buf2)) {
1452 printf("snprintf doesn't match Format: %s\n\tsnprintf(%d) = [%s]\n\t sprintf(%d) = [%s]\n",
1453 "%Lf", l1, buf1, l2, buf2);
1454 fail++;
1456 #endif
1457 printf ("%d tests failed out of %d.\n", fail, num);
1459 printf("seeing how many digits we support\n");
1461 double v0 = 0.12345678901234567890123456789012345678901;
1462 for (x=0; x<100; x++) {
1463 double p = pow(10, x);
1464 double r = v0*p;
1465 snprintf(buf1, sizeof(buf1), "%1.1f", r);
1466 sprintf(buf2, "%1.1f", r);
1467 if (strcmp(buf1, buf2)) {
1468 printf("we seem to support %d digits\n", x-1);
1469 break;
1474 return 0;
1476 #endif /* TEST_SNPRINTF */