1 /* Formatted output to obstacks.
2 Copyright (C) 2008-2011 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
24 #include "vasnprintf.h"
30 /* Grow an obstack with formatted output. Return the number of bytes
31 added to OBS. No trailing nul byte is added, and the object should
32 be closed with obstack_finish before use.
34 Upon memory allocation error, call obstack_alloc_failed_handler.
35 Upon other error, return -1. */
37 obstack_printf (struct obstack *obs, const char *format, ...)
42 va_start (args, format);
43 result = obstack_vprintf (obs, format, args);
48 /* Grow an obstack with formatted output. Return the number of bytes
49 added to OBS. No trailing nul byte is added, and the object should
50 be closed with obstack_finish before use.
52 Upon memory allocation error, call obstack_alloc_failed_handler.
53 Upon other error, return -1. */
55 obstack_vprintf (struct obstack *obs, const char *format, va_list args)
57 /* If we are close to the end of the current obstack chunk, use a
58 stack-allocated buffer and copy, to reduce the likelihood of a
59 small-size malloc. Otherwise, print directly into the
61 enum { CUTOFF = 1024 };
63 char *base = obstack_next_free (obs);
64 size_t len = obstack_room (obs);
72 str = vasnprintf (base, &len, format, args);
76 obstack_alloc_failed_handler ();
79 if (str == base && str != buf)
80 /* The output was already computed in place, but we need to
81 account for its size. */
82 obstack_blank_fast (obs, len);
85 /* The output exceeded available obstack space or we used buf;
86 copy the resulting string. */
87 obstack_grow (obs, str, len);