diff options
| author | Marc André Tanner <mat@brain-dump.org> | 2015-11-03 16:25:23 +0100 |
|---|---|---|
| committer | Marc André Tanner <mat@brain-dump.org> | 2015-11-03 16:25:23 +0100 |
| commit | 563c515068fc63cdabe9ccec9292714c78fae8eb (patch) | |
| tree | 0603b4f604529ff55109859067f3ff2899d3d963 | |
| parent | 621edbca00ae599e46f7a68ee9f17aa4049496e5 (diff) | |
| download | vis-563c515068fc63cdabe9ccec9292714c78fae8eb.tar.gz vis-563c515068fc63cdabe9ccec9292714c78fae8eb.tar.xz | |
buffer: add buffer_insert to insert data at an arbitrary position
Use it to implement buffer_{pre,ap}pend.
| -rw-r--r-- | buffer.c | 29 | ||||
| -rw-r--r-- | buffer.h | 4 |
2 files changed, 23 insertions, 10 deletions
@@ -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) { @@ -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 */ |
