Libftpp
A modern C++ library
data_buffer.cpp
Go to the documentation of this file.
1 #include "data_buffer.hpp"
2 
3 DataBuffer::DataBuffer() : _cursor(0) {}
4 
8 void DataBuffer::reset() const
9 {
10  _cursor = 0;
11 }
12 
17 {
18  _buffer.clear();
19  _cursor = 0;
20 }
21 
22 void DataBuffer::append(const unsigned char* data, size_t len)
23 {
24  if (len == 0 || data == nullptr)
25  return;
26  _buffer.insert(_buffer.end(), data, data + len);
27 }
28 
29 DataBuffer& DataBuffer::operator<<(const std::string& value)
30 {
31  size_t size = value.length();
32  *this << size;
33 
34  _buffer.insert(_buffer.end(), value.begin(), value.end());
35  return *this;
36 }
37 
38 const DataBuffer& DataBuffer::operator>>(std::string& value) const
39 {
40  size_t size;
41  *this >> size;
42 
43  if (size + _cursor > _buffer.size())
44  throw std::out_of_range("Buffer overflow on read");
45 
46  value.assign(_buffer.begin() + _cursor, _buffer.begin() + _cursor + size);
47  _cursor += size;
48 
49  return *this;
50 }
51 
52 size_t DataBuffer::size() const
53 {
54  return _buffer.size() - _cursor;
55 }
56 
57 const std::vector<unsigned char> DataBuffer::data() const
58 {
59  return std::vector<unsigned char>(_buffer.begin() + _cursor, _buffer.end());
60 }
61 
67 void DataBuffer::increaseCursor(size_t amount) const
68 {
69  if (_cursor + amount > _buffer.size())
70  throw std::out_of_range("Buffer overflow on increaseCursor");
71 
72  _cursor += amount;
73 }
74 
80 void DataBuffer::decreaseCursor(size_t amount) const
81 {
82  if (amount > _cursor)
83  throw std::out_of_range("Buffer underflow on decreaseCursor");
84 
85  _cursor -= amount;
86 }
A simple LIFO data buffer for serialization and deserialization for simple data types and std::string...
Definition: data_buffer.hpp:37
size_t size() const
Definition: data_buffer.cpp:52
void reset() const
Reset the read/write cursor to the beginning of the buffer.
Definition: data_buffer.cpp:8
void increaseCursor(size_t amount) const
Increase the read/write cursor by a specified amount.
Definition: data_buffer.cpp:67
const DataBuffer & operator>>(std::string &value) const
Definition: data_buffer.cpp:38
void clear()
Clear the buffer and reset the cursor.
Definition: data_buffer.cpp:16
const std::vector< unsigned char > data() const
Definition: data_buffer.cpp:57
void decreaseCursor(size_t amount) const
Decrease the read/write cursor by a specified amount.
Definition: data_buffer.cpp:80
void append(const unsigned char *data, size_t len)
Definition: data_buffer.cpp:22
DataBuffer & operator<<(const std::string &value)
Definition: data_buffer.cpp:29