2 buffer.c -- buffer management
3 Copyright (C) 2014 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, int 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, int size) {
37 buffer->maxlen = size;
38 buffer->data = xmalloc(size);
40 if(buffer->offset && buffer->len + size > buffer->maxlen) {
41 memmove(buffer->data, buffer->data + buffer->offset, buffer->len - buffer->offset);
42 buffer->len -= buffer->offset;
46 if(buffer->len + size > buffer->maxlen) {
47 buffer->maxlen = buffer->len + size;
48 buffer->data = xrealloc(buffer->data, buffer->maxlen);
52 char *start = buffer->data + buffer->len;
59 // Copy data into the buffer.
61 void buffer_add(buffer_t *buffer, const char *data, int size) {
62 memcpy(buffer_prepare(buffer, size), data, size);
65 // Remove given number of bytes from the buffer, return a pointer to the start of them.
67 static char *buffer_consume(buffer_t *buffer, int size) {
68 char *start = buffer->data + buffer->offset;
70 buffer->offset += size;
72 if(buffer->offset >= buffer->len) {
80 // Check if there is a complete line in the buffer, and if so, return it NULL-terminated.
82 char *buffer_readline(buffer_t *buffer) {
83 char *newline = memchr(buffer->data + buffer->offset, '\n', buffer->len - buffer->offset);
88 int len = newline + 1 - (buffer->data + buffer->offset);
90 return buffer_consume(buffer, len);
93 // Check if we have enough bytes in the buffer, and if so, return a pointer to the start of them.
95 char *buffer_read(buffer_t *buffer, int size) {
96 if(buffer->len - buffer->offset < size)
99 return buffer_consume(buffer, size);
102 void buffer_clear(buffer_t *buffer) {