1 /* Formatted output to obstacks.
2 Copyright (C) 2008-2024 Free Software Foundation, Inc.
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published
6 by the Free Software Foundation, either version 3 of the License,
7 or (at your option) any later version.
9 This file 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
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
23 #include "vasnprintf.h"
30 # define RESULT_TYPE int
31 # define OBSTACK_PRINTF obstack_printf
32 # define OBSTACK_VPRINTF obstack_vprintf
35 /* Grow an obstack with formatted output. Return the number of bytes
36 added to OBS. No trailing nul byte is added, and the object should
37 be closed with obstack_finish before use.
39 Upon memory allocation error, call obstack_alloc_failed_handler.
40 Upon other error, return -1. */
42 OBSTACK_PRINTF (struct obstack
*obs
, const char *format
, ...)
47 va_start (args
, format
);
48 result
= OBSTACK_VPRINTF (obs
, format
, args
);
53 /* Grow an obstack with formatted output. Return the number of bytes
54 added to OBS. No trailing nul byte is added, and the object should
55 be closed with obstack_finish before use.
57 Upon memory allocation error, call obstack_alloc_failed_handler.
58 Upon other error, return -1. */
60 OBSTACK_VPRINTF (struct obstack
*obs
, const char *format
, va_list args
)
62 /* If we are close to the end of the current obstack chunk, use a
63 stack-allocated buffer and copy, to reduce the likelihood of a
64 small-size malloc. Otherwise, print directly into the
66 enum { CUTOFF
= 1024 };
68 char *base
= obstack_next_free (obs
);
69 size_t len
= obstack_room (obs
);
77 str
= vasnprintf (base
, &len
, format
, args
);
81 obstack_alloc_failed_handler ();
84 if (str
== base
&& str
!= buf
)
85 /* The output was already computed in place, but we need to
86 account for its size. */
87 obstack_blank_fast (obs
, len
);
90 /* The output exceeded available obstack space or we used buf;
91 copy the resulting string. */
92 obstack_grow (obs
, str
, len
);