#ifndef ABSL_FUNCTIONAL_INTERNAL_ANY_INVOCABLE_H_
#define ABSL_FUNCTIONAL_INTERNAL_ANY_INVOCABLE_H_
#include <cassert>
#include <cstddef>
#include <cstring>
#include <exception>
#include <functional>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/invoke.h"
#include "absl/base/macros.h"
#include "absl/base/optimization.h"
#include "absl/meta/type_traits.h"
#include "absl/utility/utility.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L
#define ABSL_INTERNAL_NOEXCEPT_SPEC(noex) noexcept(noex)
#else
#define ABSL_INTERNAL_NOEXCEPT_SPEC(noex)
#endif
template <class Sig>
class AnyInvocable;
namespace internal_any_invocable {
enum StorageProperty : std::size_t {
kAlignment = alignof(std::max_align_t), kStorageSize = sizeof(void*) * 2 };
template <class T>
struct IsAnyInvocable : std::false_type {};
template <class Sig>
struct IsAnyInvocable<AnyInvocable<Sig>> : std::true_type {};
template <class T>
using IsStoredLocally = std::integral_constant<
bool, sizeof(T) <= kStorageSize && alignof(T) <= kAlignment &&
kAlignment % alignof(T) == 0 &&
std::is_nothrow_move_constructible<T>::value>;
template <class T>
using RemoveCVRef =
typename std::remove_cv<typename std::remove_reference<T>::type>::type;
template <class ReturnType, class F, class... P,
typename = absl::enable_if_t<std::is_void<ReturnType>::value>>
void InvokeR(F&& f, P&&... args) {
absl::base_internal::invoke(std::forward<F>(f), std::forward<P>(args)...);
}
template <class ReturnType, class F, class... P,
absl::enable_if_t<!std::is_void<ReturnType>::value, int> = 0>
ReturnType InvokeR(F&& f, P&&... args) {
#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
return absl::base_internal::invoke(std::forward<F>(f),
std::forward<P>(args)...);
#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0)
#pragma GCC diagnostic pop
#endif
}
template <typename T>
T ForwardImpl(std::true_type);
template <typename T>
T&& ForwardImpl(std::false_type);
template <class T>
struct ForwardedParameter {
using type = decltype((
ForwardImpl<T>)(std::integral_constant<bool,
std::is_scalar<T>::value>()));
};
template <class T>
using ForwardedParameterType = typename ForwardedParameter<T>::type;
enum class FunctionToCall : bool { relocate_from_to, dispose };
union TypeErasedState {
struct {
void* target;
std::size_t size;
} remote;
alignas(kAlignment) char storage[kStorageSize];
};
template <class T>
T& ObjectInLocalStorage(TypeErasedState* const state) {
#if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606L
return *std::launder(reinterpret_cast<T*>(&state->storage));
#elif ABSL_HAVE_BUILTIN(__builtin_launder)
return *__builtin_launder(reinterpret_cast<T*>(&state->storage));
#else
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
return *reinterpret_cast<T*>(&state->storage);
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#endif
}
using ManagerType = void(FunctionToCall ,
TypeErasedState* , TypeErasedState* )
ABSL_INTERNAL_NOEXCEPT_SPEC(true);
template <bool SigIsNoexcept, class ReturnType, class... P>
using InvokerType = ReturnType(TypeErasedState*, ForwardedParameterType<P>...)
ABSL_INTERNAL_NOEXCEPT_SPEC(SigIsNoexcept);
inline void EmptyManager(FunctionToCall ,
TypeErasedState* ,
TypeErasedState* ) noexcept {}
inline void LocalManagerTrivial(FunctionToCall ,
TypeErasedState* const from,
TypeErasedState* const to) noexcept {
*to = *from;
}
template <class T>
void LocalManagerNontrivial(FunctionToCall operation,
TypeErasedState* const from,
TypeErasedState* const to) noexcept {
static_assert(IsStoredLocally<T>::value,
"Local storage must only be used for supported types.");
static_assert(!std::is_trivially_copyable<T>::value,
"Locally stored types must be trivially copyable.");
T& from_object = (ObjectInLocalStorage<T>)(from);
switch (operation) {
case FunctionToCall::relocate_from_to:
::new (static_cast<void*>(&to->storage)) T(std::move(from_object));
ABSL_FALLTHROUGH_INTENDED;
case FunctionToCall::dispose:
from_object.~T(); return;
}
ABSL_UNREACHABLE();
}
template <bool SigIsNoexcept, class ReturnType, class QualTRef, class... P>
ReturnType LocalInvoker(
TypeErasedState* const state,
ForwardedParameterType<P>... args) noexcept(SigIsNoexcept) {
using RawT = RemoveCVRef<QualTRef>;
static_assert(
IsStoredLocally<RawT>::value,
"Target object must be in local storage in order to be invoked from it.");
auto& f = (ObjectInLocalStorage<RawT>)(state);
return (InvokeR<ReturnType>)(static_cast<QualTRef>(f),
static_cast<ForwardedParameterType<P>>(args)...);
}
inline void RemoteManagerTrivial(FunctionToCall operation,
TypeErasedState* const from,
TypeErasedState* const to) noexcept {
switch (operation) {
case FunctionToCall::relocate_from_to:
to->remote = from->remote;
return;
case FunctionToCall::dispose:
#if defined(__cpp_sized_deallocation)
::operator delete(from->remote.target, from->remote.size);
#else
::operator delete(from->remote.target);
#endif return;
}
ABSL_UNREACHABLE();
}
template <class T>
void RemoteManagerNontrivial(FunctionToCall operation,
TypeErasedState* const from,
TypeErasedState* const to) noexcept {
static_assert(!IsStoredLocally<T>::value,
"Remote storage must only be used for types that do not "
"qualify for local storage.");
switch (operation) {
case FunctionToCall::relocate_from_to:
to->remote.target = from->remote.target;
return;
case FunctionToCall::dispose:
::delete static_cast<T*>(from->remote.target); return;
}
ABSL_UNREACHABLE();
}
template <bool SigIsNoexcept, class ReturnType, class QualTRef, class... P>
ReturnType RemoteInvoker(
TypeErasedState* const state,
ForwardedParameterType<P>... args) noexcept(SigIsNoexcept) {
using RawT = RemoveCVRef<QualTRef>;
static_assert(!IsStoredLocally<RawT>::value,
"Target object must be in remote storage in order to be "
"invoked from it.");
auto& f = *static_cast<RawT*>(state->remote.target);
return (InvokeR<ReturnType>)(static_cast<QualTRef>(f),
static_cast<ForwardedParameterType<P>>(args)...);
}
template <class T>
struct IsInPlaceType : std::false_type {};
template <class T>
struct IsInPlaceType<absl::in_place_type_t<T>> : std::true_type {};
template <class QualDecayedTRef>
struct TypedConversionConstruct {};
template <class Sig>
class Impl {};
#if defined(__cpp_sized_deallocation)
class TrivialDeleter {
public:
explicit TrivialDeleter(std::size_t size) : size_(size) {}
void operator()(void* target) const {
::operator delete(target, size_);
}
private:
std::size_t size_;
};
#else
class TrivialDeleter {
public:
explicit TrivialDeleter(std::size_t) {}
void operator()(void* target) const { ::operator delete(target); }
};
#endif
template <bool SigIsNoexcept, class ReturnType, class... P>
class CoreImpl;
constexpr bool IsCompatibleConversion(void*, void*) { return false; }
template <bool NoExceptSrc, bool NoExceptDest, class... T>
constexpr bool IsCompatibleConversion(CoreImpl<NoExceptSrc, T...>*,
CoreImpl<NoExceptDest, T...>*) {
return !NoExceptDest || NoExceptSrc;
}
template <bool SigIsNoexcept, class ReturnType, class... P>
class CoreImpl {
public:
using result_type = ReturnType;
CoreImpl() noexcept : manager_(EmptyManager), invoker_(nullptr) {}
enum class TargetType {
kPointer,
kCompatibleAnyInvocable,
kIncompatibleAnyInvocable,
kOther,
};
template <class QualDecayedTRef, class F>
explicit CoreImpl(TypedConversionConstruct<QualDecayedTRef>, F&& f) {
using DecayedT = RemoveCVRef<QualDecayedTRef>;
constexpr TargetType kTargetType =
(std::is_pointer<DecayedT>::value ||
std::is_member_pointer<DecayedT>::value)
? TargetType::kPointer
: IsCompatibleAnyInvocable<DecayedT>::value
? TargetType::kCompatibleAnyInvocable
: IsAnyInvocable<DecayedT>::value
? TargetType::kIncompatibleAnyInvocable
: TargetType::kOther;
Initialize<kTargetType, QualDecayedTRef>(std::forward<F>(f));
}
template <class QualTRef, class... Args>
explicit CoreImpl(absl::in_place_type_t<QualTRef>, Args&&... args) {
InitializeStorage<QualTRef>(std::forward<Args>(args)...);
}
CoreImpl(CoreImpl&& other) noexcept {
other.manager_(FunctionToCall::relocate_from_to, &other.state_, &state_);
manager_ = other.manager_;
invoker_ = other.invoker_;
other.manager_ = EmptyManager;
other.invoker_ = nullptr;
}
CoreImpl& operator=(CoreImpl&& other) noexcept {
Clear();
other.manager_(FunctionToCall::relocate_from_to, &other.state_, &state_);
manager_ = other.manager_;
invoker_ = other.invoker_;
other.manager_ = EmptyManager;
other.invoker_ = nullptr;
return *this;
}
~CoreImpl() { manager_(FunctionToCall::dispose, &state_, &state_); }
bool HasValue() const { return invoker_ != nullptr; }
void Clear() {
manager_(FunctionToCall::dispose, &state_, &state_);
manager_ = EmptyManager;
invoker_ = nullptr;
}
template <TargetType target_type, class QualDecayedTRef, class F,
absl::enable_if_t<target_type == TargetType::kPointer, int> = 0>
void Initialize(F&& f) {
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Waddress"
#pragma GCC diagnostic ignored "-Wnonnull-compare"
#endif
if (static_cast<RemoveCVRef<QualDecayedTRef>>(f) == nullptr) {
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
manager_ = EmptyManager;
invoker_ = nullptr;
return;
}
InitializeStorage<QualDecayedTRef>(std::forward<F>(f));
}
template <TargetType target_type, class QualDecayedTRef, class F,
absl::enable_if_t<
target_type == TargetType::kCompatibleAnyInvocable, int> = 0>
void Initialize(F&& f) {
f.manager_(FunctionToCall::relocate_from_to, &f.state_, &state_);
manager_ = f.manager_;
invoker_ = f.invoker_;
f.manager_ = EmptyManager;
f.invoker_ = nullptr;
}
template <TargetType target_type, class QualDecayedTRef, class F,
absl::enable_if_t<
target_type == TargetType::kIncompatibleAnyInvocable, int> = 0>
void Initialize(F&& f) {
if (f.HasValue()) {
InitializeStorage<QualDecayedTRef>(std::forward<F>(f));
} else {
manager_ = EmptyManager;
invoker_ = nullptr;
}
}
template <TargetType target_type, class QualDecayedTRef, class F,
typename = absl::enable_if_t<target_type == TargetType::kOther>>
void Initialize(F&& f) {
InitializeStorage<QualDecayedTRef>(std::forward<F>(f));
}
template <class QualTRef, class... Args,
typename = absl::enable_if_t<
IsStoredLocally<RemoveCVRef<QualTRef>>::value>>
void InitializeStorage(Args&&... args) {
using RawT = RemoveCVRef<QualTRef>;
::new (static_cast<void*>(&state_.storage))
RawT(std::forward<Args>(args)...);
invoker_ = LocalInvoker<SigIsNoexcept, ReturnType, QualTRef, P...>;
InitializeLocalManager<RawT>();
}
template <class QualTRef, class... Args,
absl::enable_if_t<!IsStoredLocally<RemoveCVRef<QualTRef>>::value,
int> = 0>
void InitializeStorage(Args&&... args) {
InitializeRemoteManager<RemoveCVRef<QualTRef>>(std::forward<Args>(args)...);
invoker_ = RemoteInvoker<SigIsNoexcept, ReturnType, QualTRef, P...>;
}
template <class T,
typename = absl::enable_if_t<std::is_trivially_copyable<T>::value>>
void InitializeLocalManager() {
manager_ = LocalManagerTrivial;
}
template <class T,
absl::enable_if_t<!std::is_trivially_copyable<T>::value, int> = 0>
void InitializeLocalManager() {
manager_ = LocalManagerNontrivial<T>;
}
template <class T>
using HasTrivialRemoteStorage =
std::integral_constant<bool, std::is_trivially_destructible<T>::value &&
alignof(T) <=
ABSL_INTERNAL_DEFAULT_NEW_ALIGNMENT>;
template <class T, class... Args,
typename = absl::enable_if_t<HasTrivialRemoteStorage<T>::value>>
void InitializeRemoteManager(Args&&... args) {
std::unique_ptr<void, TrivialDeleter> uninitialized_target(
::operator new(sizeof(T)), TrivialDeleter(sizeof(T)));
::new (uninitialized_target.get()) T(std::forward<Args>(args)...);
state_.remote.target = uninitialized_target.release();
state_.remote.size = sizeof(T);
manager_ = RemoteManagerTrivial;
}
template <class T, class... Args,
absl::enable_if_t<!HasTrivialRemoteStorage<T>::value, int> = 0>
void InitializeRemoteManager(Args&&... args) {
state_.remote.target = ::new T(std::forward<Args>(args)...);
manager_ = RemoteManagerNontrivial<T>;
}
template <typename Other>
struct IsCompatibleAnyInvocable {
static constexpr bool value = false;
};
template <typename Sig>
struct IsCompatibleAnyInvocable<AnyInvocable<Sig>> {
static constexpr bool value =
(IsCompatibleConversion)(static_cast<
typename AnyInvocable<Sig>::CoreImpl*>(
nullptr),
static_cast<CoreImpl*>(nullptr));
};
TypeErasedState state_;
ManagerType* manager_;
InvokerType<SigIsNoexcept, ReturnType, P...>* invoker_;
};
struct ConversionConstruct {};
template <class T>
struct UnwrapStdReferenceWrapperImpl {
using type = T;
};
template <class T>
struct UnwrapStdReferenceWrapperImpl<std::reference_wrapper<T>> {
using type = T&;
};
template <class T>
using UnwrapStdReferenceWrapper =
typename UnwrapStdReferenceWrapperImpl<T>::type;
template <class... T>
using TrueAlias =
std::integral_constant<bool, sizeof(absl::void_t<T...>*) != 0>;
template <class Sig, class F,
class = absl::enable_if_t<
!std::is_same<RemoveCVRef<F>, AnyInvocable<Sig>>::value>>
using CanConvert = TrueAlias<
absl::enable_if_t<!IsInPlaceType<RemoveCVRef<F>>::value>,
absl::enable_if_t<Impl<Sig>::template CallIsValid<F>::value>,
absl::enable_if_t<
Impl<Sig>::template CallIsNoexceptIfSigIsNoexcept<F>::value>,
absl::enable_if_t<std::is_constructible<absl::decay_t<F>, F>::value>>;
template <class Sig, class F, class... Args>
using CanEmplace = TrueAlias<
absl::enable_if_t<Impl<Sig>::template CallIsValid<F>::value>,
absl::enable_if_t<
Impl<Sig>::template CallIsNoexceptIfSigIsNoexcept<F>::value>,
absl::enable_if_t<std::is_constructible<absl::decay_t<F>, Args...>::value>>;
template <class Sig, class F,
class = absl::enable_if_t<
!std::is_same<RemoveCVRef<F>, AnyInvocable<Sig>>::value>>
using CanAssign = TrueAlias<
absl::enable_if_t<Impl<Sig>::template CallIsValid<F>::value>,
absl::enable_if_t<
Impl<Sig>::template CallIsNoexceptIfSigIsNoexcept<F>::value>,
absl::enable_if_t<std::is_constructible<absl::decay_t<F>, F>::value>>;
template <class Sig, class F>
using CanAssignReferenceWrapper = TrueAlias<
absl::enable_if_t<
Impl<Sig>::template CallIsValid<std::reference_wrapper<F>>::value>,
absl::enable_if_t<Impl<Sig>::template CallIsNoexceptIfSigIsNoexcept<
std::reference_wrapper<F>>::value>>;
#define ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT(inv_quals, noex) \
ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_##noex(inv_quals)
#define ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_true(inv_quals) \
absl::enable_if_t<absl::disjunction< \
std::is_nothrow_invocable_r< \
ReturnType, UnwrapStdReferenceWrapper<absl::decay_t<F>> inv_quals, \
P...>, \
std::conjunction< \
std::is_nothrow_invocable< \
UnwrapStdReferenceWrapper<absl::decay_t<F>> inv_quals, P...>, \
std::is_same< \
ReturnType, \
absl::base_internal::invoke_result_t< \
UnwrapStdReferenceWrapper<absl::decay_t<F>> inv_quals, \
P...>>>>::value>
#define ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_false(inv_quals)
#define ABSL_INTERNAL_ANY_INVOCABLE_IMPL_(cv, ref, inv_quals, noex) \
template <class ReturnType, class... P> \
class Impl<ReturnType(P...) cv ref ABSL_INTERNAL_NOEXCEPT_SPEC(noex)> \
: public CoreImpl<noex, ReturnType, P...> { \
public: \
\
using Core = CoreImpl<noex, ReturnType, P...>; \
\
\
template <class F> \
using CallIsValid = TrueAlias<absl::enable_if_t<absl::disjunction< \
absl::base_internal::is_invocable_r<ReturnType, \
absl::decay_t<F> inv_quals, P...>, \
std::is_same<ReturnType, \
absl::base_internal::invoke_result_t< \
absl::decay_t<F> inv_quals, P...>>>::value>>; \
\
\
template <class F> \
using CallIsNoexceptIfSigIsNoexcept = \
TrueAlias<ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT(inv_quals, \
noex)>; \
\
\
Impl() = default; \
\
\
\
\
template <class F> \
explicit Impl(ConversionConstruct, F&& f) \
: Core(TypedConversionConstruct< \
typename std::decay<F>::type inv_quals>(), \
std::forward<F>(f)) {} \
\
\
template <class T, class... Args> \
explicit Impl(absl::in_place_type_t<T>, Args&&... args) \
: Core(absl::in_place_type<absl::decay_t<T> inv_quals>, \
std::forward<Args>(args)...) {} \
\
\
static ReturnType InvokedAfterMove( \
TypeErasedState*, \
ForwardedParameterType<P>...) noexcept(noex) { \
ABSL_HARDENING_ASSERT(false && "AnyInvocable use-after-move"); \
std::terminate(); \
} \
\
InvokerType<noex, ReturnType, P...>* ExtractInvoker() cv { \
using QualifiedTestType = int cv ref; \
auto* invoker = this->invoker_; \
if (!std::is_const<QualifiedTestType>::value && \
std::is_rvalue_reference<QualifiedTestType>::value) { \
ABSL_ASSERT([this]() { \
\
const_cast<Impl*>(this)->invoker_ = InvokedAfterMove; \
return this->HasValue(); \
}()); \
} \
return invoker; \
} \
\
\
ReturnType operator()(P... args) cv ref noexcept(noex) { \
assert(this->invoker_ != nullptr); \
return this->ExtractInvoker()( \
const_cast<TypeErasedState*>(&this->state_), \
static_cast<ForwardedParameterType<P>>(args)...); \
} \
}
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L
#define ABSL_INTERNAL_ANY_INVOCABLE_IMPL(cv, ref, inv_quals) \
ABSL_INTERNAL_ANY_INVOCABLE_IMPL_(cv, ref, inv_quals, false); \
ABSL_INTERNAL_ANY_INVOCABLE_IMPL_(cv, ref, inv_quals, true)
#else
#define ABSL_INTERNAL_ANY_INVOCABLE_IMPL(cv, ref, inv_quals) \
ABSL_INTERNAL_ANY_INVOCABLE_IMPL_(cv, ref, inv_quals, false)
#endif
ABSL_INTERNAL_ANY_INVOCABLE_IMPL(, , &);
ABSL_INTERNAL_ANY_INVOCABLE_IMPL(const, , const&);
ABSL_INTERNAL_ANY_INVOCABLE_IMPL(, &, &);
ABSL_INTERNAL_ANY_INVOCABLE_IMPL(const, &, const&);
ABSL_INTERNAL_ANY_INVOCABLE_IMPL(, &&, &&);
ABSL_INTERNAL_ANY_INVOCABLE_IMPL(const, &&, const&&);
#undef ABSL_INTERNAL_ANY_INVOCABLE_IMPL
#undef ABSL_INTERNAL_ANY_INVOCABLE_IMPL_
#undef ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_false
#undef ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_true
#undef ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT
#undef ABSL_INTERNAL_NOEXCEPT_SPEC
} ABSL_NAMESPACE_END
}
#endif