bison-i18n: Add support for mingw builds on Cygwin hosts.
[gnulib.git] / lib / obstack_printf.c
blobed996dd180cd1bc7b4c7d4ba50ce2433c1472168
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/>. */
17 #include <config.h>
19 /* Specification. */
20 #include <stdio.h>
22 #include "obstack.h"
23 #include "vasnprintf.h"
25 #include <errno.h>
26 #include <stdarg.h>
27 #include <stdlib.h>
29 #ifndef RESULT_TYPE
30 # define RESULT_TYPE int
31 # define OBSTACK_PRINTF obstack_printf
32 # define OBSTACK_VPRINTF obstack_vprintf
33 #endif
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. */
41 RESULT_TYPE
42 OBSTACK_PRINTF (struct obstack *obs, const char *format, ...)
44 va_list args;
45 RESULT_TYPE result;
47 va_start (args, format);
48 result = OBSTACK_VPRINTF (obs, format, args);
49 va_end (args);
50 return result;
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. */
59 RESULT_TYPE
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
65 obstack. */
66 enum { CUTOFF = 1024 };
67 char buf[CUTOFF];
68 char *base = obstack_next_free (obs);
69 size_t len = obstack_room (obs);
70 char *str;
72 if (len < CUTOFF)
74 base = buf;
75 len = CUTOFF;
77 str = vasnprintf (base, &len, format, args);
78 if (!str)
80 if (errno == ENOMEM)
81 obstack_alloc_failed_handler ();
82 return -1;
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);
88 else
90 /* The output exceeded available obstack space or we used buf;
91 copy the resulting string. */
92 obstack_grow (obs, str, len);
93 if (str != buf)
94 free (str);
96 return len;