95 lines
2.2 KiB
C
Raw Normal View History

2013-01-22 13:46:38 +01:00
// Copyright (C) 2013 Red Hat, Inc. All rights reserved.
//
// This file is part of the thin-provisioning-tools source.
//
// thin-provisioning-tools is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// thin-provisioning-tools is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with thin-provisioning-tools. If not, see
// <http://www.gnu.org/licenses/>.
#ifndef BUFFER_H
#define BUFFER_H
#include <stdint.h>
2013-01-23 13:28:00 +01:00
#include <malloc.h>
2013-01-22 13:46:38 +01:00
2013-01-23 13:28:00 +01:00
#include <boost/optional.hpp>
#include <boost/shared_ptr.hpp>
2013-01-23 14:39:42 +01:00
#include <boost/static_assert.hpp>
2013-01-23 13:28:00 +01:00
#include <stdexcept>
2013-01-22 13:46:38 +01:00
//----------------------------------------------------------------
namespace persistent_data {
2013-01-23 13:28:00 +01:00
uint32_t const DEFAULT_BUFFER_SIZE = 4096;
2013-01-22 13:46:38 +01:00
template <uint32_t Size = DEFAULT_BUFFER_SIZE>
class buffer {
2013-01-22 13:46:38 +01:00
public:
buffer(void *data, bool writeable = true)
: data_(static_cast<unsigned char *>(data)),
writeable_(writeable) {
}
2013-01-23 14:39:42 +01:00
2013-01-23 13:28:00 +01:00
typedef boost::shared_ptr<buffer> ptr;
2013-01-23 14:32:03 +01:00
typedef boost::shared_ptr<buffer const> const_ptr;
2013-01-23 13:28:00 +01:00
2013-06-25 14:18:38 +01:00
size_t size() const {
return Size;
}
2013-01-22 13:46:38 +01:00
unsigned char &operator[](unsigned index) {
check_writeable();
2013-01-22 13:46:38 +01:00
check_index(index);
2013-01-23 13:28:00 +01:00
2013-01-22 13:46:38 +01:00
return data_[index];
}
unsigned char const &operator[](unsigned index) const {
check_index(index);
2013-01-23 13:28:00 +01:00
2013-01-22 13:46:38 +01:00
return data_[index];
}
unsigned char *raw() {
return data_;
}
unsigned char const *raw() const {
return data_;
}
void set_data(void *data) {
data_ = static_cast<unsigned char *>(data);
2013-01-22 13:46:38 +01:00
}
2013-01-23 13:51:13 +01:00
private:
2013-01-22 13:46:38 +01:00
static void check_index(unsigned index) {
2013-01-23 13:28:00 +01:00
if (index >= Size)
throw std::range_error("buffer index out of bounds");
2013-01-22 13:46:38 +01:00
}
void check_writeable() const {
if (!writeable_)
throw std::runtime_error("buffer isn't writeable");
}
unsigned char *data_;
bool writeable_;
2013-01-22 13:46:38 +01:00
};
}
//----------------------------------------------------------------
#endif