blob: 11569f22c7a11f8c3735d097daa684afbe1962a4 [file] [log] [blame]
Dominik Laskowskie6c5e6e2022-08-03 12:58:28 -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/algorithm.h>
18#include <ftl/small_map.h>
19#include <ftl/static_vector.h>
20#include <gtest/gtest.h>
21
22#include <string_view>
23
24namespace android::test {
25
26// Keep in sync with example usage in header file.
Lloyd Pique23550ef2024-05-01 17:00:22 -070027TEST(Algorithm, Contains) {
28 const ftl::StaticVector vector = {1, 2, 3};
29 EXPECT_TRUE(ftl::contains(vector, 1));
30
31 EXPECT_FALSE(ftl::contains(vector, 0));
32 EXPECT_TRUE(ftl::contains(vector, 2));
33 EXPECT_TRUE(ftl::contains(vector, 3));
34 EXPECT_FALSE(ftl::contains(vector, 4));
35}
36
37// Keep in sync with example usage in header file.
Dominik Laskowskie6c5e6e2022-08-03 12:58:28 -070038TEST(Algorithm, FindIf) {
39 using namespace std::string_view_literals;
40
41 const ftl::StaticVector vector = {"upside"sv, "down"sv, "cake"sv};
42 EXPECT_EQ(ftl::find_if(vector, [](const auto& str) { return str.front() == 'c'; }), "cake"sv);
43
44 const ftl::SmallMap map = ftl::init::map<int, ftl::StaticVector<std::string_view, 3>>(
45 12, "snow"sv, "cone"sv)(13, "tiramisu"sv)(14, "upside"sv, "down"sv, "cake"sv);
46
47 using Map = decltype(map);
48
49 EXPECT_EQ(14, ftl::find_if(map, [](const auto& pair) {
50 return pair.second.size() == 3;
51 }).transform(ftl::to_key<Map>));
52
53 const auto opt = ftl::find_if(map, [](const auto& pair) {
54 return pair.second.size() == 1;
55 }).transform(ftl::to_mapped_ref<Map>);
56
57 ASSERT_TRUE(opt);
58 EXPECT_EQ(opt->get(), ftl::StaticVector("tiramisu"sv));
59}
60
Dominik Laskowski80872bd2022-11-15 11:34:33 -050061TEST(Algorithm, StaticRef) {
62 using namespace std::string_view_literals;
63
64 const ftl::SmallMap map = ftl::init::map(13, "tiramisu"sv)(14, "upside-down cake"sv);
65 ASSERT_EQ("???"sv,
66 map.get(20).or_else(ftl::static_ref<std::string_view>([] { return "???"sv; }))->get());
67
68 using Map = decltype(map);
69
70 ASSERT_EQ("snow cone"sv,
71 ftl::find_if(map, [](const auto& pair) { return pair.second.front() == 's'; })
72 .transform(ftl::to_mapped_ref<Map>)
73 .or_else(ftl::static_ref<std::string_view>([] { return "snow cone"sv; }))
74 ->get());
75}
76
Dominik Laskowskie6c5e6e2022-08-03 12:58:28 -070077} // namespace android::test