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