flexible_struct.cpp (1970B)
1 #include "libshit/flexible_struct.hpp" 2 3 #include "libshit/doctest.hpp" 4 #include "libshit/utils.hpp" 5 6 #include <vector> 7 8 namespace Libshit::Test 9 { 10 TEST_SUITE_BEGIN("Libshit::FlexibleStruct"); 11 12 namespace 13 { 14 struct DummyStruct 15 { 16 int x = 123; 17 constexpr DummyStruct() noexcept = default; 18 constexpr DummyStruct(int x) noexcept : x{x} {} 19 }; 20 using FlexPod = FlexibleStruct<DummyStruct, int>; 21 22 struct Counter 23 { 24 static inline int throw_after; 25 static inline int cnt = 0; 26 Counter() 27 { 28 if (throw_after == 0) throw 3; 29 --throw_after; 30 ++cnt; 31 } 32 ~Counter() noexcept { --cnt; } 33 34 Counter(Counter&&) = delete; 35 void operator=(Counter&&) = delete; 36 }; 37 using FlexCounter = FlexibleStruct<DummyStruct, Counter>; 38 } 39 40 TEST_CASE("Flexible Pod") 41 { 42 { 43 auto x = FlexPod::Create(5); 44 AtScopeExit y{[&]() { FlexPod::DestructArray(x, 5); delete x; }}; 45 CHECK(x->x == 123); 46 FlexPod::GetArray(x)[0] = 98; 47 FlexPod::GetArray(x)[4] = 0x11223344; 48 } 49 50 { 51 auto x = FlexPod::Create(5, 10); 52 AtScopeExit y{[&]() { FlexPod::DestructArray(x, 5); delete x; }}; 53 CHECK(x->x == 10); 54 } 55 56 { 57 std::vector<int> ary{13, 42, 20, 5, -3}; 58 auto x = FlexPod::Create(ary.begin(), ary.end(), 13); 59 AtScopeExit y{[&]() { FlexPod::DestructArray(x, 5); delete x; }}; 60 CHECK(x->x == 13); 61 auto fary = FlexPod::GetArray(x); 62 CHECK(std::vector<int>{fary, fary+5} == ary); 63 } 64 } 65 66 TEST_CASE("Flexible Counter") 67 { 68 { 69 Counter::throw_after = -1; 70 auto x = FlexCounter::Create(5); 71 AtScopeExit y{[&]() { FlexCounter::DestructArray(x, 5); delete x; }}; 72 CHECK(x->x == 123); 73 CHECK(Counter::cnt == 5); 74 } 75 CHECK(Counter::cnt == 0); 76 77 { 78 Counter::throw_after = 3; 79 CHECK_THROWS(FlexCounter::Create(10)); 80 CHECK(Counter::cnt == 0); 81 } 82 } 83 84 TEST_SUITE_END(); 85 }