buffer.cpp 2.09 KB
Newer Older
1
2
3
/** A simple growing buffer.
 *
 * @author Steffen Vogel <stvogel@eonerc.rwth-aachen.de>
Steffen Vogel's avatar
Steffen Vogel committed
4
 * @copyright 2014-2019, Institute for Automation of Complex Power Systems, EONERC
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
 * @license GNU General Public License (version 3)
 *
 * VILLAScommon
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *********************************************************************************/

#include <string.h>

#include <villas/compat.h>
#include <villas/buffer.h>
#include <villas/common.h>

int buffer_init(struct buffer *b, size_t size)
{
	b->len = 0;
	b->size = size;
Steffen Vogel's avatar
Steffen Vogel committed
33
	b->buf = (char *) malloc(size);
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
	if (!b->buf)
		return -1;

	b->state = STATE_INITIALIZED;

	return 0;
}

int buffer_destroy(struct buffer *b)
{
	if (b->buf)
		free(b->buf);

	b->state = STATE_DESTROYED;

	return 0;
}

void buffer_clear(struct buffer *b)
{
	b->len = 0;
}

int buffer_append(struct buffer *b, const char *data, size_t len)
{
	if (b->len + len > b->size) {
		b->size = b->len + len;
Steffen Vogel's avatar
Steffen Vogel committed
61
		b->buf = (char *) realloc(b->buf, b->size);
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
		if (!b->buf)
			return -1;
	}

	memcpy(b->buf + b->len, data, len);

	b->len += len;

	return 0;
}

int buffer_parse_json(struct buffer *b, json_t **j)
{
	*j = json_loadb(b->buf, b->len, 0, NULL);
	if (!*j)
		return -1;

	return 0;
}

int buffer_append_json(struct buffer *b, json_t *j)
{
	size_t len;

retry:	len = json_dumpb(j, b->buf + b->len, b->size - b->len, 0);
	if (b->size < b->len + len) {
Steffen Vogel's avatar
Steffen Vogel committed
88
		b->buf = (char *) realloc(b->buf, b->len + len);
89
90
91
92
93
94
95
96
97
98
99
		if (!b->buf)
			return -1;

		b->size = b->len + len;
		goto retry;
	}

	b->len += len;

	return 0;
}