summaryrefslogtreecommitdiff
path: root/asl/tests/box_tests.cpp
blob: 3faf121e7c37ccebaa4bf12173a34a7384b95e5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "asl/box.hpp"
#include "asl/option.hpp"

#include "asl/testing/testing.hpp"
#include "asl/tests/test_types.hpp"

static_assert(sizeof(asl::box<int>) == sizeof(int*));
static_assert(!asl::copyable<asl::box<int>>);
static_assert(asl::moveable<asl::box<int>>);
static_assert(asl::has_niche<asl::box<int>>);
static_assert(sizeof(asl::option<asl::box<int>>) == sizeof(int*));

ASL_TEST(destructor)
{
    bool d = false;

    {
        auto box = asl::make_box<DestructorObserver>(&d);
        ASL_TEST_ASSERT(!d);


        auto box3 = ASL_MOVE(box);
        ASL_TEST_ASSERT(!d);
    }

    ASL_TEST_ASSERT(d);
}

ASL_TEST(value)
{
    auto b = asl::make_box<int>(24);
    ASL_TEST_EXPECT(*b == 24);

    auto b2 = ASL_MOVE(b);
    ASL_TEST_EXPECT(*b2 == 24);
}

ASL_TEST(ptr)
{
    auto b = asl::make_box<int>(24);
    auto* ptr1 = b.get();

    auto b2 = ASL_MOVE(b);
    auto* ptr2 = b2.get();
    ASL_TEST_EXPECT(ptr1 == ptr2);
}

struct Struct { int a; };

ASL_TEST(arrow)
{
    auto b = asl::make_box<Struct>(45);
    ASL_TEST_EXPECT(b->a == 45);
}

ASL_TEST(niche)
{
    static_assert(sizeof(asl::box<int>) == sizeof(asl::option<asl::box<int>>));

    asl::option<asl::box<int>> opt;
    ASL_TEST_EXPECT(!opt.has_value());

    opt = asl::make_box<int>(66);
    ASL_TEST_EXPECT(opt.has_value());
    ASL_TEST_EXPECT(*opt.value() == 66);

    opt = asl::nullopt;
    ASL_TEST_EXPECT(!opt.has_value());

    bool destroyed = false;
    asl::option opt2 = asl::make_box<DestructorObserver>(&destroyed);
    ASL_TEST_EXPECT(opt2.has_value());
    ASL_TEST_EXPECT(!destroyed);

    opt2.reset();
    ASL_TEST_EXPECT(!opt2.has_value());
    ASL_TEST_EXPECT(destroyed);
}

class Base
{
public:
    virtual ~Base() = default;
    virtual int number() { return 1; }
};

class Derived : public Base
{
public:
    int number() override { return 2; }
};

static_assert(asl::convertible_from<asl::box<Base>, asl::box<Derived>>);
static_assert(asl::convertible_from<asl::box<Base>, asl::box<Base>>);
static_assert(!asl::convertible_from<asl::box<Derived>, asl::box<Base>>);
static_assert(!asl::convertible_from<asl::box<int>, asl::box<float>>);

ASL_TEST(derived)
{
    asl::box<Base> obj = asl::make_box<Derived>();
    ASL_TEST_ASSERT(obj->number() == 2);
}