|
| 1 | +#include "test.h" |
| 2 | +#include <libvisual/libvisual.h> |
| 3 | +#include <libvisual/lv_aligned_allocator.hpp> |
| 4 | +#include <string> |
| 5 | +#include <vector> |
| 6 | +#include <cstdint> |
| 7 | + |
| 8 | +namespace |
| 9 | +{ |
| 10 | + inline bool ptr_is_aligned (void* ptr, std::size_t alignment) |
| 11 | + { |
| 12 | + return (reinterpret_cast<std::intptr_t> (ptr) % alignment) == 0; |
| 13 | + } |
| 14 | + |
| 15 | + void test_allocation () |
| 16 | + { |
| 17 | + std::array<std::size_t, 6> constexpr alignments { 4, 8, 16, 32, 64, 128 }; |
| 18 | + |
| 19 | + for (auto alignment = alignments.begin (); alignment != alignments.end(); ++alignment) { |
| 20 | + std::size_t const test_block_size = *alignment * 2 + 1; |
| 21 | + |
| 22 | + void* ptr = visual_mem_malloc_aligned (test_block_size, *alignment); |
| 23 | + LV_TEST_ASSERT (ptr_is_aligned (ptr, *alignment)); |
| 24 | + |
| 25 | + visual_mem_free_aligned (ptr); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + template <std::size_t alignment> |
| 30 | + void test_cxx_allocator () |
| 31 | + { |
| 32 | + constexpr size_t test_count = 3; |
| 33 | + |
| 34 | + LV::AlignedAllocator<alignment, std::string> allocator; |
| 35 | + using allocator_traits = std::allocator_traits<decltype(allocator)>; |
| 36 | + |
| 37 | + std::string* strings = allocator_traits::allocate (allocator, test_count); |
| 38 | + |
| 39 | + LV_TEST_ASSERT (ptr_is_aligned (strings, alignment)); |
| 40 | + |
| 41 | + allocator_traits::deallocate (allocator, strings, test_count); |
| 42 | + } |
| 43 | + |
| 44 | + void test_cxx_allocators () |
| 45 | + { |
| 46 | + test_cxx_allocator<4> (); |
| 47 | + test_cxx_allocator<8> (); |
| 48 | + test_cxx_allocator<16> (); |
| 49 | + test_cxx_allocator<32> (); |
| 50 | + test_cxx_allocator<64> (); |
| 51 | + test_cxx_allocator<128> (); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +int main (int argc, char* argv[]) |
| 56 | +{ |
| 57 | + LV::System::init (argc, argv); |
| 58 | + |
| 59 | + test_allocation (); |
| 60 | + test_cxx_allocators (); |
| 61 | + |
| 62 | + LV::System::destroy (); |
| 63 | +} |
0 commit comments