blob: 7318c45b7b0c07220a0e188e9ca00564024799bd [file] [log] [blame]
Dominik Laskowskif2fdb562022-09-02 09:50:39 -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#pragma once
18
19#include <utility>
20#include <variant>
21
22#include <ftl/details/match.h>
23
24namespace android::ftl {
25
26// Concise alternative to std::visit that compiles to branches rather than a dispatch table. For
27// std::variant<T0, ..., TN> where N is small, this is slightly faster since the branches can be
28// inlined unlike the function pointers.
29//
30// using namespace std::chrono;
31// std::variant<seconds, minutes, hours> duration = 119min;
32//
33// // Mutable match.
34// ftl::match(duration, [](auto& d) { ++d; });
35//
36// // Immutable match. Exhaustive due to minutes being convertible to seconds.
37// assert("2 hours"s ==
38// ftl::match(duration,
39// [](const seconds& s) {
40// const auto h = duration_cast<hours>(s);
41// return std::to_string(h.count()) + " hours"s;
42// },
43// [](const hours& h) { return std::to_string(h.count() / 24) + " days"s; }));
44//
45template <typename... Ts, typename... Ms>
46decltype(auto) match(std::variant<Ts...>& variant, Ms&&... matchers) {
47 const auto matcher = details::Matcher{std::forward<Ms>(matchers)...};
48 static_assert(details::is_exhaustive_match_v<decltype(matcher), Ts&...>, "Non-exhaustive match");
49
50 return details::Match<Ts...>::match(variant, matcher);
51}
52
53template <typename... Ts, typename... Ms>
54decltype(auto) match(const std::variant<Ts...>& variant, Ms&&... matchers) {
55 const auto matcher = details::Matcher{std::forward<Ms>(matchers)...};
56 static_assert(details::is_exhaustive_match_v<decltype(matcher), const Ts&...>,
57 "Non-exhaustive match");
58
59 return details::Match<Ts...>::match(variant, matcher);
60}
61
62} // namespace android::ftl