summaryrefslogtreecommitdiff
path: root/Tests/AK/TestStdLibExtras.cpp
blob: af6f4c81e684690f6aa0b5b11aad9a5aaf55f52d (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
/*
 * Copyright (c) 2021, Tim Flynn <trflynn89@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibTest/TestSuite.h>

#include <AK/Optional.h>
#include <AK/StdLibExtras.h>
#include <AK/StringView.h>
#include <AK/Variant.h>
#include <AK/Vector.h>

TEST_CASE(mix)
{
    double a = 1.0;
    double b = 3.0;

    EXPECT_APPROXIMATE(mix(a, b, 0.0), 1.0);
    EXPECT_APPROXIMATE(mix(a, b, 0.5), 2.0);
    EXPECT_APPROXIMATE(mix(a, b, 1.0), 3.0);

    EXPECT_APPROXIMATE(mix(b, a, 0.0), 3.0);
    EXPECT_APPROXIMATE(mix(b, a, 0.5), 2.0);
    EXPECT_APPROXIMATE(mix(b, a, 1.0), 1.0);
}

TEST_CASE(swap)
{
    int i = 4;
    int j = 6;

    swap(i, j);

    EXPECT_EQ(i, 6);
    EXPECT_EQ(j, 4);
}

TEST_CASE(swap_same_value)
{

    int i = 4;
    swap(i, i);
    EXPECT_EQ(i, 4);
}

TEST_CASE(swap_same_complex_object)
{
    struct Type1 {
        StringView foo;
    };
    struct Type2 {
        Optional<Type1> foo;
        Vector<Type1> bar;
    };

    Variant<Type1, Type2> value1 { Type1 { "hello"sv } };
    Variant<Type1, Type2> value2 { Type2 { {}, { { "goodbye"sv } } } };

    swap(value1, value2);

    EXPECT(value1.has<Type2>());
    EXPECT(value2.has<Type1>());

    swap(value1, value1);

    EXPECT(value1.has<Type2>());
    EXPECT(value2.has<Type1>());
}