Skip to content

Commit 6febcfb

Browse files
committed
Add obstack_vprint function
closes #9
1 parent 3626297 commit 6febcfb

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

obstack.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@
110110

111111
#include <stddef.h> /* For size_t and ptrdiff_t. */
112112
#include <string.h> /* For __GNU_LIBRARY__, and memcpy. */
113+
#include <stdarg.h> /* For va_list. */
113114

114115
#if _OBSTACK_INTERFACE_VERSION == 1
115116
/* For binary compatibility with obstack version 1, which used "int"
@@ -213,6 +214,7 @@ extern _OBSTACK_SIZE_T _obstack_memory_used (struct obstack *)
213214

214215
/* Declare obstack_printf; it's in obstack_printf.c. */
215216
extern int obstack_printf(struct obstack *obstack, const char *__restrict fmt, ...);
217+
extern int obstack_vprintf(struct obstack *obstack, const char *__restrict fmt, va_list args);
216218

217219

218220
/* Error handler called when 'obstack_chunk_alloc' failed to allocate

obstack_printf.c

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,41 @@
11
#include <stdarg.h>
22
#include <stdio.h>
33
#include <strings.h>
4+
#include <stdlib.h>
45
#include "obstack.h"
56

67
int obstack_printf(struct obstack *obstack, const char *__restrict fmt, ...)
78
{
8-
char buf[1024];
99
va_list ap;
1010
int len;
1111

1212
va_start(ap, fmt);
13-
len = vsnprintf(buf, sizeof(buf), fmt, ap);
14-
obstack_grow(obstack, buf, len);
13+
len = obstack_vprintf(obstack, fmt, ap);
1514
va_end(ap);
1615

1716
return len;
1817
}
18+
19+
20+
int obstack_vprintf (struct obstack *obstack, const char *__restrict fmt, va_list args)
21+
{
22+
char buf[1024];
23+
size_t len;
24+
char * str = buf;
25+
26+
len = vsnprintf (buf, sizeof(buf), fmt, args);
27+
if (len >= sizeof(buf)) {
28+
str = NULL;
29+
len = vasprintf(&str, fmt, args);
30+
if ( len < 0 ) {
31+
free(str);
32+
return -1;
33+
}
34+
}
35+
obstack_grow (obstack, str, len);
36+
37+
if (str != buf)
38+
free(str);
39+
40+
return len;
41+
}

0 commit comments

Comments
 (0)