[buffer.h] add static test for alignment

This commit is contained in:
Joe Thornber 2013-01-23 13:32:33 +00:00
parent c2ab5390cb
commit aa12870c22
2 changed files with 12 additions and 1 deletions

View File

@ -26,6 +26,7 @@
#include <boost/noncopyable.hpp> #include <boost/noncopyable.hpp>
#include <boost/optional.hpp> #include <boost/optional.hpp>
#include <boost/shared_ptr.hpp> #include <boost/shared_ptr.hpp>
#include <boost/static_assert.hpp>
#include <stdexcept> #include <stdexcept>
@ -43,6 +44,9 @@ namespace persistent_data {
template <uint32_t Size = DEFAULT_BUFFER_SIZE, uint32_t Alignment = 512> template <uint32_t Size = DEFAULT_BUFFER_SIZE, uint32_t Alignment = 512>
class buffer : private boost::noncopyable { class buffer : private boost::noncopyable {
public: public:
BOOST_STATIC_ASSERT_MSG((Alignment > 1) && !(Alignment & (Alignment - 1)),
"Alignment must be a power of two.");
typedef boost::shared_ptr<buffer> ptr; typedef boost::shared_ptr<buffer> ptr;
typedef boost::shared_ptr<buffer const> const_ptr; typedef boost::shared_ptr<buffer const> const_ptr;
@ -73,7 +77,11 @@ namespace persistent_data {
// Allocates size bytes and returns a pointer to the // Allocates size bytes and returns a pointer to the
// allocated memory. The memory address will be a // allocated memory. The memory address will be a
// multiple of 'Alignment', which must be a power of two // multiple of 'Alignment', which must be a power of two
return memalign(Alignment, s); void *mem = memalign(Alignment, s);
if (!mem)
throw std::bad_alloc();
return mem;
} }
static void operator delete(void *p) { static void operator delete(void *p) {

View File

@ -82,6 +82,7 @@ BOOST_AUTO_TEST_CASE(buffer_8_a_8_access)
BOOST_CHECK_EQUAL((*b)[0], '\0'); BOOST_CHECK_EQUAL((*b)[0], '\0');
} }
#if 0
BOOST_AUTO_TEST_CASE(buffer_8_a_8_const_access) BOOST_AUTO_TEST_CASE(buffer_8_a_8_const_access)
{ {
uint32_t const sz = 8, align = 8; uint32_t const sz = 8, align = 8;
@ -89,6 +90,7 @@ BOOST_AUTO_TEST_CASE(buffer_8_a_8_const_access)
(*b)[0] = 0; // Compile time error accessing read-only location (*b)[0] = 0; // Compile time error accessing read-only location
} }
#endif
// 8 byte buffer size, varying alignment from 1 - 7 // 8 byte buffer size, varying alignment from 1 - 7
BOOST_AUTO_TEST_CASE(buffer_128_a_1_fails) BOOST_AUTO_TEST_CASE(buffer_128_a_1_fails)
@ -97,6 +99,7 @@ BOOST_AUTO_TEST_CASE(buffer_128_a_1_fails)
buffer<sz, align>::ptr b = create_buffer<sz, align>(); buffer<sz, align>::ptr b = create_buffer<sz, align>();
BOOST_CHECK(!b); BOOST_CHECK(!b);
BOOST_CHECK_EQUAL((unsigned long) b->raw() & (align - 1), 1);
} }
BOOST_AUTO_TEST_CASE(buffer_128_a_2_succeeds) BOOST_AUTO_TEST_CASE(buffer_128_a_2_succeeds)