Libftpp
A modern C++ library
data_buffer.hpp
Go to the documentation of this file.
1 #ifndef DATA_BUFFER_HPP
2 #define DATA_BUFFER_HPP
3 
4 #include <stdio.h>
5 
6 #include <cstring>
7 #include <iostream>
8 #include <type_traits>
9 #include <vector>
10 
37 {
38 private:
39  std::vector<unsigned char> _buffer;
40  mutable size_t _cursor;
41 
42 public:
43  DataBuffer();
44  ~DataBuffer() = default;
45 
46  const std::vector<unsigned char> data() const;
47  void increaseCursor(size_t amount) const;
48  void decreaseCursor(size_t amount) const;
49 
50  void reset() const;
51  void clear();
52  size_t size() const;
53 
54  void append(const unsigned char* data, size_t len);
55 
56  DataBuffer& operator<<(const std::string& value);
57  const DataBuffer& operator>>(std::string& value) const;
58 
59  template <typename T>
60  DataBuffer& operator<<(const T& value)
61  {
62  const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&value);
63  _buffer.insert(_buffer.end(), ptr, ptr + sizeof(T));
64  return *this;
65  }
66 
67  template <typename T>
68  const DataBuffer& operator>>(T& value) const
69  {
70  if (sizeof(T) + _cursor > _buffer.size())
71  throw std::out_of_range("Buffer overflow on read");
72 
73  std::memcpy(&value, _buffer.data() + _cursor, sizeof(T));
74 
75  _cursor += sizeof(T);
76  return *this;
77  }
78 };
79 
80 #endif
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
const DataBuffer & operator>>(T &value) const
Definition: data_buffer.hpp:68
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
~DataBuffer()=default
DataBuffer & operator<<(const T &value)
Definition: data_buffer.hpp:60
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