Logo AND Algorithmique Numérique Distribuée

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