Logo AND Algorithmique Numérique Distribuée

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