Skip to content

Commit

Permalink
Expand buffer functionality (#389)
Browse files Browse the repository at this point in the history
  • Loading branch information
hkadayam authored Jan 13, 2023
1 parent e74f357 commit 1524ac9
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
14 changes: 14 additions & 0 deletions include/libnuraft/buffer.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,20 @@ public:
*/
static ptr<buffer> clone(const buffer& buf);

/**
* Expand the current buffer to new size (which is expected to
* bigger than current size) and return a new buffer. It will copy
* the existing buffer.
*
* WARNING: It will still retain the current position of the passed
* buffer and the new ptr buffer (i.e. ret_buf->pos() == buf->pos())
*
* @param buf Pointer to buffer which will be realloced
* @param new_size New size of the buffer
* @return Expanded buffer instance
*/
static ptr<buffer> expand(const buffer& buf, uint32_t new_size);

/**
* Get total size of entire buffer container, including meta section.
*
Expand Down
20 changes: 19 additions & 1 deletion src/buffer.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ ptr<buffer> buffer::alloc(const size_t size) {

if (size >= 0x80000000) {
throw std::out_of_range( "size exceed the max size that "
"cornrestone::buffer could support" );
"nuraft::buffer could support" );
}
num_allocs++;
num_active++;
Expand Down Expand Up @@ -144,6 +144,24 @@ ptr<buffer> buffer::clone(const buffer& buf) {
return other;
}

ptr<buffer> buffer::expand(const buffer& buf, uint32_t new_size) {
if (new_size >= 0x80000000) {
throw std::out_of_range( "size exceed the max size that "
"nuraft::buffer could support" );
}

if (new_size < buf.size()) {
throw std::out_of_range( "realloc() new_size is less than "
"old size" );
}
ptr<buffer> other = alloc(new_size);
byte* dst = other->data_begin();
byte* src = buf.data_begin();
::memcpy(dst, src, buf.size());
other->pos(buf.pos());
return other;
}

size_t buffer::container_size() const {
return (size_t)( __size_of_block(this) +
( ( __is_big_block(this) )
Expand Down
14 changes: 14 additions & 0 deletions tests/unit/buffer_test.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,20 @@ int buffer_basic_test(size_t buf_size) {
ulong long_val_copy = lbuf1->get_ulong();
CHK_EQ( long_val, long_val_copy );

ptr<buffer> buf4(buffer::alloc(sz_int * 100));
buf4->pos(0);
for (int i = 0; i < 100; ++i) {
buf4->put(i);
}
buf4 = buffer::expand(*buf4, sz_int * 200);
for (int i = 0; i < 100; ++i) {
buf4->put(i + 100);
}
buf4->pos(0);
for (int i = 0; i < 200; ++i) {
int32 val = buf4->get_int();
CHK_EQ( i, val );
}
return 0;
}

Expand Down

0 comments on commit 1524ac9

Please sign in to comment.