Last active
October 23, 2023 03:17
-
-
Save KVM-Explorer/3e8982fb47352a8eb1368434b35f082b to your computer and use it in GitHub Desktop.
[Fix Size Buffer]manager a simple fix length buffer with smart pointer #cpp #RAII
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <memory> | |
#include <assert.h> | |
/** | |
* @brief 一个固定长度的buffer | |
* @note 用于存储固定长度的数据,不会发生内存的重新分配 | |
* @author | |
*/ | |
class FixSizeBuffer { | |
public: | |
FixSizeBuffer(uint32_t size) | |
: data_(std::make_unique<uint8_t[]>(size)), | |
len_(size){} | |
~FixSizeBuffer() = default; | |
FixSizeBuffer(const FixSizeBuffer &) = delete; | |
FixSizeBuffer &operator=(const FixSizeBuffer &) = delete; | |
FixSizeBuffer(FixSizeBuffer &&) = default; | |
FixSizeBuffer &operator=(FixSizeBuffer &&) = default; | |
public: | |
int length() const { return len_; } | |
void copy_data(int offset, const uint8_t *src, int size) { | |
assert(offset + size <= len_ ); | |
data_ = std::make_unique<uint8_t[]>(size); | |
std::memcpy(data_.get() + offset, src, size); | |
} | |
const uint8_t *data() const { return data_.get(); } | |
private: | |
std::unique_ptr<uint8_t[]> data_; | |
int len_; | |
}; | |
int main() { | |
FixSizeBuffer key(10); | |
uint8_t data[10] = {0,1,2,3,4,5,6,7,8,9}; | |
key.copy_data(0, data, 10); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment