Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libc / test / src / __support / CPP / optional_test.cpp
blobf9254d42c9a9ea838f916f09048c99a01167e9ec
1 //===-- Unittests for Optional --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "src/__support/CPP/optional.h"
10 #include "test/UnitTest/Test.h"
12 using LIBC_NAMESPACE::cpp::nullopt;
13 using LIBC_NAMESPACE::cpp::optional;
15 // This class has three properties for testing:
16 // 1) No default constructor.
17 // 2) A non-trivial destructor with an observable side-effect.
18 // 3) Functions that can be called explicitly.
19 class Contrived {
20 int *_a;
22 public:
23 Contrived(int *a) : _a(a) {}
24 ~Contrived() { (*_a)++; }
26 int get_a() { return *_a; }
27 void inc_a() { (*_a)++; }
30 TEST(LlvmLibcOptionalTest, Tests) {
31 optional<int> Trivial1(12);
32 ASSERT_TRUE(Trivial1.has_value());
33 ASSERT_EQ(Trivial1.value(), 12);
34 ASSERT_EQ(*Trivial1, 12);
35 Trivial1.reset();
36 ASSERT_FALSE(Trivial1.has_value());
38 optional<int> Trivial2(12);
39 ASSERT_TRUE(Trivial2.has_value());
40 Trivial2 = nullopt;
41 ASSERT_FALSE(Trivial2.has_value());
43 // For this test case, the destructor increments the pointed-to value.
44 int holding = 1;
45 optional<Contrived> Complicated(&holding);
46 // Destructor was run once as part of copying the object.
47 ASSERT_EQ(holding, 2);
48 // Destructor was run a second time as part of destruction.
49 Complicated.reset();
50 ASSERT_EQ(holding, 3);
51 // Destructor was not run a third time as the object is already destroyed.
52 Complicated.reset();
53 ASSERT_EQ(holding, 3);
55 // Test that assigning an optional to another works when set
56 optional<int> Trivial3(12);
57 optional<int> Trivial4 = Trivial3;
58 ASSERT_TRUE(Trivial4.has_value());
59 ASSERT_EQ(Trivial4.value(), 12);
61 // Test that assigning an option to another works when unset
62 optional<int> Trivial5;
63 ASSERT_FALSE(Trivial5.has_value());
64 optional<int> Trivial6 = Trivial5;
65 ASSERT_FALSE(Trivial6.has_value());
67 // Test operator->
68 int arrow_num = 5;
69 optional<Contrived> arrow_test(&arrow_num);
70 ASSERT_TRUE(arrow_test.has_value());
71 ASSERT_EQ(arrow_test->get_a(), arrow_num);
72 arrow_num = 10;
73 ASSERT_EQ(arrow_test->get_a(), arrow_num);
74 arrow_test->inc_a();
75 ASSERT_EQ(arrow_test->get_a(), arrow_num);
76 ASSERT_EQ(arrow_num, 11);
77 arrow_test.reset();