1 /* Copyright (c) 2015-2018. 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>
10 #include <xbt/utility.hpp>
22 #include <type_traits>
29 template <class F> class MainFunction {
32 std::shared_ptr<const std::vector<std::string>> args_;
35 MainFunction(F code, std::vector<std::string> args)
36 : code_(std::move(code)), args_(std::make_shared<const std::vector<std::string>>(std::move(args)))
39 void operator()() const
41 const int argc = args_->size();
42 std::vector<std::string> args = *args_;
43 if (not args.empty()) {
44 char noarg[] = {'\0'};
45 std::unique_ptr<char* []> argv(new char*[argc + 1]);
46 for (int i = 0; i != argc; ++i)
47 argv[i] = args[i].empty() ? noarg : &args[i].front();
49 code_(argc, argv.get());
55 template <class F> inline std::function<void()> wrap_main(F code, std::vector<std::string> args)
57 return MainFunction<F>(std::move(code), std::move(args));
60 template <class F> inline std::function<void()> wrap_main(F code, int argc, const char* const argv[])
62 std::vector<std::string> args(argv, argv + argc);
63 return MainFunction<F>(std::move(code), std::move(args));
67 template <class F, class Tuple, std::size_t... I>
68 constexpr auto apply(F&& f, Tuple&& t, simgrid::xbt::index_sequence<I...>)
69 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...))
71 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
75 /** Call a functional object with the values in the given tuple (from C++17)
78 * int foo(int a, bool b);
80 * auto args = std::make_tuple(1, false);
81 * int res = apply(foo, args);
84 template <class F, class Tuple>
85 constexpr auto apply(F&& f, Tuple&& t)
86 -> decltype(simgrid::xbt::bits::apply(
88 std::forward<Tuple>(t),
89 simgrid::xbt::make_index_sequence<
90 std::tuple_size<typename std::decay<Tuple>::type>::value
93 return simgrid::xbt::bits::apply(
95 std::forward<Tuple>(t),
96 simgrid::xbt::make_index_sequence<
97 std::tuple_size<typename std::decay<Tuple>::type>::value
101 template<class T> class Task;
103 /** Type-erased run-once task
105 * * Like std::function but callable only once.
106 * However, it works with move-only types.
108 * * Like std::packaged_task<> but without the shared state.
110 template<class R, class... Args>
111 class Task<R(Args...)> {
114 // Placeholder for some class type:
117 // Union used for storage:
119 typedef typename std::aligned_union<0,
121 std::pair<void(*)(),void*>,
122 std::pair<void(whatever::*)(), whatever*>
127 std::pair<void(*)(),void*> funcptr;
128 std::pair<void(whatever::*)(), whatever*> memberptr;
129 char any1[sizeof(std::pair<void(*)(),void*>)];
130 char any2[sizeof(std::pair<void(whatever::*)(), whatever*>)];
131 TaskUnion() { /* Nothing to do */}
132 ~TaskUnion() { /* Nothing to do */}
136 // Is F suitable for small buffer optimization?
138 static constexpr bool canSBO()
140 return sizeof(F) <= sizeof(TaskUnion) &&
141 alignof(F) <= alignof(TaskUnion);
144 static_assert(canSBO<std::reference_wrapper<whatever>>(),
145 "SBO not working for reference_wrapper");
147 // Call (and possibly destroy) the function:
148 typedef R (*call_function)(TaskUnion&, Args...);
149 // Destroy the function (of needed):
150 typedef void (*destroy_function)(TaskUnion&);
151 // Move the function (otherwise memcpy):
152 typedef void (*move_function)(TaskUnion& dest, TaskUnion& src);
154 // Vtable of functions for manipulating whatever is in the TaskUnion:
157 destroy_function destroy;
162 const TaskVtable* vtable_ = nullptr;
166 if (vtable_ && vtable_->destroy)
167 vtable_->destroy(buffer_);
171 Task() { /* Nothing to do */}
172 explicit Task(std::nullptr_t) { /* Nothing to do */}
178 Task(Task const&) = delete;
182 if (that.vtable_ && that.vtable_->move)
183 that.vtable_->move(buffer_, that.buffer_);
185 std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
187 vtable_ = that.vtable_;
188 that.vtable_ = nullptr;
190 Task& operator=(Task that)
193 if (that.vtable_ && that.vtable_->move)
194 that.vtable_->move(buffer_, that.buffer_);
196 std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
197 vtable_ = that.vtable_;
198 that.vtable_ = nullptr;
205 typename std::enable_if<canSBO<F>()>::type
208 const static TaskVtable vtable {
210 [](TaskUnion& buffer, Args... args) {
211 F* src = reinterpret_cast<F*>(&buffer);
212 F code = std::move(*src);
214 return code(std::forward<Args>(args)...);
217 std::is_trivially_destructible<F>::value ?
218 static_cast<destroy_function>(nullptr) :
219 [](TaskUnion& buffer) {
220 F* code = reinterpret_cast<F*>(&buffer);
224 [](TaskUnion& dst, TaskUnion& src) {
225 F* src_code = reinterpret_cast<F*>(&src);
226 F* dst_code = reinterpret_cast<F*>(&dst);
227 new(dst_code) F(std::move(*src_code));
231 new(&buffer_) F(std::move(code));
235 template <class F> typename std::enable_if<not canSBO<F>()>::type init(F code)
237 const static TaskVtable vtable {
239 [](TaskUnion& buffer, Args... args) {
240 // Delete F when we go out of scope:
241 std::unique_ptr<F> code(*reinterpret_cast<F**>(&buffer));
242 return (*code)(std::forward<Args>(args)...);
245 [](TaskUnion& buffer) {
246 F* code = *reinterpret_cast<F**>(&buffer);
252 *reinterpret_cast<F**>(&buffer_) = new F(std::move(code));
257 template <class F> explicit Task(F code) { this->init(std::move(code)); }
259 operator bool() const { return vtable_ != nullptr; }
260 bool operator!() const { return vtable_ == nullptr; }
262 R operator()(Args... args)
264 if (vtable_ == nullptr)
265 throw std::bad_function_call();
266 const TaskVtable* vtable = vtable_;
268 return vtable->call(buffer_, std::forward<Args>(args)...);
272 template<class F, class... Args>
276 std::tuple<Args...> args_;
277 typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
279 TaskImpl(F code, std::tuple<Args...> args) :
280 code_(std::move(code)),
281 args_(std::move(args))
283 result_type operator()()
285 return simgrid::xbt::apply(std::move(code_), std::move(args_));
289 template <class F, class... Args> auto make_task(F code, Args... args) -> Task<decltype(code(std::move(args)...))()>
291 TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
292 return Task<decltype(code(std::move(args)...))()>(std::move(task));
296 template <class F, class... Args>
297 XBT_ATTRIB_DEPRECATED_v323("Please use make_task()") auto makeTask(F code, Args... args)
298 -> Task<decltype(code(std::move(args)...))()>
300 TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
301 return Task<decltype(code(std::move(args)...))()>(std::move(task));
305 inline XBT_ATTRIB_DEPRECATED_v323("Please use wrap_main()") std::function<void()> wrapMain(
306 F code, std::vector<std::string> args)
308 return MainFunction<F>(std::move(code), std::move(args));
312 inline XBT_ATTRIB_DEPRECATED_v323("Please use wrap_main()") std::function<void()> wrapMain(F code, int argc,
313 const char* const argv[])
315 std::vector<std::string> args(argv, argv + argc);
316 return MainFunction<F>(std::move(code), std::move(args));
320 } // namespace simgrid