diff options
author | Karen Arutyunov <karen@codesynthesis.com> | 2023-12-13 21:57:53 +0300 |
---|---|---|
committer | Karen Arutyunov <karen@codesynthesis.com> | 2024-01-23 21:20:44 +0300 |
commit | fc3fb39c90ab7fe5fccbe3f3bc0eb2645157bb96 (patch) | |
tree | 6c8c1bfb5fe89f7378b92ac066b4ca8ecfd25228 /libcommon/buffer.hxx | |
parent | 02367faedb16b6186e8852de47e5b749dc48c2df (diff) |
Switch to build2
Diffstat (limited to 'libcommon/buffer.hxx')
-rw-r--r-- | libcommon/buffer.hxx | 104 |
1 files changed, 104 insertions, 0 deletions
diff --git a/libcommon/buffer.hxx b/libcommon/buffer.hxx new file mode 100644 index 0000000..41b7e46 --- /dev/null +++ b/libcommon/buffer.hxx @@ -0,0 +1,104 @@ +// file : libcommon/buffer.hxx +// license : GNU GPL v2; see accompanying LICENSE file + +#ifndef LIBCOMMON_BUFFER_HXX +#define LIBCOMMON_BUFFER_HXX + +#include <new> +#include <cstddef> // std::size_t +#include <cstring> // std::{memcmp,memcpy} + +struct basic_buffer_base +{ + ~basic_buffer_base () + { + operator delete (data_); + } + + basic_buffer_base () + : data_ (0), size_ (0) + { + } + + basic_buffer_base (const void* data, std::size_t size) + : data_ (0), size_ (size) + { + data_ = operator new (size_); + std::memcpy (data_, data, size_); + } + + basic_buffer_base (const basic_buffer_base& y) + : data_ (0), size_ (0) + { + assign (y.data_, y.size_); + } + + basic_buffer_base& + operator= (const basic_buffer_base& y) + { + if (this != &y) + assign (y.data_, y.size_); + + return *this; + } + + void + assign (const void* data, std::size_t size) + { + if (size_ < size) + { + void *p (operator new (size)); + operator delete (data_); + data_ = p; + } + + std::memcpy (data_, data, size); + size_ = size; + } + + std::size_t + size () const + { + return size_; + } + + bool + operator== (const basic_buffer_base& y) const + { + return size_ == y.size_ && std::memcmp (data_, y.data_, size_) == 0; + } + +protected: + void* data_; + std::size_t size_; +}; + +template <typename T> +struct basic_buffer: basic_buffer_base +{ + basic_buffer () + { + } + + basic_buffer (const T* data, std::size_t size) + : basic_buffer_base (data, size) + { + } + + T* + data () + { + return static_cast<T*> (data_); + } + + const T* + data () const + { + return static_cast<const T*> (data_); + } +}; + +typedef basic_buffer<char> buffer; +typedef basic_buffer<unsigned char> ubuffer; + +#endif // LIBCOMMON_BUFFER_HXX |