Logo AND Algorithmique Numérique Distribuée

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