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>
21 #include <type_traits>
28 template <class F> class MainFunction {
30 std::shared_ptr<const std::vector<std::string>> args_;
33 MainFunction(F code, std::vector<std::string>&& args)
34 : code_(std::move(code)), args_(std::make_shared<const std::vector<std::string>>(std::move(args)))
37 void operator()() const
39 const int argc = args_->size();
40 std::vector<std::string> args = *args_;
41 if (not args.empty()) {
42 char noarg[] = {'\0'};
43 auto argv = std::make_unique<char*[]>(argc + 1);
44 for (int i = 0; i != argc; ++i)
45 argv[i] = args[i].empty() ? noarg : &args[i].front();
47 code_(argc, argv.get());
53 template <class F> inline std::function<void()> wrap_main(F code, std::vector<std::string>&& args)
55 return MainFunction<F>(std::move(code), std::move(args));
58 template <class F> inline std::function<void()> wrap_main(F code, int argc, const char* const argv[])
60 std::vector<std::string> args(argv, argv + argc);
61 return MainFunction<F>(std::move(code), std::move(args));
65 template <class F, class Tuple, std::size_t... I>
66 constexpr auto apply(F&& f, Tuple&& t, std::index_sequence<I...>)
67 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...))
69 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
73 /** Call a functional object with the values in the given tuple (from C++17)
76 * int foo(int a, bool b);
78 * auto args = std::make_tuple(1, false);
79 * int res = apply(foo, args);
82 template <class F, class Tuple>
83 constexpr auto apply(F&& f, Tuple&& t) -> decltype(
84 simgrid::xbt::bits::apply(std::forward<F>(f), std::forward<Tuple>(t),
85 std::make_index_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>()))
87 return simgrid::xbt::bits::apply(
88 std::forward<F>(f), std::forward<Tuple>(t),
89 std::make_index_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>());
92 template<class T> class Task;
94 /** Type-erased run-once task
96 * * Like std::function but callable only once.
97 * However, it works with move-only types.
99 * * Like std::packaged_task<> but without the shared state.
101 template<class R, class... Args>
102 class Task<R(Args...)> {
103 // Placeholder for some class type:
106 // Union used for storage:
107 typedef typename std::aligned_union<0,
109 std::pair<void(*)(),void*>,
110 std::pair<void(whatever::*)(), whatever*>
113 // Is F suitable for small buffer optimization?
115 static constexpr bool canSBO()
117 return sizeof(F) <= sizeof(TaskUnion) &&
118 alignof(F) <= alignof(TaskUnion);
121 static_assert(canSBO<std::reference_wrapper<whatever>>(),
122 "SBO not working for reference_wrapper");
124 // Call (and possibly destroy) the function:
125 typedef R (*call_function)(TaskUnion&, Args...);
126 // Destroy the function (of needed):
127 typedef void (*destroy_function)(TaskUnion&);
128 // Move the function (otherwise memcpy):
129 typedef void (*move_function)(TaskUnion& dest, TaskUnion& src);
131 // Vtable of functions for manipulating whatever is in the TaskUnion:
134 destroy_function destroy;
139 const TaskVtable* vtable_ = nullptr;
143 if (vtable_ && vtable_->destroy)
144 vtable_->destroy(buffer_);
148 Task() { /* Nothing to do */}
149 explicit Task(std::nullptr_t) { /* Nothing to do */}
155 Task(Task const&) = delete;
157 Task(Task&& that) noexcept
159 if (that.vtable_ && that.vtable_->move)
160 that.vtable_->move(buffer_, that.buffer_);
162 std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
163 vtable_ = std::move(that.vtable_);
164 that.vtable_ = nullptr;
166 Task& operator=(Task const& that) = delete;
167 Task& operator=(Task&& that) noexcept
170 if (that.vtable_ && that.vtable_->move)
171 that.vtable_->move(buffer_, that.buffer_);
173 std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
174 vtable_ = std::move(that.vtable_);
175 that.vtable_ = nullptr;
181 typename std::enable_if<canSBO<F>()>::type
184 const static TaskVtable vtable {
186 [](TaskUnion& buffer, Args... args) {
187 auto* src = reinterpret_cast<F*>(&buffer);
188 F code = std::move(*src);
190 // NOTE: std::forward<Args>(args)... is correct.
191 return code(std::forward<Args>(args)...);
194 std::is_trivially_destructible<F>::value ?
195 static_cast<destroy_function>(nullptr) :
196 [](TaskUnion& buffer) {
197 auto* code = reinterpret_cast<F*>(&buffer);
201 [](TaskUnion& dst, TaskUnion& src) {
202 auto* src_code = reinterpret_cast<F*>(&src);
203 auto* dst_code = reinterpret_cast<F*>(&dst);
204 new(dst_code) F(std::move(*src_code));
208 new(&buffer_) F(std::move(code));
212 template <class F> typename std::enable_if<not canSBO<F>()>::type init(F code)
214 const static TaskVtable vtable {
216 [](TaskUnion& buffer, Args... args) {
217 // Delete F when we go out of scope:
218 std::unique_ptr<F> code(*reinterpret_cast<F**>(&buffer));
219 // NOTE: std::forward<Args>(args)... is correct.
220 return (*code)(std::forward<Args>(args)...);
223 [](TaskUnion& buffer) {
224 F* code = *reinterpret_cast<F**>(&buffer);
230 *reinterpret_cast<F**>(&buffer_) = new F(std::move(code));
235 template <class F> explicit Task(F code) { this->init(std::move(code)); }
237 operator bool() const { return vtable_ != nullptr; }
238 bool operator!() const { return vtable_ == nullptr; }
240 R operator()(Args... args)
242 if (vtable_ == nullptr)
243 throw std::bad_function_call();
244 const TaskVtable* vtable = vtable_;
246 // NOTE: std::forward<Args>(args)... is correct.
247 // see C++ [func.wrap.func.inv] for an example
248 return vtable->call(buffer_, std::forward<Args>(args)...);
252 template<class F, class... Args>
255 std::tuple<Args...> args_;
256 typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
258 TaskImpl(F code, std::tuple<Args...> args) :
259 code_(std::move(code)),
260 args_(std::move(args))
262 result_type operator()()
264 return simgrid::xbt::apply(std::move(code_), std::move(args_));
268 template <class F, class... Args> auto make_task(F code, Args... args) -> Task<decltype(code(std::move(args)...))()>
270 TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
271 return Task<decltype(code(std::move(args)...))()>(std::move(task));
275 } // namespace simgrid