tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

any_invocable.h (12942B)


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