added methods to the template Buffer class : copy ctor, ==, !=, clear, =, swap, empty

This commit is contained in:
Marian Krivos
2012-05-13 17:00:42 +00:00
parent dd5eea6cd1
commit c41196bd5b
2 changed files with 87 additions and 4 deletions

View File

@@ -9,7 +9,7 @@
// //
// Definition of the Buffer class. // Definition of the Buffer class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -65,7 +65,29 @@ public:
/// Creates and allocates the Buffer. /// Creates and allocates the Buffer.
{ {
} }
Buffer(const Buffer& other):
/// Copy constructor.
_capacity(other._used),
_used(other._used),
_ptr(new T[other._used])
{
if (_used)
std::memcpy(_ptr, other._ptr, _used * sizeof(T));
}
Buffer& operator =(const Buffer& other)
/// Assignment operator.
{
if (this != &other)
{
Buffer tmp(other);
swap(tmp);
}
return *this;
}
~Buffer() ~Buffer()
/// Destroys the Buffer. /// Destroys the Buffer.
{ {
@@ -100,6 +122,46 @@ public:
return _capacity; return _capacity;
} }
void swap(Buffer& other)
/// Swaps the buffer with another one.
{
using std::swap;
swap(_ptr, other._ptr);
swap(_capacity, other._capacity);
swap(_used, other._used);
}
bool operator ==(const Buffer& other) const
/// Compare operator.
{
if (this != &other)
{
if (_used == other._used)
{
if (std::memcmp(_ptr, other._ptr, _used) == 0)
{
return true;
}
}
return false;
}
return true;
}
bool operator !=(const Buffer& other) const
/// Compare operator.
{
return !(*this == other);
}
void clear()
/// Sets the contents of the bufer to zero.
{
std::memset(_ptr, 0, _used * sizeof(T));
}
std::size_t size() const std::size_t size() const
/// Returns the used size of the buffer. /// Returns the used size of the buffer.
{ {
@@ -130,6 +192,12 @@ public:
return _ptr + _used; return _ptr + _used;
} }
bool empty() const
/// Return true if buffer is empty.
{
return 0 == _used;
}
T& operator [] (std::size_t index) T& operator [] (std::size_t index)
{ {
poco_assert (index < _used); poco_assert (index < _used);
@@ -146,8 +214,6 @@ public:
private: private:
Buffer(); Buffer();
Buffer(const Buffer&);
Buffer& operator = (const Buffer&);
std::size_t _capacity; std::size_t _capacity;
std::size_t _used; std::size_t _used;

View File

@@ -234,6 +234,23 @@ void CoreTest::testBuffer()
try { int i = b[s]; fail ("must fail"); } try { int i = b[s]; fail ("must fail"); }
catch (Exception&) { } catch (Exception&) { }
#endif #endif
Buffer<int> c(s);
Buffer<int> d(c);
assert (c == d);
c[1] = -1;
assert (c[1] == -1);
c.clear();
assert (c[1] == 0);
Buffer<int> e(0);
assert (e.empty());
assert (c != e);
Buffer<int> f = e;
assert (f == e);
} }