aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--buffer.c29
-rw-r--r--buffer.h4
2 files changed, 23 insertions, 10 deletions
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) {
diff --git a/buffer.h b/buffer.h
index 85679c8..4c5ae33 100644
--- a/buffer.h
+++ b/buffer.h
@@ -23,6 +23,10 @@ void buffer_truncate(Buffer*);
bool buffer_put(Buffer*, const void *data, size_t len);
/* same but with NUL-terminated data */
bool buffer_put0(Buffer*, const char *data);
+/* insert arbitrary data of length len at pos (in [0, buf->len]) */
+bool buffer_insert(Buffer*, size_t pos, const void *data, size_t len);
+/* insert NUL-terminate data at pos (in [0, buf->len]) */
+bool buffer_insert0(Buffer*, size_t pos, const char *data);
/* append futher content to the end of the buffer data */
bool buffer_append(Buffer*, const void *data, size_t len);
/* append NUl-terminated data */