blob: ede159a955fd3f5bd9e825faef3046cae26e3e52 [file] [log] [blame]
Dominik Laskowskia7e22552022-08-01 08:23:34 -07001/*
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/optional.h>
18#include <ftl/static_vector.h>
19#include <ftl/string.h>
Dominik Laskowski54494bd2022-08-02 13:37:14 -070020#include <ftl/unit.h>
Dominik Laskowskia7e22552022-08-01 08:23:34 -070021#include <gtest/gtest.h>
22
23#include <functional>
24#include <numeric>
25#include <utility>
26
27using namespace std::placeholders;
28using namespace std::string_literals;
29
30namespace android::test {
31
32using ftl::Optional;
33using ftl::StaticVector;
34
35TEST(Optional, Transform) {
36 // Empty.
37 EXPECT_EQ(std::nullopt, Optional<int>().transform([](int) { return 0; }));
38
39 // By value.
40 EXPECT_EQ(0, Optional(0).transform([](int x) { return x; }));
41 EXPECT_EQ(100, Optional(99).transform([](int x) { return x + 1; }));
42 EXPECT_EQ("0b100"s, Optional(4).transform(std::bind(ftl::to_string<int>, _1, ftl::Radix::kBin)));
43
44 // By reference.
45 {
46 Optional opt = 'x';
47 EXPECT_EQ('z', opt.transform([](char& c) {
48 c = 'y';
49 return 'z';
50 }));
51
52 EXPECT_EQ('y', opt);
53 }
54
55 // By rvalue reference.
56 {
57 std::string out;
58 EXPECT_EQ("xyz"s, Optional("abc"s).transform([&out](std::string&& str) {
59 out = std::move(str);
60 return "xyz"s;
61 }));
62
63 EXPECT_EQ(out, "abc"s);
64 }
65
Dominik Laskowski54494bd2022-08-02 13:37:14 -070066 // No return value.
67 {
68 Optional opt = "food"s;
69 EXPECT_EQ(ftl::unit, opt.transform(ftl::unit_fn([](std::string& str) { str.pop_back(); })));
70 EXPECT_EQ(opt, "foo"s);
71 }
72
Dominik Laskowskia7e22552022-08-01 08:23:34 -070073 // Chaining.
74 EXPECT_EQ(14u, Optional(StaticVector{"upside"s, "down"s})
75 .transform([](StaticVector<std::string, 3>&& v) {
76 v.push_back("cake"s);
77 return v;
78 })
79 .transform([](const StaticVector<std::string, 3>& v) {
80 return std::accumulate(v.begin(), v.end(), std::string());
81 })
82 .transform([](const std::string& s) { return s.length(); }));
83}
84
85} // namespace android::test