1 /* Copyright (c) 2015-2023. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 #ifndef XBT_FUNCTIONAL_HPP
7 #define XBT_FUNCTIONAL_HPP
9 #include <xbt/sysdep.h>
22 #include <type_traits>
29 template <class F> class MainFunction {
31 std::shared_ptr<const std::vector<std::string>> args_;
34 MainFunction(F code, std::vector<std::string>&& args)
35 : code_(std::move(code)), args_(std::make_shared<const std::vector<std::string>>(std::move(args)))
38 void operator()() const
40 std::vector<std::string> args = *args_;
41 std::vector<char*> argv(args.size() + 1); // argv[argc] is nullptr
42 std::transform(begin(args), end(args), begin(argv), [](std::string& s) { return &s.front(); });
43 code_(static_cast<int>(args.size()), argv.data());
47 template <class F> inline std::function<void()> wrap_main(F code, std::vector<std::string>&& args)
49 return MainFunction<F>(std::move(code), std::move(args));
52 template <class F> inline std::function<void()> wrap_main(F code, int argc, const char* const argv[])
54 std::vector<std::string> args(argv, argv + argc);
55 return MainFunction<F>(std::move(code), std::move(args));
59 template <class F, class Tuple, std::size_t... I>
60 constexpr auto apply(F&& f, Tuple&& t, std::index_sequence<I...>)
61 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...))
63 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
67 /** Call a functional object with the values in the given tuple (from C++17)
70 * int foo(int a, bool b);
72 * auto args = std::make_tuple(1, false);
73 * int res = apply(foo, args);
76 template <class F, class Tuple>
77 constexpr auto apply(F&& f, Tuple&& t) -> decltype(
78 simgrid::xbt::bits::apply(std::forward<F>(f), std::forward<Tuple>(t),
79 std::make_index_sequence<std::tuple_size<typename std::decay_t<Tuple>>::value>()))
81 return simgrid::xbt::bits::apply(std::forward<F>(f), std::forward<Tuple>(t),
82 std::make_index_sequence<std::tuple_size<typename std::decay_t<Tuple>>::value>());
85 template<class T> class Task;
87 /** Type-erased run-once task
89 * * Like std::function but callable only once.
90 * However, it works with move-only types.
92 * * Like std::packaged_task<> but without the shared state.
94 template<class R, class... Args>
95 class Task<R(Args...)> {
96 // Placeholder for some class type:
99 // Union used for storage:
101 typename std::aligned_union_t<0, void*, std::pair<void (*)(), void*>, std::pair<void (whatever::*)(), whatever*>>;
103 // Is F suitable for small buffer optimization?
105 static constexpr bool canSBO()
107 return sizeof(F) <= sizeof(TaskUnion) &&
108 alignof(F) <= alignof(TaskUnion);
111 static_assert(canSBO<std::reference_wrapper<whatever>>(),
112 "SBO not working for reference_wrapper");
114 // Call (and possibly destroy) the function:
115 using call_function = R (*)(TaskUnion&, Args...);
116 // Destroy the function (of needed):
117 using destroy_function = void (*)(TaskUnion&);
118 // Move the function (otherwise memcpy):
119 using move_function = void (*)(TaskUnion& dest, TaskUnion& src);
121 // Vtable of functions for manipulating whatever is in the TaskUnion:
124 destroy_function destroy;
128 TaskUnion buffer_ = {};
129 const TaskVtable* vtable_ = nullptr;
133 if (vtable_ && vtable_->destroy)
134 vtable_->destroy(buffer_);
139 explicit Task(std::nullptr_t) { /* Nothing to do */}
145 Task(Task const&) = delete;
147 Task(Task&& that) noexcept
149 if (that.vtable_ && that.vtable_->move)
150 that.vtable_->move(buffer_, that.buffer_);
152 std::memcpy(&buffer_, &that.buffer_, sizeof(buffer_));
153 vtable_ = std::move(that.vtable_);
154 that.vtable_ = nullptr;
156 Task& operator=(Task const& that) = delete;
157 Task& operator=(Task&& that) noexcept
160 if (that.vtable_ && that.vtable_->move)
161 that.vtable_->move(buffer_, that.buffer_);
163 std::memcpy(&buffer_, &that.buffer_, sizeof(buffer_));
164 vtable_ = std::move(that.vtable_);
165 that.vtable_ = nullptr;
170 template <class F> typename std::enable_if_t<canSBO<F>()> init(F task_code)
172 const static TaskVtable vtable {
174 [](TaskUnion& buffer, Args... args) {
175 auto* src = reinterpret_cast<F*>(&buffer);
176 F code = std::move(*src);
178 // NOTE: std::forward<Args>(args)... is correct.
179 return code(std::forward<Args>(args)...);
182 std::is_trivially_destructible<F>::value ?
183 static_cast<destroy_function>(nullptr) :
184 [](TaskUnion& buffer) {
185 auto* code = reinterpret_cast<F*>(&buffer);
189 [](TaskUnion& dst, TaskUnion& src) {
190 auto* src_code = reinterpret_cast<F*>(&src);
191 auto* dst_code = reinterpret_cast<F*>(&dst);
192 new(dst_code) F(std::move(*src_code));
196 new (&buffer_) F(std::move(task_code));
200 template <class F> typename std::enable_if_t<not canSBO<F>()> init(F task_code)
202 const static TaskVtable vtable {
204 [](TaskUnion& buffer, Args... args) {
205 // Delete F when we go out of scope:
206 std::unique_ptr<F> code(*reinterpret_cast<F**>(&buffer));
207 // NOTE: std::forward<Args>(args)... is correct.
208 return (*code)(std::forward<Args>(args)...);
211 [](TaskUnion& buffer) {
212 F* code = *reinterpret_cast<F**>(&buffer);
218 *reinterpret_cast<F**>(&buffer_) = new F(std::move(task_code));
223 template <class F> explicit Task(F code) { this->init(std::move(code)); }
225 operator bool() const { return vtable_ != nullptr; }
226 bool operator!() const { return vtable_ == nullptr; }
228 R operator()(Args... args)
230 if (vtable_ == nullptr)
231 throw std::bad_function_call();
232 const TaskVtable* vtable = vtable_;
234 // NOTE: std::forward<Args>(args)... is correct.
235 // see C++ [func.wrap.func.inv] for an example
236 return vtable->call(buffer_, std::forward<Args>(args)...);
240 template<class F, class... Args>
243 std::tuple<Args...> args_;
244 using result_type = decltype(simgrid::xbt::apply(std::move(code_), std::move(args_)));
247 TaskImpl(F code, std::tuple<Args...> args) :
248 code_(std::move(code)),
249 args_(std::move(args))
251 result_type operator()()
253 return simgrid::xbt::apply(std::move(code_), std::move(args_));
257 template <class F, class... Args> auto make_task(F code, Args... args) -> Task<decltype(code(std::move(args)...))()>
259 TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
260 return Task<decltype(code(std::move(args)...))()>(std::move(task));
264 } // namespace simgrid