1 /*
2  * Copyright 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <ftl/expected.h>
18 #include <ftl/optional.h>
19 #include <ftl/static_vector.h>
20 #include <ftl/string.h>
21 #include <ftl/unit.h>
22 #include <gtest/gtest.h>
23 
24 #include <cstdlib>
25 #include <functional>
26 #include <numeric>
27 #include <system_error>
28 #include <utility>
29 
30 using namespace std::placeholders;
31 using namespace std::string_literals;
32 
33 namespace android::test {
34 
35 using ftl::Optional;
36 using ftl::StaticVector;
37 
TEST(Optional,Construct)38 TEST(Optional, Construct) {
39   // Empty.
40   EXPECT_EQ(std::nullopt, Optional<int>());
41   EXPECT_EQ(std::nullopt, Optional<std::string>(std::nullopt));
42 
43   // Value.
44   EXPECT_EQ('?', Optional('?'));
45   EXPECT_EQ(""s, Optional(std::string()));
46 
47   // In place.
48   EXPECT_EQ("???"s, Optional<std::string>(std::in_place, 3u, '?'));
49   EXPECT_EQ("abc"s, Optional<std::string>(std::in_place, {'a', 'b', 'c'}));
50 
51   // Implicit downcast.
52   {
53     Optional opt = std::optional("test"s);
54     static_assert(std::is_same_v<decltype(opt), Optional<std::string>>);
55 
56     ASSERT_TRUE(opt);
57     EXPECT_EQ(opt.value(), "test"s);
58   }
59 }
60 
TEST(Optional,Transform)61 TEST(Optional, Transform) {
62   // Empty.
63   EXPECT_EQ(std::nullopt, Optional<int>().transform([](int) { return 0; }));
64 
65   // By value.
66   EXPECT_EQ(0, Optional(0).transform([](int x) { return x; }));
67   EXPECT_EQ(100, Optional(99).transform([](int x) { return x + 1; }));
68   EXPECT_EQ("0b100"s, Optional(4).transform(std::bind(ftl::to_string<int>, _1, ftl::Radix::kBin)));
69 
70   // By reference.
71   {
72     Optional opt = 'x';
73     EXPECT_EQ('z', opt.transform([](char& c) {
74       c = 'y';
75       return 'z';
76     }));
77 
78     EXPECT_EQ('y', opt);
79   }
80 
81   // By rvalue reference.
82   {
83     std::string out;
84     EXPECT_EQ("xyz"s, Optional("abc"s).transform([&out](std::string&& str) {
85       out = std::move(str);
86       return "xyz"s;
87     }));
88 
89     EXPECT_EQ(out, "abc"s);
90   }
91 
92   // No return value.
93   {
94     Optional opt = "food"s;
95     EXPECT_EQ(ftl::unit, opt.transform(ftl::unit_fn([](std::string& str) { str.pop_back(); })));
96     EXPECT_EQ(opt, "foo"s);
97   }
98 
99   // Chaining.
100   EXPECT_EQ(14u, Optional(StaticVector{"upside"s, "down"s})
101                      .transform([](StaticVector<std::string, 3>&& v) {
102                        v.push_back("cake"s);
103                        return v;
104                      })
105                      .transform([](const StaticVector<std::string, 3>& v) {
106                        return std::accumulate(v.begin(), v.end(), std::string());
107                      })
108                      .transform([](const std::string& s) { return s.length(); }));
109 }
110 
111 namespace {
112 
parse_int(const std::string & str)113 Optional<int> parse_int(const std::string& str) {
114   if (const int i = std::atoi(str.c_str())) return i;
115   return std::nullopt;
116 }
117 
118 }  // namespace
119 
TEST(Optional,AndThen)120 TEST(Optional, AndThen) {
121   // Empty.
122   EXPECT_EQ(std::nullopt, Optional<int>().and_then([](int) -> Optional<int> { return 0; }));
123   EXPECT_EQ(std::nullopt, Optional<int>().and_then([](int) { return Optional<int>(); }));
124 
125   // By value.
126   EXPECT_EQ(0, Optional(0).and_then([](int x) { return Optional(x); }));
127   EXPECT_EQ(123, Optional("123").and_then(parse_int));
128   EXPECT_EQ(std::nullopt, Optional("abc").and_then(parse_int));
129 
130   // By reference.
131   {
132     Optional opt = 'x';
133     EXPECT_EQ('z', opt.and_then([](char& c) {
134       c = 'y';
135       return Optional('z');
136     }));
137 
138     EXPECT_EQ('y', opt);
139   }
140 
141   // By rvalue reference.
142   {
143     std::string out;
144     EXPECT_EQ("xyz"s, Optional("abc"s).and_then([&out](std::string&& str) {
145       out = std::move(str);
146       return Optional("xyz"s);
147     }));
148 
149     EXPECT_EQ(out, "abc"s);
150   }
151 
152   // Chaining.
153   using StringVector = StaticVector<std::string, 3>;
154   EXPECT_EQ(14u, Optional(StaticVector{"-"s, "1"s})
155                      .and_then([](StringVector&& v) -> Optional<StringVector> {
156                        if (v.push_back("4"s)) return v;
157                        return {};
158                      })
159                      .and_then([](const StringVector& v) -> Optional<std::string> {
160                        if (v.full()) return std::accumulate(v.begin(), v.end(), std::string());
161                        return {};
162                      })
163                      .and_then(parse_int)
164                      .and_then([](int i) {
165                        return i > 0 ? std::nullopt : std::make_optional(static_cast<unsigned>(-i));
166                      }));
167 }
168 
TEST(Optional,OrElse)169 TEST(Optional, OrElse) {
170   // Non-empty.
171   {
172     const Optional opt = false;
173     EXPECT_EQ(false, opt.or_else([] { return Optional(true); }));
174     EXPECT_EQ('x', Optional('x').or_else([] { return std::make_optional('y'); }));
175   }
176 
177   // Empty.
178   {
179     const Optional<int> opt;
180     EXPECT_EQ(123, opt.or_else([]() -> Optional<int> { return 123; }));
181     EXPECT_EQ("abc"s, Optional<std::string>().or_else([] { return Optional("abc"s); }));
182   }
183   {
184     bool empty = false;
185     EXPECT_EQ(Optional<float>(), Optional<float>().or_else([&empty]() -> Optional<float> {
186       empty = true;
187       return std::nullopt;
188     }));
189     EXPECT_TRUE(empty);
190   }
191 
192   // Chaining.
193   using StringVector = StaticVector<std::string, 3>;
194   EXPECT_EQ(999, Optional(StaticVector{"1"s, "0"s, "0"s})
195                      .and_then([](StringVector&& v) -> Optional<StringVector> {
196                        if (v.push_back("0"s)) return v;
197                        return {};
198                      })
199                      .or_else([] {
200                        return Optional(StaticVector{"9"s, "9"s, "9"s});
201                      })
202                      .transform([](const StringVector& v) {
203                        return std::accumulate(v.begin(), v.end(), std::string());
204                      })
205                      .and_then(parse_int)
206                      .or_else([] { return Optional(-1); }));
207 }
208 
TEST(Optional,OkOr)209 TEST(Optional, OkOr) {
210   using CharExp = ftl::Expected<char, std::errc>;
211   using StringExp = ftl::Expected<std::string, std::errc>;
212 
213   EXPECT_EQ(CharExp('z'), Optional('z').ok_or(std::errc::broken_pipe));
214   EXPECT_EQ(CharExp(ftl::Unexpected(std::errc::broken_pipe)),
215             Optional<char>().ok_or(std::errc::broken_pipe));
216 
217   EXPECT_EQ(StringExp("abc"s), Optional("abc"s).ok_or(std::errc::protocol_error));
218   EXPECT_EQ(StringExp(ftl::Unexpected(std::errc::protocol_error)),
219             Optional<std::string>().ok_or(std::errc::protocol_error));
220 }
221 
222 // Comparison.
223 namespace {
224 
225 constexpr Optional<int> kOptional1 = 1;
226 constexpr Optional<int> kAnotherOptional1 = 1;
227 constexpr Optional<int> kOptional2 = 2;
228 constexpr Optional<int> kOptionalEmpty, kAnotherOptionalEmpty;
229 
230 constexpr std::optional<int> kStdOptional1 = 1;
231 
232 static_assert(kOptional1 == kAnotherOptional1);
233 
234 static_assert(kOptional1 != kOptional2);
235 static_assert(kOptional2 != kOptional1);
236 
237 static_assert(kOptional1 != kOptionalEmpty);
238 static_assert(kOptionalEmpty != kOptional1);
239 
240 static_assert(kOptionalEmpty == kAnotherOptionalEmpty);
241 
242 static_assert(kOptional1 == kStdOptional1);
243 static_assert(kStdOptional1 == kOptional1);
244 
245 static_assert(kOptional2 != kStdOptional1);
246 static_assert(kStdOptional1 != kOptional2);
247 
248 static_assert(kOptional2 != kOptionalEmpty);
249 static_assert(kOptionalEmpty != kOptional2);
250 
251 } // namespace
252 
253 }  // namespace android::test
254