]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/rust/util/rust-optional-test.cc
Update copyright years.
[thirdparty/gcc.git] / gcc / rust / util / rust-optional-test.cc
1 // Copyright (C) 2020-2024 Free Software Foundation, Inc.
2
3 // This file is part of GCC.
4
5 // GCC is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 3, or (at your option) any later
8 // version.
9
10 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 // for more details.
14
15 // You should have received a copy of the GNU General Public License
16 // along with GCC; see the file COPYING3. If not see
17 // <http://www.gnu.org/licenses/>.
18
19 #include "rust-system.h"
20 #include "rust-optional.h"
21 #include "selftest.h"
22
23 #if CHECKING_P
24
25 static void
26 rust_optional_create ()
27 {
28 auto opt = Rust::Optional<int>::some (15);
29
30 ASSERT_TRUE (opt.is_some ());
31 ASSERT_EQ (opt.get (), 15);
32
33 Rust::Optional<int> const_opt = Rust::Optional<int>::some (15);
34 const int &value = const_opt.get ();
35
36 ASSERT_EQ (value, 15);
37 }
38
39 static void
40 rust_optional_operators ()
41 {
42 auto opt = Rust::Optional<int>::some (15);
43
44 // as bool
45 ASSERT_TRUE (opt);
46
47 // deref
48 ASSERT_EQ (*opt, 15);
49
50 class Methodable
51 {
52 public:
53 int method () { return 15; }
54 };
55
56 auto m_opt = Rust::Optional<Methodable>::some (Methodable ());
57 ASSERT_EQ (m_opt->method (), 15);
58 }
59
60 static void
61 rust_optional_take ()
62 {
63 auto opt = Rust::Optional<int>::some (15);
64 auto value = opt.take ();
65
66 ASSERT_EQ (value, 15);
67 ASSERT_TRUE (opt.is_none ());
68 }
69
70 static void
71 rust_optional_map ()
72 {
73 auto opt = Rust::Optional<int>::some (15);
74 auto twice = opt.map<int> ([] (int value) { return value * 2; });
75
76 ASSERT_FALSE (opt);
77 ASSERT_TRUE (twice);
78 ASSERT_EQ (*twice, 30);
79 }
80
81 static void
82 rust_optional_reference ()
83 {
84 auto value = std::vector<std::string> ();
85 value.emplace_back ("rust");
86 value.emplace_back ("+");
87 value.emplace_back ("gcc");
88 value.emplace_back ("=");
89 value.emplace_back ("<3");
90
91 auto opt = Rust::Optional<std::vector<std::string> &>::some (value);
92
93 ASSERT_EQ (opt->at (0), "rust");
94 ASSERT_EQ (opt->at (2), "gcc");
95 }
96
97 #endif /* #if CHECKING_P */
98
99 void
100 rust_optional_test ()
101 {
102 #if CHECKING_P
103 rust_optional_create ();
104 rust_optional_operators ();
105 rust_optional_take ();
106 rust_optional_map ();
107 rust_optional_reference ();
108
109 #endif /* #if CHECKING_P */
110 }