2 buffer.c -- buffer management
3 Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
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 void buffer_compact(buffer_t *buffer, size_t maxsize) {
26 if(buffer->len >= maxsize || buffer->offset / 7 > buffer->len / 8) {
27 memmove(buffer->data, buffer->data + buffer->offset, buffer->len - buffer->offset);
28 buffer->len -= buffer->offset;
33 // Make sure we can add size bytes to the buffer, and return a pointer to the start of those bytes.
35 char *buffer_prepare(buffer_t *buffer, size_t size) {
37 assert(!buffer->maxlen);
39 buffer->maxlen = size;
40 buffer->data = xmalloc(size);
42 if(buffer->offset && buffer->len + size > buffer->maxlen) {
43 memmove(buffer->data, buffer->data + buffer->offset, buffer->len - buffer->offset);
44 buffer->len -= buffer->offset;
48 if(buffer->len + size > buffer->maxlen) {
49 buffer->maxlen = buffer->len + size;
50 buffer->data = xrealloc(buffer->data, buffer->maxlen);
54 char *start = buffer->data + buffer->len;
61 // Copy data into the buffer.
63 void buffer_add(buffer_t *buffer, const char *data, size_t size) {
67 memcpy(buffer_prepare(buffer, size), data, size);
70 // Remove given number of bytes from the buffer, return a pointer to the start of them.
72 static char *buffer_consume(buffer_t *buffer, size_t size) {
74 assert(buffer->len - buffer->offset >= size);
76 char *start = buffer->data + buffer->offset;
78 buffer->offset += size;
80 if(buffer->offset >= buffer->len) {
88 // Check if there is a complete line in the buffer, and if so, return it NULL-terminated.
90 char *buffer_readline(buffer_t *buffer) {
91 char *newline = memchr(buffer->data + buffer->offset, '\n', buffer->len - buffer->offset);
97 size_t len = newline + 1 - (buffer->data + buffer->offset);
99 return buffer_consume(buffer, len);
102 // Check if we have enough bytes in the buffer, and if so, return a pointer to the start of them.
104 char *buffer_read(buffer_t *buffer, size_t size) {
107 if(buffer->len - buffer->offset < size) {
111 return buffer_consume(buffer, size);
114 void buffer_clear(buffer_t *buffer) {
115 assert(!buffer->data == !buffer->maxlen);