1 //===-- Unittests for Optional --------------------------------------------===//
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
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.
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);
36 ASSERT_FALSE(Trivial1
.has_value());
38 optional
<int> Trivial2(12);
39 ASSERT_TRUE(Trivial2
.has_value());
41 ASSERT_FALSE(Trivial2
.has_value());
43 // For this test case, the destructor increments the pointed-to value.
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.
50 ASSERT_EQ(holding
, 3);
51 // Destructor was not run a third time as the object is already destroyed.
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());
69 optional
<Contrived
> arrow_test(&arrow_num
);
70 ASSERT_TRUE(arrow_test
.has_value());
71 ASSERT_EQ(arrow_test
->get_a(), arrow_num
);
73 ASSERT_EQ(arrow_test
->get_a(), arrow_num
);
75 ASSERT_EQ(arrow_test
->get_a(), arrow_num
);
76 ASSERT_EQ(arrow_num
, 11);