1 /* Like vsprintf but provides a pointer to malloc'd storage, which must
2 be freed by the caller.
3 Copyright (C) 1994, 1998, 1999, 2000-2003 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
24 #include "vasprintf.h"
33 size_t global_total_width
;
37 int_vasprintf (char **result
, const char *format
, va_list *args
)
39 const char *p
= format
;
40 /* Add one to make sure that it is never zero, which might cause malloc
42 size_t total_width
= strlen (format
) + 1;
49 while (strchr ("-+ #0", *p
))
54 total_width
+= abs (va_arg (ap
, int));
57 total_width
+= strtoul (p
, (char **) &p
, 10);
64 total_width
+= abs (va_arg (ap
, int));
67 total_width
+= strtoul (p
, (char **) &p
, 10);
69 while (strchr ("hlLjtz", *p
))
71 /* Should be big enough for any format specifier except %s
83 (void) va_arg (ap
, int);
88 double arg
= va_arg (ap
, double);
89 if (arg
>= 1.0 || arg
<= -1.0)
90 /* Since an ieee double can have an exponent of 307, we'll
91 make the buffer wide enough to cover the gross case. */
99 (void) va_arg (ap
, double);
102 total_width
+= strlen (va_arg (ap
, char *));
106 (void) va_arg (ap
, char *);
113 global_total_width
= total_width
;
115 *result
= malloc (total_width
);
117 return vsprintf (*result
, format
, *args
);
123 vasprintf (char **result
, const char *format
, va_list args
)
125 return int_vasprintf (result
, format
, &args
);
129 asprintf (char **result
, const char *format
, ...)
134 va_start (args
, format
);
135 done
= vasprintf (result
, format
, args
);
141 /* ========================= test program ========================= */
148 checkit (const char* format
, ...)
153 va_start (args
, format
);
154 vasprintf (&result
, format
, args
);
155 if (strlen (result
) < global_total_width
)
159 printf ("%lu %s\n", (unsigned long) global_total_width
, result
);
165 checkit ("%d", 0x12345678);
166 checkit ("%200d", 5);
167 checkit ("%.300d", 6);
168 checkit ("%100.150d", 7);
169 checkit ("%s", "jjjjjjjjjiiiiiiiiiiiiiiioooooooooooooooooppppppppppppaa\n\
170 777777777777777777333333333333366666666666622222222222777777777777733333");
171 checkit ("%f%s%d%s", 1.0, "foo", 77, "asdjffffffffffffffiiiiiiiiiiixxxxx");
172 checkit ("%e", DBL_MIN
);
173 checkit ("%e", DBL_MAX
);
174 checkit ("%.400f", DBL_MIN
);
175 checkit ("%f", DBL_MAX
);
176 checkit ("%g", DBL_MIN
);
177 checkit ("%g", DBL_MAX
);