blob: 62549a3f9d7b46c2cec99dccb81565064b3c5b63 [file] [log] [blame]
Dominik Laskowski54494bd2022-08-02 13:37:14 -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 <type_traits>
20#include <utility>
21
22namespace android::ftl {
23
24// The unit type, and its only value.
25constexpr struct Unit {
26} unit;
27
28constexpr bool operator==(Unit, Unit) {
29 return true;
30}
31
32constexpr bool operator!=(Unit, Unit) {
33 return false;
34}
35
36// Adapts a function object F to return Unit. The return value of F is ignored.
37//
38// As a practical use, the function passed to ftl::Optional<T>::transform is not allowed to return
39// void (cf. https://wg21.link/P0798R8#mapping-functions-returning-void), but may return Unit if
40// only its side effects are meaningful:
41//
42// ftl::Optional opt = "food"s;
43// opt.transform(ftl::unit_fn([](std::string& str) { str.pop_back(); }));
44// assert(opt == "foo"s);
45//
46template <typename F>
47struct UnitFn {
48 F f;
49
50 template <typename... Args>
51 Unit operator()(Args&&... args) {
52 return f(std::forward<Args>(args)...), unit;
53 }
54};
55
56template <typename F>
57constexpr auto unit_fn(F&& f) -> UnitFn<std::decay_t<F>> {
58 return {std::forward<F>(f)};
59}
60
Dominik Laskowski189d1822024-05-03 17:30:26 -040061namespace details {
62
63// Identity function for all T except Unit, which maps to void.
64template <typename T>
65struct UnitToVoid {
66 template <typename U>
67 static auto from(U&& value) {
68 return value;
69 }
70};
71
72template <>
73struct UnitToVoid<Unit> {
74 template <typename U>
75 static void from(U&&) {}
76};
77
78} // namespace details
Dominik Laskowski54494bd2022-08-02 13:37:14 -070079} // namespace android::ftl