You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
libshit/test/flexible_struct.cpp

86 lines
1.9 KiB
C++

#include "libshit/flexible_struct.hpp"
#include "libshit/doctest.hpp"
#include "libshit/utils.hpp"
#include <vector>
namespace Libshit::Test
{
TEST_SUITE_BEGIN("Libshit::FlexibleStruct");
namespace
{
struct DummyStruct
{
int x = 123;
constexpr DummyStruct() noexcept = default;
constexpr DummyStruct(int x) noexcept : x{x} {}
};
using FlexPod = FlexibleStruct<DummyStruct, int>;
struct Counter
{
static inline int throw_after;
static inline int cnt = 0;
Counter()
{
if (throw_after == 0) throw 3;
--throw_after;
++cnt;
}
~Counter() noexcept { --cnt; }
Counter(Counter&&) = delete;
void operator=(Counter&&) = delete;
};
using FlexCounter = FlexibleStruct<DummyStruct, Counter>;
}
TEST_CASE("Flexible Pod")
{
{
auto x = FlexPod::Create(5);
AtScopeExit y{[&]() { FlexPod::DestructArray(x, 5); delete x; }};
CHECK(x->x == 123);
FlexPod::GetArray(x)[0] = 98;
FlexPod::GetArray(x)[4] = 0x11223344;
}
{
auto x = FlexPod::Create(5, 10);
AtScopeExit y{[&]() { FlexPod::DestructArray(x, 5); delete x; }};
CHECK(x->x == 10);
}
{
std::vector<int> ary{13, 42, 20, 5, -3};
auto x = FlexPod::Create(ary.begin(), ary.end(), 13);
AtScopeExit y{[&]() { FlexPod::DestructArray(x, 5); delete x; }};
CHECK(x->x == 13);
auto fary = FlexPod::GetArray(x);
CHECK(std::vector<int>{fary, fary+5} == ary);
}
}
TEST_CASE("Flexible Counter")
{
{
Counter::throw_after = -1;
auto x = FlexCounter::Create(5);
AtScopeExit y{[&]() { FlexCounter::DestructArray(x, 5); delete x; }};
CHECK(x->x == 123);
CHECK(Counter::cnt == 5);
}
CHECK(Counter::cnt == 0);
{
Counter::throw_after = 3;
CHECK_THROWS(FlexCounter::Create(10));
CHECK(Counter::cnt == 0);
}
}
TEST_SUITE_END();
}