From 563c515068fc63cdabe9ccec9292714c78fae8eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20Andr=C3=A9=20Tanner?= Date: Tue, 3 Nov 2015 16:25:23 +0100 Subject: buffer: add buffer_insert to insert data at an arbitrary position Use it to implement buffer_{pre,ap}pend. --- buffer.c | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) (limited to 'buffer.c') diff --git a/buffer.c b/buffer.c index 3cdf65a..6a16a7b 100644 --- a/buffer.c +++ b/buffer.c @@ -48,15 +48,29 @@ bool buffer_put0(Buffer *buf, const char *data) { return buffer_put(buf, data, strlen(data)+1); } -bool buffer_append(Buffer *buf, const void *data, size_t len) { - size_t rem = buf->size - buf->len; - if (len > rem && !buffer_grow(buf, buf->size + len - rem)) +bool buffer_insert(Buffer *buf, size_t pos, const void *data, size_t len) { + if (pos > buf->len) + return false; + if (!buffer_grow(buf, buf->len + len)) return false; - memcpy(buf->data + buf->len, data, len); + memmove(buf->data + pos + len, buf->data + pos, buf->len - pos); + memcpy(buf->data + pos, data, len); buf->len += len; return true; } +bool buffer_insert0(Buffer *buf, size_t pos, const char *data) { + if (pos == 0) + return buffer_prepend0(buf, data); + if (pos == buf->len) + return buffer_append0(buf, data); + return buffer_insert(buf, pos, data, strlen(data)); +} + +bool buffer_append(Buffer *buf, const void *data, size_t len) { + return buffer_insert(buf, buf->len, data, len); +} + bool buffer_append0(Buffer *buf, const char *data) { if (buf->len > 0 && buf->data[buf->len-1] == '\0') buf->len--; @@ -64,12 +78,7 @@ bool buffer_append0(Buffer *buf, const char *data) { } bool buffer_prepend(Buffer *buf, const void *data, size_t len) { - if (!buffer_grow(buf, buf->len + len)) - return false; - memmove(buf->data + len, buf->data, buf->len); - memcpy(buf->data, data, len); - buf->len += len; - return true; + return buffer_insert(buf, 0, data, len); } bool buffer_prepend0(Buffer *buf, const char *data) { -- cgit v1.2.3