File: xstring.h

package info (click to toggle)
mlmmj 1.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,560 kB
  • sloc: ansic: 13,223; php: 1,337; perl: 904; sh: 501; makefile: 99
file content (70 lines) | stat: -rw-r--r-- 1,061 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#ifndef __XSTRING_H_
#define __XSTRING_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct xstring {
	char* buf;
	size_t size;
	FILE* fp;
};

typedef struct xstring xstring;

static inline xstring *
xstring_new(void)
{
	xstring *str;

	str = calloc(1, sizeof(*str));
	if (str == NULL)
		abort();
	str->fp = open_memstream(&str->buf, &str->size);
	if (str->fp == NULL)
		abort();

	return (str);
}

static inline void
xstring_reset(xstring *str)
{
	if (str->buf)
		memset(str->buf, 0, str->size);
	rewind(str->fp);

}

static inline void
xstring_free(xstring *str)
{
	if (str == NULL)
		return;
	fclose(str->fp);
	free(str->buf);
	free(str);
}

#define xstring_renew(s)      \
do {                          \
   if (s) {                   \
     xstring_reset(s);        \
   } else {                   \
     s = xstring_new();       \
   }                          \
} while(0)

static inline char *
xstring_get(xstring *str)
{
	if (str == NULL)
		return (NULL);
	fclose(str->fp);
	char *ret = str->buf;
	free(str);
	return (ret);
}

#endif