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