00001 #include "ByteBuffer.hpp"
00002 #include <cstring>
00003 #include <cstdlib>
00004
00005 namespace aitools {
00006 namespace invertedindex {
00007
00008 ByteBuffer::ByteBuffer(size_t size) throw (std::bad_alloc)
00009 : data_(static_cast<char*>(std::malloc(size))),
00010 capacity_(size),
00011 size_(size)
00012 {
00013 if (data_ == NULL)
00014 {
00015 throw std::bad_alloc();
00016 }
00017 std::memset(data_, 0, size_);
00018 }
00019
00020 ByteBuffer::ByteBuffer(const ByteBuffer& buffer) throw (std::bad_alloc)
00021 : data_(static_cast<char*>(std::malloc(buffer.size_))),
00022 capacity_(buffer.size_),
00023 size_(buffer.size_)
00024 {
00025 if (data_ == NULL)
00026 {
00027 throw std::bad_alloc();
00028 }
00029 std::memcpy(data_, buffer.data_, size_);
00030 }
00031
00032 ByteBuffer::~ByteBuffer()
00033 {
00034 free();
00035 }
00036
00037 size_t
00038 ByteBuffer::capacity() const
00039 {
00040 return capacity_;
00041 }
00042
00043 void
00044 ByteBuffer::clear()
00045 {
00046 size_ = 0;
00047 }
00048
00049 char*
00050 ByteBuffer::data()
00051 {
00052 return data_;
00053 }
00054
00055 const char*
00056 ByteBuffer::data() const
00057 {
00058 return data_;
00059 }
00060
00061 bool
00062 ByteBuffer::empty() const
00063 {
00064 return size_ == 0;
00065 }
00066
00067 void
00068 ByteBuffer::free()
00069 {
00070 if (data_ != NULL)
00071 {
00072 std::free(data_);
00073 capacity_ = 0;
00074 data_ = NULL;
00075 size_ = 0;
00076 }
00077 }
00078
00079 ByteBuffer&
00080 ByteBuffer::operator=(const ByteBuffer& buffer) throw (std::bad_alloc)
00081 {
00082 resize(buffer.size_);
00083 std::memcpy(data_, buffer.data_, size_);
00084 return *this;
00085 }
00086
00087 bool
00088 ByteBuffer::operator==(const ByteBuffer& buffer) const
00089 {
00090 if (size_ != buffer.size_) return false;
00091 return std::memcmp(data_, buffer.data_, size_) == 0;
00092 }
00093
00094 bool
00095 ByteBuffer::operator!=(const ByteBuffer& buffer) const
00096 {
00097 return !(*this == buffer);
00098 }
00099
00100 void
00101 ByteBuffer::resize(size_t size) throw (std::bad_alloc)
00102 {
00103 if (size > capacity_)
00104 {
00105 char* data(static_cast<char*>(std::realloc(data_, size)));
00106 if (size != 0 && data == NULL)
00107 {
00108 throw std::bad_alloc();
00109 }
00110 capacity_ = size;
00111 data_ = data;
00112 }
00113 size_ = size;
00114 }
00115
00116 size_t
00117 ByteBuffer::size() const
00118 {
00119 return size_;
00120 }
00121
00122 }
00123 }
00124
00125 namespace std {
00126
00127 ostream&
00128 operator<<(ostream& os, const aitools::invertedindex::ByteBuffer& buffer)
00129 {
00130 if (os)
00131 {
00132 os << "ByteBuffer [ size = " << buffer.size()
00133 << ", capacity = " << buffer.capacity() << " ]";
00134 }
00135 return os;
00136 }
00137 }