Function.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /*
  2. * Copyright (C) 2016 Apple Inc. All rights reserved.
  3. * Copyright (c) 2021, Gunnar Beutner <gbeutner@serenityos.org>
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
  15. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  16. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  17. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
  18. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  20. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  22. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  24. * THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #pragma once
  27. #include <AK/Assertions.h>
  28. #include <AK/Atomic.h>
  29. #include <AK/BitCast.h>
  30. #include <AK/Noncopyable.h>
  31. #include <AK/ScopeGuard.h>
  32. #include <AK/StdLibExtras.h>
  33. #include <AK/Types.h>
  34. namespace AK {
  35. template<typename>
  36. class Function;
  37. template<typename F>
  38. inline constexpr bool IsFunctionPointer = (IsPointer<F> && IsFunction<RemovePointer<F>>);
  39. // Not a function pointer, and not an lvalue reference.
  40. template<typename F>
  41. inline constexpr bool IsFunctionObject = (!IsFunctionPointer<F> && IsRvalueReference<F&&>);
  42. template<typename Out, typename... In>
  43. class Function<Out(In...)> {
  44. AK_MAKE_NONCOPYABLE(Function);
  45. public:
  46. Function() = default;
  47. Function(std::nullptr_t)
  48. {
  49. }
  50. ~Function()
  51. {
  52. clear(false);
  53. }
  54. template<typename CallableType>
  55. Function(CallableType&& callable) requires((IsFunctionObject<CallableType> && IsCallableWithArguments<CallableType, In...> && !IsSame<RemoveCVReference<CallableType>, Function>))
  56. {
  57. init_with_callable(forward<CallableType>(callable));
  58. }
  59. template<typename FunctionType>
  60. Function(FunctionType f) requires((IsFunctionPointer<FunctionType> && IsCallableWithArguments<RemovePointer<FunctionType>, In...> && !IsSame<RemoveCVReference<FunctionType>, Function>))
  61. {
  62. init_with_callable(move(f));
  63. }
  64. Function(Function&& other)
  65. {
  66. move_from(move(other));
  67. }
  68. // Note: Despite this method being const, a mutable lambda _may_ modify its own captures.
  69. Out operator()(In... in) const
  70. {
  71. auto* wrapper = callable_wrapper();
  72. VERIFY(wrapper);
  73. ++m_call_nesting_level;
  74. ScopeGuard guard([this] {
  75. if (--m_call_nesting_level == 0 && m_deferred_clear)
  76. const_cast<Function*>(this)->clear(false);
  77. });
  78. return wrapper->call(forward<In>(in)...);
  79. }
  80. explicit operator bool() const { return !!callable_wrapper(); }
  81. template<typename CallableType>
  82. Function& operator=(CallableType&& callable) requires((IsFunctionObject<CallableType> && IsCallableWithArguments<CallableType, In...>))
  83. {
  84. clear();
  85. init_with_callable(forward<CallableType>(callable));
  86. return *this;
  87. }
  88. template<typename FunctionType>
  89. Function& operator=(FunctionType f) requires((IsFunctionPointer<FunctionType> && IsCallableWithArguments<RemovePointer<FunctionType>, In...>))
  90. {
  91. clear();
  92. if (f)
  93. init_with_callable(move(f));
  94. return *this;
  95. }
  96. Function& operator=(std::nullptr_t)
  97. {
  98. clear();
  99. return *this;
  100. }
  101. Function& operator=(Function&& other)
  102. {
  103. if (this != &other) {
  104. clear();
  105. move_from(move(other));
  106. }
  107. return *this;
  108. }
  109. private:
  110. class CallableWrapperBase {
  111. public:
  112. virtual ~CallableWrapperBase() = default;
  113. // Note: This is not const to allow storing mutable lambdas.
  114. virtual Out call(In...) = 0;
  115. virtual void destroy() = 0;
  116. virtual void init_and_swap(u8*, size_t) = 0;
  117. };
  118. template<typename CallableType>
  119. class CallableWrapper final : public CallableWrapperBase {
  120. AK_MAKE_NONMOVABLE(CallableWrapper);
  121. AK_MAKE_NONCOPYABLE(CallableWrapper);
  122. public:
  123. explicit CallableWrapper(CallableType&& callable)
  124. : m_callable(move(callable))
  125. {
  126. }
  127. Out call(In... in) final override
  128. {
  129. return m_callable(forward<In>(in)...);
  130. }
  131. void destroy() final override
  132. {
  133. delete this;
  134. }
  135. // NOLINTNEXTLINE(readability-non-const-parameter) False positive; destination is used in a placement new expression
  136. void init_and_swap(u8* destination, size_t size) final override
  137. {
  138. VERIFY(size >= sizeof(CallableWrapper));
  139. new (destination) CallableWrapper { move(m_callable) };
  140. }
  141. private:
  142. CallableType m_callable;
  143. };
  144. enum class FunctionKind {
  145. NullPointer,
  146. Inline,
  147. Outline,
  148. };
  149. CallableWrapperBase* callable_wrapper() const
  150. {
  151. switch (m_kind) {
  152. case FunctionKind::NullPointer:
  153. return nullptr;
  154. case FunctionKind::Inline:
  155. return bit_cast<CallableWrapperBase*>(&m_storage);
  156. case FunctionKind::Outline:
  157. return *bit_cast<CallableWrapperBase**>(&m_storage);
  158. default:
  159. VERIFY_NOT_REACHED();
  160. }
  161. }
  162. void clear(bool may_defer = true)
  163. {
  164. bool called_from_inside_function = m_call_nesting_level > 0;
  165. // NOTE: This VERIFY could fail because a Function is destroyed from within itself.
  166. VERIFY(may_defer || !called_from_inside_function);
  167. if (called_from_inside_function && may_defer) {
  168. m_deferred_clear = true;
  169. return;
  170. }
  171. m_deferred_clear = false;
  172. auto* wrapper = callable_wrapper();
  173. if (m_kind == FunctionKind::Inline) {
  174. VERIFY(wrapper);
  175. wrapper->~CallableWrapperBase();
  176. } else if (m_kind == FunctionKind::Outline) {
  177. VERIFY(wrapper);
  178. wrapper->destroy();
  179. }
  180. m_kind = FunctionKind::NullPointer;
  181. }
  182. template<typename Callable>
  183. void init_with_callable(Callable&& callable)
  184. {
  185. VERIFY(m_call_nesting_level == 0);
  186. using WrapperType = CallableWrapper<Callable>;
  187. if constexpr (sizeof(WrapperType) > inline_capacity) {
  188. *bit_cast<CallableWrapperBase**>(&m_storage) = new WrapperType(forward<Callable>(callable));
  189. m_kind = FunctionKind::Outline;
  190. } else {
  191. new (m_storage) WrapperType(forward<Callable>(callable));
  192. m_kind = FunctionKind::Inline;
  193. }
  194. }
  195. void move_from(Function&& other)
  196. {
  197. VERIFY(m_call_nesting_level == 0 && other.m_call_nesting_level == 0);
  198. auto* other_wrapper = other.callable_wrapper();
  199. switch (other.m_kind) {
  200. case FunctionKind::NullPointer:
  201. break;
  202. case FunctionKind::Inline:
  203. other_wrapper->init_and_swap(m_storage, inline_capacity);
  204. m_kind = FunctionKind::Inline;
  205. break;
  206. case FunctionKind::Outline:
  207. *bit_cast<CallableWrapperBase**>(&m_storage) = other_wrapper;
  208. m_kind = FunctionKind::Outline;
  209. break;
  210. default:
  211. VERIFY_NOT_REACHED();
  212. }
  213. other.m_kind = FunctionKind::NullPointer;
  214. }
  215. FunctionKind m_kind { FunctionKind::NullPointer };
  216. bool m_deferred_clear { false };
  217. mutable Atomic<u16> m_call_nesting_level { 0 };
  218. // Empirically determined to fit most lambdas and functions.
  219. static constexpr size_t inline_capacity = 4 * sizeof(void*);
  220. alignas(max(alignof(CallableWrapperBase), alignof(CallableWrapperBase*))) u8 m_storage[inline_capacity];
  221. };
  222. }
  223. using AK::Function;