1 /* Copyright (c) 2015-2020. 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 const int argc = args_->size();
41 std::vector<std::string> args = *args_;
42 std::vector<char*> argv(args.size() + 1); // argv[argc] is nullptr
43 std::transform(begin(args), end(args), begin(argv), [](std::string& s) { return &s.front(); });
44 code_(argc, argv.data());
48 template <class F> inline std::function<void()> wrap_main(F code, std::vector<std::string>&& args)
50 return MainFunction<F>(std::move(code), std::move(args));
53 template <class F> inline std::function<void()> wrap_main(F code, int argc, const char* const argv[])
55 std::vector<std::string> args(argv, argv + argc);
56 return MainFunction<F>(std::move(code), std::move(args));
60 template <class F, class Tuple, std::size_t... I>
61 constexpr auto apply(F&& f, Tuple&& t, std::index_sequence<I...>)
62 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...))
64 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
68 /** Call a functional object with the values in the given tuple (from C++17)
71 * int foo(int a, bool b);
73 * auto args = std::make_tuple(1, false);
74 * int res = apply(foo, args);
77 template <class F, class Tuple>
78 constexpr auto apply(F&& f, Tuple&& t) -> decltype(
79 simgrid::xbt::bits::apply(std::forward<F>(f), std::forward<Tuple>(t),
80 std::make_index_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>()))
82 return simgrid::xbt::bits::apply(
83 std::forward<F>(f), std::forward<Tuple>(t),
84 std::make_index_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>());
87 template<class T> class Task;
89 /** Type-erased run-once task
91 * * Like std::function but callable only once.
92 * However, it works with move-only types.
94 * * Like std::packaged_task<> but without the shared state.
96 template<class R, class... Args>
97 class Task<R(Args...)> {
98 // Placeholder for some class type:
101 // Union used for storage:
102 typedef typename std::aligned_union<0,
104 std::pair<void(*)(),void*>,
105 std::pair<void(whatever::*)(), whatever*>
108 // Is F suitable for small buffer optimization?
110 static constexpr bool canSBO()
112 return sizeof(F) <= sizeof(TaskUnion) &&
113 alignof(F) <= alignof(TaskUnion);
116 static_assert(canSBO<std::reference_wrapper<whatever>>(),
117 "SBO not working for reference_wrapper");
119 // Call (and possibly destroy) the function:
120 typedef R (*call_function)(TaskUnion&, Args...);
121 // Destroy the function (of needed):
122 typedef void (*destroy_function)(TaskUnion&);
123 // Move the function (otherwise memcpy):
124 typedef void (*move_function)(TaskUnion& dest, TaskUnion& src);
126 // Vtable of functions for manipulating whatever is in the TaskUnion:
129 destroy_function destroy;
134 const TaskVtable* vtable_ = nullptr;
138 if (vtable_ && vtable_->destroy)
139 vtable_->destroy(buffer_);
144 explicit Task(std::nullptr_t) { /* Nothing to do */}
150 Task(Task const&) = delete;
152 Task(Task&& that) noexcept
154 if (that.vtable_ && that.vtable_->move)
155 that.vtable_->move(buffer_, that.buffer_);
157 std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
158 vtable_ = std::move(that.vtable_);
159 that.vtable_ = nullptr;
161 Task& operator=(Task const& that) = delete;
162 Task& operator=(Task&& that) noexcept
165 if (that.vtable_ && that.vtable_->move)
166 that.vtable_->move(buffer_, that.buffer_);
168 std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
169 vtable_ = std::move(that.vtable_);
170 that.vtable_ = nullptr;
176 typename std::enable_if<canSBO<F>()>::type
179 const static TaskVtable vtable {
181 [](TaskUnion& buffer, Args... args) {
182 auto* src = reinterpret_cast<F*>(&buffer);
183 F code = std::move(*src);
185 // NOTE: std::forward<Args>(args)... is correct.
186 return code(std::forward<Args>(args)...);
189 std::is_trivially_destructible<F>::value ?
190 static_cast<destroy_function>(nullptr) :
191 [](TaskUnion& buffer) {
192 auto* code = reinterpret_cast<F*>(&buffer);
196 [](TaskUnion& dst, TaskUnion& src) {
197 auto* src_code = reinterpret_cast<F*>(&src);
198 auto* dst_code = reinterpret_cast<F*>(&dst);
199 new(dst_code) F(std::move(*src_code));
203 new(&buffer_) F(std::move(code));
207 template <class F> typename std::enable_if<not canSBO<F>()>::type init(F code)
209 const static TaskVtable vtable {
211 [](TaskUnion& buffer, Args... args) {
212 // Delete F when we go out of scope:
213 std::unique_ptr<F> code(*reinterpret_cast<F**>(&buffer));
214 // NOTE: std::forward<Args>(args)... is correct.
215 return (*code)(std::forward<Args>(args)...);
218 [](TaskUnion& buffer) {
219 F* code = *reinterpret_cast<F**>(&buffer);
225 *reinterpret_cast<F**>(&buffer_) = new F(std::move(code));
230 template <class F> explicit Task(F code) { this->init(std::move(code)); }
232 operator bool() const { return vtable_ != nullptr; }
233 bool operator!() const { return vtable_ == nullptr; }
235 R operator()(Args... args)
237 if (vtable_ == nullptr)
238 throw std::bad_function_call();
239 const TaskVtable* vtable = vtable_;
241 // NOTE: std::forward<Args>(args)... is correct.
242 // see C++ [func.wrap.func.inv] for an example
243 return vtable->call(buffer_, std::forward<Args>(args)...);
247 template<class F, class... Args>
250 std::tuple<Args...> args_;
251 typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
253 TaskImpl(F code, std::tuple<Args...> args) :
254 code_(std::move(code)),
255 args_(std::move(args))
257 result_type operator()()
259 return simgrid::xbt::apply(std::move(code_), std::move(args_));
263 template <class F, class... Args> auto make_task(F code, Args... args) -> Task<decltype(code(std::move(args)...))()>
265 TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
266 return Task<decltype(code(std::move(args)...))()>(std::move(task));
270 } // namespace simgrid