/ libpkg / xstring.h
xstring.h
 1  #ifndef __XSTRING_H_
 2  #define __XSTRING_H_
 3  
 4  #include <stdio.h>
 5  #include <stdlib.h>
 6  #include <string.h>
 7  
 8  struct xstring {
 9  	char* buf;
10  	size_t size;
11  	FILE* fp;
12  };
13  
14  typedef struct xstring xstring;
15  
16  static inline xstring *
17  xstring_new(void)
18  {
19  	xstring *str;
20  
21  	str = calloc(1, sizeof(*str));
22  	if (str == NULL)
23  		abort();
24  	str->fp = open_memstream(&str->buf, &str->size);
25  	if (str->fp == NULL)
26  		abort();
27  
28  	return (str);
29  }
30  
31  static inline void
32  xstring_reset(xstring *str)
33  {
34  	if (str->buf)
35  		memset(str->buf, 0, str->size);
36  	rewind(str->fp);
37  
38  }
39  
40  static inline void
41  xstring_free(xstring *str)
42  {
43  	if (str == NULL)
44  		return;
45  	fclose(str->fp);
46  	free(str->buf);
47  	free(str);
48  }
49  
50  #define xstring_renew(s)      \
51  do {                          \
52     if (s) {                   \
53       xstring_reset(s);        \
54     } else {                   \
55       s = xstring_new();       \
56     }                          \
57  } while(0)
58  
59  static inline char *
60  xstring_get(xstring *str)
61  {
62  	fclose(str->fp);
63  	char *ret = str->buf;
64  	free(str);
65  	return (ret);
66  }
67  
68  static inline char *
69  xstring_get_binary(xstring *str, size_t *size)
70  {
71  	fclose(str->fp);
72  	char *ret = str->buf;
73  	*size = str->size;
74  	free(str);
75  	return (ret);
76  }
77  
78  #endif