From 74bd3bbc7edf0c067ba9eafe51b463d2e0e121bd Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Mon, 28 Mar 2011 11:40:14 +0200 Subject: Factor out common buffer implementation --- libcommon/common/buffer.hxx | 89 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 libcommon/common/buffer.hxx (limited to 'libcommon') diff --git a/libcommon/common/buffer.hxx b/libcommon/common/buffer.hxx new file mode 100644 index 0000000..97e8962 --- /dev/null +++ b/libcommon/common/buffer.hxx @@ -0,0 +1,89 @@ +// file : libcommon/common/buffer.hxx +// author : Boris Kolpackov +// copyright : Copyright (c) 2005-2011 Code Synthesis Tools CC +// license : GNU GPL v2; see accompanying LICENSE file + +#ifndef LIBCOMMON_COMMON_BUFFER_HXX +#define LIBCOMMON_COMMON_BUFFER_HXX + +#include // std::size_t +#include // std::{memcmp,memcpy} + +struct buffer +{ + ~buffer () + { + delete[] data_; + } + + buffer () + : data_ (0), size_ (0) + { + } + + buffer (const void* data, std::size_t size) + : data_ (0), size_ (size) + { + data_ = new char[size_]; + std::memcpy (data_, data, size_); + } + + buffer (const buffer& y) + : data_ (0), size_ (0) + { + assign (y.data_, y.size_); + } + + buffer& + operator= (const buffer& y) + { + if (this != &y) + assign (y.data_, y.size_); + + return *this; + } + + void + assign (const void* data, std::size_t size) + { + if (size_ < size) + { + char* p (new char[size]); + delete[] data_; + data_ = p; + } + + std::memcpy (data_, data, size); + size_ = size; + } + + char* + data () + { + return data_; + } + + const char* + data () const + { + return data_; + } + + std::size_t + size () const + { + return size_; + } + + bool + operator== (const buffer& y) const + { + return size_ == y.size_ && std::memcmp (data_, y.data_, size_) == 0; + } + +private: + char* data_; + std::size_t size_; +}; + +#endif // LIBCOMMON_COMMON_BUFFER_HXX -- cgit v1.1