2 buffer.c -- buffer management
3 Copyright (C) 2011 Guus Sliepen <guus@tinc-vpn.org>,
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 // Make sure we can add size bytes to the buffer, and return a pointer to the start of those bytes.
27 char *buffer_prepare(buffer_t *buffer, int size) {
29 buffer->maxlen = size;
30 buffer->data = xmalloc(size);
32 if(buffer->offset && buffer->len + size > buffer->maxlen) {
33 memmove(buffer->data, buffer->data + buffer->offset, buffer->len - buffer->offset);
34 buffer->len -= buffer->offset;
38 if(buffer->len + size > buffer->maxlen) {
39 buffer->maxlen = buffer->len + size;
40 buffer->data = xrealloc(buffer->data, buffer->maxlen);
45 return buffer->data + buffer->offset;
48 // Copy data into the buffer.
50 char *buffer_add(buffer_t *buffer, const char *data, int size) {
51 memcpy(buffer_prepare(buffer, size), data, size);
54 // Remove given number of bytes from the buffer, return a pointer to the start of them.
56 static char *buffer_consume(buffer_t *buffer, int size) {
57 char *start = buffer->data + buffer->offset;
59 buffer->offset += size;
61 if(buffer->offset >= buffer->len) {
65 buffer->offset += size;
71 // Check if there is a complete line in the buffer, and if so, return it NULL-terminated.
73 char *buffer_readline(buffer_t *buffer) {
74 char *newline = memchr(buffer->data + buffer->offset, '\n', buffer->len - buffer->offset);
79 int len = newline + 1 - buffer->data + buffer->offset;
81 return buffer_consume(buffer, len);
84 // Check if we have enough bytes in the buffer, and if so, return a pointer to the start of them.
86 char *buffer_read(buffer_t *buffer, int size) {
87 if(buffer->len - buffer->offset < size)
90 return buffer_consume(buffer, size);
93 void buffer_clear(buffer_t *buffer) {