Coverage Report

Created: 2026-06-07 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/sentencepiece/third_party/absl/functional/any_invocable.h
Line
Count
Source
1
// Copyright 2022 The Abseil Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
//
15
// -----------------------------------------------------------------------------
16
// File: any_invocable.h
17
// -----------------------------------------------------------------------------
18
//
19
// This header file defines an `absl::AnyInvocable` type that assumes ownership
20
// and wraps an object of an invocable type. (Invocable types adhere to the
21
// concept specified in https://en.cppreference.com/w/cpp/concepts/invocable.)
22
//
23
// In general, prefer `absl::AnyInvocable` when you need a type-erased
24
// function parameter that needs to take ownership of the type.
25
//
26
// NOTE: `absl::AnyInvocable` is similar to the C++23 `std::move_only_function`
27
// abstraction, but has a slightly different API and is not designed to be a
28
// drop-in replacement or backfill of that type.
29
//
30
// Credits to Matt Calabrese (https://github.com/mattcalabrese) for the original
31
// implementation.
32
33
#ifndef ABSL_FUNCTIONAL_ANY_INVOCABLE_H_
34
#define ABSL_FUNCTIONAL_ANY_INVOCABLE_H_
35
36
#include <cstddef>
37
#include <functional>
38
#include <initializer_list>
39
#include <type_traits>
40
#include <utility>
41
42
#include "absl/base/attributes.h"
43
#include "absl/base/config.h"
44
#include "absl/base/nullability.h"
45
#include "absl/functional/internal/any_invocable.h"
46
#include "absl/meta/type_traits.h"
47
#include "absl/utility/utility.h"
48
49
namespace absl {
50
ABSL_NAMESPACE_BEGIN
51
52
// absl::AnyInvocable
53
//
54
// `absl::AnyInvocable` is a functional wrapper type, like `std::function`, that
55
// assumes ownership of an invocable object. Unlike `std::function`, an
56
// `absl::AnyInvocable` is more type-safe and provides the following additional
57
// benefits:
58
//
59
// * Properly adheres to const correctness of the underlying type
60
// * Is move-only so avoids concurrency problems with copied invocables and
61
//   unnecessary copies in general.
62
// * Supports reference qualifiers allowing it to perform unique actions (noted
63
//   below).
64
//
65
// `absl::AnyInvocable` is a template, and an `absl::AnyInvocable` instantiation
66
// may wrap any invocable object with a compatible function signature, e.g.
67
// having arguments and return types convertible to types matching the
68
// `absl::AnyInvocable` signature, and also matching any stated reference
69
// qualifiers, as long as that type is moveable. It therefore provides broad
70
// type erasure for functional objects.
71
//
72
// An `absl::AnyInvocable` is typically used as a type-erased function parameter
73
// for accepting various functional objects:
74
//
75
// // Define a function taking an AnyInvocable parameter.
76
// void my_func(absl::AnyInvocable<int()> f) {
77
//   ...
78
// };
79
//
80
// // That function can accept any invocable type:
81
//
82
// // Accept a function reference. We don't need to move a reference.
83
// int func1() { return 0; };
84
// my_func(func1);
85
//
86
// // Accept a lambda. We use std::move here because otherwise my_func would
87
// // copy the lambda.
88
// auto lambda = []() { return 0; };
89
// my_func(std::move(lambda));
90
//
91
// // Accept a function pointer. We don't need to move a function pointer.
92
// func2 = &func1;
93
// my_func(func2);
94
//
95
// // Accept an std::function by moving it. Note that the lambda is copyable
96
// // (satisfying std::function requirements) and moveable (satisfying
97
// // absl::AnyInvocable requirements).
98
// std::function<int()> func6 = []() { return 0; };
99
// my_func(std::move(func6));
100
//
101
// `AnyInvocable` also properly respects `const` qualifiers, reference
102
// qualifiers, and the `noexcept` specification  as part of the user-specified
103
// function type (e.g. `AnyInvocable<void() const && noexcept>`). These
104
// qualifiers will be applied to the `AnyInvocable` object's `operator()`, and
105
// the underlying invocable must be compatible with those qualifiers.
106
//
107
// Comparison of const and non-const function types:
108
//
109
//   // Store a closure inside of `func` with the function type `int()`.
110
//   // Note that we have made `func` itself `const`.
111
//   const AnyInvocable<int()> func = [](){ return 0; };
112
//
113
//   func();  // Compile-error: the passed type `int()` isn't `const`.
114
//
115
//   // Store a closure inside of `const_func` with the function type
116
//   // `int() const`.
117
//   // Note that we have also made `const_func` itself `const`.
118
//   const AnyInvocable<int() const> const_func = [](){ return 0; };
119
//
120
//   const_func();  // Fine: `int() const` is `const`.
121
//
122
// In the above example, the call `func()` would have compiled if
123
// `std::function` were used even though the types are not const compatible.
124
// This is a bug, and using `absl::AnyInvocable` properly detects that bug.
125
//
126
// In addition to affecting the signature of `operator()`, the `const` and
127
// reference qualifiers of the function type also appropriately constrain which
128
// kinds of invocable objects you are allowed to place into the `AnyInvocable`
129
// instance. If you specify a function type that is const-qualified, then
130
// anything that you attempt to put into the `AnyInvocable` must be callable on
131
// a `const` instance of that type.
132
//
133
// Constraint example:
134
//
135
//   // Fine because the lambda is callable when `const`.
136
//   AnyInvocable<int() const> func = [=](){ return 0; };
137
//
138
//   // This is a compile-error because the lambda isn't callable when `const`.
139
//   AnyInvocable<int() const> error = [=]() mutable { return 0; };
140
//
141
// An `&&` qualifier can be used to express that an `absl::AnyInvocable`
142
// instance should be invoked at most once:
143
//
144
//   // Invokes `continuation` with the logical result of an operation when
145
//   // that operation completes (common in asynchronous code).
146
//   void CallOnCompletion(AnyInvocable<void(int)&&> continuation) {
147
//     int result_of_foo = foo();
148
//
149
//     // `std::move` is required because the `operator()` of `continuation` is
150
//     // rvalue-reference qualified.
151
//     std::move(continuation)(result_of_foo);
152
//   }
153
//
154
// Attempting to call `absl::AnyInvocable` multiple times in such a case
155
// results in undefined behavior.
156
//
157
// Invoking an empty `absl::AnyInvocable` results in undefined behavior:
158
//
159
//   // Create an empty instance using the default constructor.
160
//   AnyInvocable<void()> empty;
161
//   empty();  // WARNING: Undefined behavior!
162
template <class Sig>
163
class ABSL_NULLABILITY_COMPATIBLE ABSL_ATTRIBUTE_OWNER AnyInvocable
164
    : private internal_any_invocable::Impl<Sig> {
165
 private:
166
  static_assert(
167
      std::is_function<Sig>::value,
168
      "The template argument of AnyInvocable must be a function type.");
169
170
  using Impl = internal_any_invocable::Impl<Sig>;
171
172
 public:
173
  // The return type of Sig
174
  using result_type = typename Impl::result_type;
175
  using absl_internal_is_view = std::false_type;
176
177
  // Constructors
178
179
  // Constructs the `AnyInvocable` in an empty state.
180
  // Invoking it results in undefined behavior.
181
102k
  AnyInvocable() noexcept = default;
182
51.1k
  AnyInvocable(std::nullptr_t) noexcept {}  // NOLINT
183
184
  // Constructs the `AnyInvocable` from an existing `AnyInvocable` by a move.
185
  // Note that `f` is not guaranteed to be empty after move-construction,
186
  // although it may be.
187
102k
  AnyInvocable(AnyInvocable&& /*f*/) noexcept = default;
188
189
  // Constructs an `AnyInvocable` from an invocable object.
190
  //
191
  // Upon construction, `*this` is only empty if `f` is a function pointer or
192
  // member pointer type and is null, or if `f` is an `AnyInvocable` that is
193
  // empty.
194
  template <class F, typename = absl::enable_if_t<
195
                         internal_any_invocable::CanConvert<Sig, F>::value>>
196
  AnyInvocable(F&& f)  // NOLINT
197
51.1k
      : Impl(internal_any_invocable::ConversionConstruct(),
198
51.1k
             std::forward<F>(f)) {}
199
200
  // Constructs an `AnyInvocable` that holds an invocable object of type `T`,
201
  // which is constructed in-place from the given arguments.
202
  //
203
  // Example:
204
  //
205
  //   AnyInvocable<int(int)> func(
206
  //       absl::in_place_type<PossiblyImmovableType>, arg1, arg2);
207
  //
208
  template <class T, class... Args,
209
            typename = absl::enable_if_t<
210
                internal_any_invocable::CanEmplace<Sig, T, Args...>::value>>
211
  explicit AnyInvocable(absl::in_place_type_t<T>, Args&&... args)
212
      : Impl(absl::in_place_type<absl::decay_t<T>>,
213
             std::forward<Args>(args)...) {
214
    static_assert(std::is_same<T, absl::decay_t<T>>::value,
215
                  "The explicit template argument of in_place_type is required "
216
                  "to be an unqualified object type.");
217
  }
218
219
  // Overload of the above constructor to support list-initialization.
220
  template <class T, class U, class... Args,
221
            typename = absl::enable_if_t<internal_any_invocable::CanEmplace<
222
                Sig, T, std::initializer_list<U>&, Args...>::value>>
223
  explicit AnyInvocable(absl::in_place_type_t<T>,
224
                        std::initializer_list<U> ilist, Args&&... args)
225
      : Impl(absl::in_place_type<absl::decay_t<T>>, ilist,
226
             std::forward<Args>(args)...) {
227
    static_assert(std::is_same<T, absl::decay_t<T>>::value,
228
                  "The explicit template argument of in_place_type is required "
229
                  "to be an unqualified object type.");
230
  }
231
232
  // Assignment Operators
233
234
  // Assigns an `AnyInvocable` through move-assignment.
235
  // Note that `f` is not guaranteed to be empty after move-assignment
236
  // although it may be.
237
102k
  AnyInvocable& operator=(AnyInvocable&& /*f*/) noexcept = default;
238
239
  // Assigns an `AnyInvocable` from a nullptr, clearing the `AnyInvocable`. If
240
  // not empty, destroys the target, putting `*this` into an empty state.
241
  AnyInvocable& operator=(std::nullptr_t) noexcept {
242
    this->Clear();
243
    return *this;
244
  }
245
246
  // Assigns an `AnyInvocable` from an existing `AnyInvocable` instance.
247
  //
248
  // Upon assignment, `*this` is only empty if `f` is a function pointer or
249
  // member pointer type and is null, or if `f` is an `AnyInvocable` that is
250
  // empty.
251
  template <class F, typename = absl::enable_if_t<
252
                         internal_any_invocable::CanAssign<Sig, F>::value>>
253
  AnyInvocable& operator=(F&& f) {
254
    *this = AnyInvocable(std::forward<F>(f));
255
    return *this;
256
  }
257
258
  // Assigns an `AnyInvocable` from a reference to an invocable object.
259
  // Upon assignment, stores a reference to the invocable object in the
260
  // `AnyInvocable` instance.
261
  template <
262
      class F,
263
      typename = absl::enable_if_t<
264
          internal_any_invocable::CanAssignReferenceWrapper<Sig, F>::value>>
265
  AnyInvocable& operator=(std::reference_wrapper<F> f) noexcept {
266
    *this = AnyInvocable(f);
267
    return *this;
268
  }
269
270
  // Destructor
271
272
  // If not empty, destroys the target.
273
  ~AnyInvocable() = default;
274
275
  // absl::AnyInvocable::swap()
276
  //
277
  // Exchanges the targets of `*this` and `other`.
278
  void swap(AnyInvocable& other) noexcept { std::swap(*this, other); }
279
280
  // absl::AnyInvocable::operator bool()
281
  //
282
  // Returns `true` if `*this` is not empty.
283
  //
284
  // WARNING: An `AnyInvocable` that wraps an empty `std::function` is not
285
  // itself empty. This behavior is consistent with the standard equivalent
286
  // `std::move_only_function`. In the following example, `a()` will actually
287
  // invoke `f()`, leading to an `std::bad_function_call` exception:
288
  //   std::function<void()> f;  // empty
289
  //   absl::AnyInvocable<void()> a = f;  // not empty
290
  //
291
  // Invoking an empty `AnyInvocable` results in undefined behavior.
292
  explicit operator bool() const noexcept { return this->HasValue(); }
293
294
  // Invokes the target object of `*this`. `*this` must not be empty.
295
  //
296
  // Note: The signature of this function call operator is the same as the
297
  //       template parameter `Sig`.
298
  using Impl::operator();
299
300
  // Equality operators
301
302
  // Returns `true` if `f` is empty.
303
102k
  friend bool operator==(const AnyInvocable& f, std::nullptr_t) noexcept {
304
102k
    return !f.HasValue();
305
102k
  }
306
307
  // Returns `true` if `f` is empty.
308
  friend bool operator==(std::nullptr_t, const AnyInvocable& f) noexcept {
309
    return !f.HasValue();
310
  }
311
312
  // Returns `false` if `f` is empty.
313
  friend bool operator!=(const AnyInvocable& f, std::nullptr_t) noexcept {
314
    return f.HasValue();
315
  }
316
317
  // Returns `false` if `f` is empty.
318
  friend bool operator!=(std::nullptr_t, const AnyInvocable& f) noexcept {
319
    return f.HasValue();
320
  }
321
322
  // swap()
323
  //
324
  // Exchanges the targets of `f1` and `f2`.
325
  friend void swap(AnyInvocable& f1, AnyInvocable& f2) noexcept { f1.swap(f2); }
326
327
 private:
328
  // Friending other instantiations is necessary for conversions.
329
  template <bool /*SigIsNoexcept*/, class /*ReturnType*/, class... /*P*/>
330
  friend class internal_any_invocable::CoreImpl;
331
};
332
333
ABSL_NAMESPACE_END
334
}  // namespace absl
335
336
#endif  // ABSL_FUNCTIONAL_ANY_INVOCABLE_H_