[libc][NFC] Move aligned access implementations to separate header
[llvm-project.git] / libc / src / __support / CPP / functional.h
blobe346011debab10cd3db7766a69453b35b7a36c11
1 //===-- Self contained functional header ------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SRC_SUPPORT_CPP_FUNCTIONAL_H
10 #define LLVM_LIBC_SRC_SUPPORT_CPP_FUNCTIONAL_H
12 #include "src/__support/CPP/type_traits.h"
13 #include "src/__support/CPP/utility.h"
14 #include "src/__support/macros/attributes.h"
16 #include <stdint.h>
18 namespace __llvm_libc {
19 namespace cpp {
21 /// A function type adapted from LLVM's function_ref.
22 /// This class does not own the callable, so it is not in general safe to
23 /// store a function.
24 template <typename Fn> class function;
26 template <typename Ret, typename... Params> class function<Ret(Params...)> {
27 Ret (*callback)(intptr_t callable, Params... params) = nullptr;
28 intptr_t callable;
30 template <typename Callable>
31 LIBC_INLINE static Ret callback_fn(intptr_t callable, Params... params) {
32 return (*reinterpret_cast<Callable *>(callable))(
33 forward<Params>(params)...);
36 public:
37 LIBC_INLINE function() = default;
38 LIBC_INLINE function(decltype(nullptr)) {}
39 LIBC_INLINE ~function() = default;
41 template <typename Callable>
42 LIBC_INLINE function(
43 Callable &&callable,
44 // This is not the copy-constructor.
45 enable_if_t<!is_same<remove_cvref_t<Callable>, function>::value> * =
46 nullptr,
47 // Functor must be callable and return a suitable type.
48 enable_if_t<is_void_v<Ret> ||
49 is_convertible_v<
50 decltype(declval<Callable>()(declval<Params>()...)), Ret>>
51 * = nullptr)
52 : callback(callback_fn<remove_reference_t<Callable>>),
53 callable(reinterpret_cast<intptr_t>(&callable)) {}
55 LIBC_INLINE Ret operator()(Params... params) const {
56 return callback(callable, forward<Params>(params)...);
59 LIBC_INLINE explicit operator bool() const { return callback; }
62 } // namespace cpp
63 } // namespace __llvm_libc
65 #endif // LLVM_LIBC_SRC_SUPPORT_CPP_FUNCTIONAL_H