From 251f4917c3442c6c2716daca667c3022dda484ad Mon Sep 17 00:00:00 2001 From: Christopher Faulet Date: Mon, 24 Feb 2020 11:28:05 +0100 Subject: [PATCH] MINOR: buf: Add function to insert a string at an absolute offset in a buffer The b_insert_blk() function may now be used to insert a string, given a pointer and the string length, at an absolute offset in a buffer, moving data between this offset and the buffer's tail just after the end of the inserted string. The buffer's length is automatically updated. This function supports wrapping. All the string is copied or nothing. So it returns 0 if there are not enough space to perform the copy. Otherwise, the number of bytes copied is returned. --- include/common/buf.h | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/include/common/buf.h b/include/common/buf.h index b594c81ebb..0bdc5beb9d 100644 --- a/include/common/buf.h +++ b/include/common/buf.h @@ -673,6 +673,35 @@ static inline int b_rep_blk(struct buffer *b, char *pos, char *end, const char * return delta; } +/* b_insert_blk(): inserts the block at the absolute offset moving + * data between this offset and the buffer's tail just after the end of the copy + * of . The buffer's length is automatically updated. It Supports + * wrapping. If there are not enough space to perform the copy, 0 is + * returned. Otherwise, the number of bytes copied is returned +*/ +static inline int b_insert_blk(struct buffer *b, size_t off, const char *blk, size_t len) +{ + size_t pos; + + if (!len || len > b_room(b)) + return 0; /* nothing to copy or not enough space left */ + + pos = b_peek_ofs(b, off); + if (pos == b_tail_ofs(b)) + __b_putblk(b, blk, len); + else { + size_t delta = b_data(b) - off; + + /* first, protect the end of the buffer */ + b_move(b, pos, delta, len); + + /* change the amount of data in the buffer during the copy */ + b_sub(b, delta); + __b_putblk(b, blk, len); + b_add(b, delta); + } + return len; +} /* __b_put_varint(): encode 64-bit value as a varint into buffer . The * caller must have checked that the encoded value fits in the buffer so that