Logo AND Algorithmique Numérique Distribuée

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