Serenity Operating System
1/*
2 * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <LibTest/TestCase.h>
8#include <LibTest/TestSuite.h>
9
10#include <AK/FixedArray.h>
11#include <AK/NoAllocationGuard.h>
12
13TEST_CASE(construct)
14{
15 EXPECT_EQ(FixedArray<int>().size(), 0u);
16 EXPECT_EQ(FixedArray<int>::must_create_but_fixme_should_propagate_errors(1985).size(), 1985u);
17}
18
19TEST_CASE(ints)
20{
21 FixedArray<int> ints = FixedArray<int>::must_create_but_fixme_should_propagate_errors(3);
22 ints[0] = 0;
23 ints[1] = 1;
24 ints[2] = 2;
25 EXPECT_EQ(ints[0], 0);
26 EXPECT_EQ(ints[1], 1);
27 EXPECT_EQ(ints[2], 2);
28}
29
30TEST_CASE(swap)
31{
32 FixedArray<int> first = FixedArray<int>::must_create_but_fixme_should_propagate_errors(4);
33 FixedArray<int> second = FixedArray<int>::must_create_but_fixme_should_propagate_errors(5);
34 first[3] = 1;
35 second[3] = 2;
36 first.swap(second);
37 EXPECT_EQ(first.size(), 5u);
38 EXPECT_EQ(second.size(), 4u);
39 EXPECT_EQ(first[3], 2);
40 EXPECT_EQ(second[3], 1);
41}
42
43TEST_CASE(move)
44{
45 FixedArray<int> moved_from_array = FixedArray<int>::must_create_but_fixme_should_propagate_errors(6);
46 FixedArray<int> moved_to_array(move(moved_from_array));
47 EXPECT_EQ(moved_to_array.size(), 6u);
48 EXPECT_EQ(moved_from_array.size(), 0u);
49}
50
51TEST_CASE(no_allocation)
52{
53 FixedArray<int> array = FixedArray<int>::must_create_but_fixme_should_propagate_errors(5);
54 EXPECT_NO_CRASH("Assignments", [&] {
55 NoAllocationGuard guard;
56 array[0] = 0;
57 array[1] = 1;
58 array[2] = 2;
59 array[4] = array[1];
60 array[3] = array[0] + array[2];
61 return Test::Crash::Failure::DidNotCrash;
62 });
63
64 EXPECT_NO_CRASH("Move", [&] {
65 FixedArray<int> moved_from_array = FixedArray<int>::must_create_but_fixme_should_propagate_errors(6);
66 // We need an Optional here to ensure that the NoAllocationGuard is
67 // destroyed before the moved_to_array, because that would call free
68 Optional<FixedArray<int>> moved_to_array;
69
70 {
71 NoAllocationGuard guard;
72 moved_to_array.emplace(move(moved_from_array));
73 }
74
75 return Test::Crash::Failure::DidNotCrash;
76 });
77
78 EXPECT_NO_CRASH("Swap", [&] {
79 FixedArray<int> target_for_swapping;
80 {
81 NoAllocationGuard guard;
82 array.swap(target_for_swapping);
83 }
84 return Test::Crash::Failure::DidNotCrash;
85 });
86}