1 /* Like vsprintf but provides a pointer to malloc'd storage, which must
2 be freed by the caller.
3 Copyright (C) 1994 Free Software Foundation, Inc.
5 This file is part of the libiberty library.
6 Libiberty is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
11 Libiberty is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with libiberty; see the file COPYING.LIB. If
18 not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
31 int global_total_width
;
34 unsigned long strtoul ();
38 int_vasprintf (result
, format
, args
)
43 const char *p
= format
;
44 /* Add one to make sure that it is never zero, which might cause malloc
46 int total_width
= strlen (format
) + 1;
49 memcpy ((PTR
) &ap
, (PTR
) args
, sizeof (va_list));
55 while (strchr ("-+ #0", *p
))
60 total_width
+= abs (va_arg (ap
, int));
63 total_width
+= strtoul (p
, &p
, 10);
70 total_width
+= abs (va_arg (ap
, int));
73 total_width
+= strtoul (p
, &p
, 10);
75 while (strchr ("hlL", *p
))
77 /* Should be big enough for any format specifier except %s and floats. */
88 (void) va_arg (ap
, int);
95 (void) va_arg (ap
, double);
96 /* Since an ieee double can have an exponent of 307, we'll
97 make the buffer wide enough to cover the gross case. */
101 total_width
+= strlen (va_arg (ap
, char *));
105 (void) va_arg (ap
, char *);
111 global_total_width
= total_width
;
113 *result
= malloc (total_width
);
115 return vsprintf (*result
, format
, *args
);
121 vasprintf (result
, format
, args
)
124 #if defined (_BSD_VA_LIST_) && defined (__FreeBSD__)
130 return int_vasprintf (result
, format
, &args
);
137 (const char* format
, ...)
147 va_start (args
, format
);
151 format
= va_arg (args
, char *);
153 vasprintf (&result
, format
, args
);
154 if (strlen (result
) < global_total_width
)
158 printf ("%d %s\n", global_total_width
, result
);
164 checkit ("%d", 0x12345678);
165 checkit ("%200d", 5);
166 checkit ("%.300d", 6);
167 checkit ("%100.150d", 7);
168 checkit ("%s", "jjjjjjjjjiiiiiiiiiiiiiiioooooooooooooooooppppppppppppaa\n\
169 777777777777777777333333333333366666666666622222222222777777777777733333");
170 checkit ("%f%s%d%s", 1.0, "foo", 77, "asdjffffffffffffffiiiiiiiiiiixxxxx");