Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
get rid of xbt_os_thread_yield() using C++11
[simgrid.git] / include / xbt / functional.hpp
1 /* Copyright (c) 2015-2018. The SimGrid Team. All rights reserved.          */
2
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. */
5
6 #ifndef XBT_FUNCTIONAL_HPP
7 #define XBT_FUNCTIONAL_HPP
8
9 #include <xbt/sysdep.h>
10 #include <xbt/utility.hpp>
11
12 #include <cstddef>
13 #include <cstdlib>
14 #include <cstring>
15
16 #include <array>
17 #include <exception>
18 #include <functional>
19 #include <memory>
20 #include <string>
21 #include <tuple>
22 #include <type_traits>
23 #include <utility>
24 #include <vector>
25
26 namespace simgrid {
27 namespace xbt {
28
29 template<class F>
30 class MainFunction {
31 private:
32   F code_;
33   std::shared_ptr<const std::vector<std::string>> args_;
34 public:
35   MainFunction(F code, std::vector<std::string> args) :
36     code_(std::move(code)),
37     args_(std::make_shared<const std::vector<std::string>>(std::move(args)))
38   {}
39   void operator()() const
40   {
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();
48       argv[argc] = nullptr;
49       code_(argc, argv.get());
50     } else
51       code_(argc, nullptr);
52   }
53 };
54
55 template <class F>
56 inline XBT_ATTRIB_DEPRECATED_v323("Please use wrap_main()") std::function<void()> wrapMain(
57     F code, std::vector<std::string> args)
58 {
59   return MainFunction<F>(std::move(code), std::move(args));
60 }
61
62 template <class F> inline std::function<void()> wrap_main(F code, std::vector<std::string> args)
63 {
64   return MainFunction<F>(std::move(code), std::move(args));
65 }
66
67 template <class F>
68 inline XBT_ATTRIB_DEPRECATED_v323("Please use wrap_main()") std::function<void()> wrapMain(F code, int argc,
69                                                                                            const char* const argv[])
70 {
71   std::vector<std::string> args(argv, argv + argc);
72   return MainFunction<F>(std::move(code), std::move(args));
73 }
74 template <class F> inline std::function<void()> wrap_main(F code, int argc, const char* const argv[])
75 {
76   std::vector<std::string> args(argv, argv + argc);
77   return MainFunction<F>(std::move(code), std::move(args));
78 }
79
80 namespace bits {
81 template <class F, class Tuple, std::size_t... I>
82 constexpr auto apply(F&& f, Tuple&& t, simgrid::xbt::index_sequence<I...>)
83   -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...))
84 {
85   return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
86 }
87 }
88
89 /** Call a functional object with the values in the given tuple (from C++17)
90  *
91  *  @code{.cpp}
92  *  int foo(int a, bool b);
93  *
94  *  auto args = std::make_tuple(1, false);
95  *  int res = apply(foo, args);
96  *  @endcode
97  **/
98 template <class F, class Tuple>
99 constexpr auto apply(F&& f, Tuple&& t)
100   -> decltype(simgrid::xbt::bits::apply(
101     std::forward<F>(f),
102     std::forward<Tuple>(t),
103     simgrid::xbt::make_index_sequence<
104       std::tuple_size<typename std::decay<Tuple>::type>::value
105     >()))
106 {
107   return simgrid::xbt::bits::apply(
108     std::forward<F>(f),
109     std::forward<Tuple>(t),
110     simgrid::xbt::make_index_sequence<
111       std::tuple_size<typename std::decay<Tuple>::type>::value
112     >());
113 }
114
115 template<class T> class Task;
116
117 /** Type-erased run-once task
118  *
119  *  * Like std::function but callable only once.
120  *    However, it works with move-only types.
121  *
122  *  * Like std::packaged_task<> but without the shared state.
123  */
124 template<class R, class... Args>
125 class Task<R(Args...)> {
126 private:
127
128   // Placeholder for some class type:
129   struct whatever {};
130
131   // Union used for storage:
132 #if 0
133   typedef typename std::aligned_union<0,
134     void*,
135     std::pair<void(*)(),void*>,
136     std::pair<void(whatever::*)(), whatever*>
137   >::type TaskUnion;
138 #else
139   union TaskUnion {
140     void* ptr;
141     std::pair<void(*)(),void*> funcptr;
142     std::pair<void(whatever::*)(), whatever*> memberptr;
143     char any1[sizeof(std::pair<void(*)(),void*>)];
144     char any2[sizeof(std::pair<void(whatever::*)(), whatever*>)];
145     TaskUnion() { /* Nothing to do */}
146     ~TaskUnion() { /* Nothing to do */}
147   };
148 #endif
149
150   // Is F suitable for small buffer optimization?
151   template<class F>
152   static constexpr bool canSBO()
153   {
154     return sizeof(F) <= sizeof(TaskUnion) &&
155       alignof(F) <= alignof(TaskUnion);
156   }
157
158   static_assert(canSBO<std::reference_wrapper<whatever>>(),
159     "SBO not working for reference_wrapper");
160
161   // Call (and possibly destroy) the function:
162   typedef R (*call_function)(TaskUnion&, Args...);
163   // Destroy the function (of needed):
164   typedef void (*destroy_function)(TaskUnion&);
165   // Move the function (otherwise memcpy):
166   typedef void (*move_function)(TaskUnion& dest, TaskUnion& src);
167
168   // Vtable of functions for manipulating whatever is in the TaskUnion:
169   struct TaskVtable {
170     call_function call;
171     destroy_function destroy;
172     move_function move;
173   };
174
175   TaskUnion buffer_;
176   const TaskVtable* vtable_ = nullptr;
177
178   void clear()
179   {
180     if (vtable_ && vtable_->destroy)
181       vtable_->destroy(buffer_);
182   }
183
184 public:
185   Task() { /* Nothing to do */}
186   explicit Task(std::nullptr_t) { /* Nothing to do */}
187   ~Task()
188   {
189     this->clear();
190   }
191
192   Task(Task const&) = delete;
193
194   Task(Task&& that)
195   {
196     if (that.vtable_ && that.vtable_->move)
197       that.vtable_->move(buffer_, that.buffer_);
198     else
199       std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
200
201     vtable_ = that.vtable_;
202     that.vtable_ = nullptr;
203   }
204   Task& operator=(Task that)
205   {
206     this->clear();
207     if (that.vtable_ && that.vtable_->move)
208       that.vtable_->move(buffer_, that.buffer_);
209     else
210       std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
211     vtable_ = that.vtable_;
212     that.vtable_ = nullptr;
213     return *this;
214   }
215
216 private:
217
218   template<class F>
219   typename std::enable_if<canSBO<F>()>::type
220   init(F code)
221   {
222     const static TaskVtable vtable {
223       // Call:
224       [](TaskUnion& buffer, Args... args) {
225         F* src = reinterpret_cast<F*>(&buffer);
226         F code = std::move(*src);
227         src->~F();
228         return code(std::forward<Args>(args)...);
229       },
230       // Destroy:
231       std::is_trivially_destructible<F>::value ?
232       static_cast<destroy_function>(nullptr) :
233       [](TaskUnion& buffer) {
234         F* code = reinterpret_cast<F*>(&buffer);
235         code->~F();
236       },
237       // Move:
238       [](TaskUnion& dst, TaskUnion& src) {
239         F* src_code = reinterpret_cast<F*>(&src);
240         F* dst_code = reinterpret_cast<F*>(&dst);
241         new(dst_code) F(std::move(*src_code));
242         src_code->~F();
243       }
244     };
245     new(&buffer_) F(std::move(code));
246     vtable_ = &vtable;
247   }
248
249   template <class F> typename std::enable_if<not canSBO<F>()>::type init(F code)
250   {
251     const static TaskVtable vtable {
252       // Call:
253       [](TaskUnion& buffer, Args... args) {
254         // Delete F when we go out of scope:
255         std::unique_ptr<F> code(*reinterpret_cast<F**>(&buffer));
256         return (*code)(std::forward<Args>(args)...);
257       },
258       // Destroy:
259       [](TaskUnion& buffer) {
260         F* code = *reinterpret_cast<F**>(&buffer);
261         delete code;
262       },
263       // Move:
264       nullptr
265     };
266     *reinterpret_cast<F**>(&buffer_) = new F(std::move(code));
267     vtable_ = &vtable;
268   }
269
270 public:
271   template <class F> explicit Task(F code) { this->init(std::move(code)); }
272
273   operator bool() const { return vtable_ != nullptr; }
274   bool operator!() const { return vtable_ == nullptr; }
275
276   R operator()(Args... args)
277   {
278     if (vtable_ == nullptr)
279       throw std::bad_function_call();
280     const TaskVtable* vtable = vtable_;
281     vtable_ = nullptr;
282     return vtable->call(buffer_, std::forward<Args>(args)...);
283   }
284 };
285
286 template<class F, class... Args>
287 class TaskImpl {
288 private:
289   F code_;
290   std::tuple<Args...> args_;
291   typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
292 public:
293   TaskImpl(F code, std::tuple<Args...> args) :
294     code_(std::move(code)),
295     args_(std::move(args))
296   {}
297   result_type operator()()
298   {
299     return simgrid::xbt::apply(std::move(code_), std::move(args_));
300   }
301 };
302
303 template <class F, class... Args>
304 XBT_ATTRIB_DEPRECATED_v323("Please use make_task()") auto makeTask(F code, Args... args)
305     -> Task<decltype(code(std::move(args)...))()>
306 {
307   TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
308   return Task<decltype(code(std::move(args)...))()>(std::move(task));
309 }
310
311 template <class F, class... Args> auto make_task(F code, Args... args) -> Task<decltype(code(std::move(args)...))()>
312 {
313   TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
314   return Task<decltype(code(std::move(args)...))()>(std::move(task));
315 }
316 }
317 }
318
319 #endif