Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
9849224987fb88876b740a976c487d530164c2b2
[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   int 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     return 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 namespace bits {
103
104   // Compute the maximum size taken by any of the given types:
105   template <class... T> struct max_size;
106   template <>
107   struct max_size<> : public std::integral_constant<std::size_t, 0> {};
108   template <class T>
109   struct max_size<T> : public std::integral_constant<std::size_t, sizeof(T)> {};
110   template <class T, class... U>
111   struct max_size<T, U...> : public std::integral_constant<std::size_t,
112     (sizeof(T) > max_size<U...>::value) ? sizeof(T) : max_size<U...>::value
113   > {};
114
115   struct whatever {};
116
117   // What we can store in a Task:
118   typedef void* ptr_callback;
119   struct funcptr_callback {
120     // Placeholder for any function pointer:
121     void(*callback)();
122     void* data;
123   };
124   struct member_funcptr_callback {
125     // Placeholder for any pointer to member function:
126     void (whatever::* callback)();
127     whatever* data;
128   };
129   constexpr std::size_t any_size = max_size<
130     ptr_callback,
131     funcptr_callback,
132     member_funcptr_callback
133   >::value;
134   typedef std::array<char, any_size> any_callback;
135
136   // Union of what we can store in a Task:
137   union TaskErasure {
138     ptr_callback ptr;
139     funcptr_callback funcptr;
140     member_funcptr_callback member_funcptr;
141     any_callback any;
142   };
143
144   // Can we copy F in Task (or do we have to use the heap)?
145   template<class F>
146   constexpr bool isUsableDirectlyInTask()
147   {
148     // The only types we can portably store directly in the Task are the
149     // trivially copyable ones (we can memcpy) which are small enough to fit:
150     return std::is_trivially_copyable<F>::value &&
151       sizeof(F) <= sizeof(bits::any_callback);
152   }
153
154 }
155
156 /** Type-erased run-once task
157  *
158  *  * Like std::function but callable only once.
159  *    However, it works with move-only types.
160  *
161  *  * Like std::packaged_task<> but without the shared state.
162  */
163 template<class R, class... Args>
164 class Task<R(Args...)> {
165 private:
166
167   typedef bits::TaskErasure TaskErasure;
168   struct TaskErasureVtable {
169     // Call (and possibly destroy) the function:
170     R (*call)(TaskErasure&, Args...);
171     // Destroy the function:
172     void (*destroy)(TaskErasure&);
173   };
174
175   TaskErasure code_;
176   const TaskErasureVtable* vtable_ = nullptr;
177
178 public:
179   Task() {}
180   Task(std::nullptr_t) {}
181   ~Task()
182   {
183     if (vtable_ && vtable_->destroy)
184       vtable_->destroy(code_);
185   }
186
187   Task(Task const&) = delete;
188   Task& operator=(Task const&) = delete;
189
190   Task(Task&& that)
191   {
192     std::memcpy(&code_, &that.code_, sizeof(code_));
193     vtable_ = that.vtable_;
194     that.vtable_ = nullptr;
195   }
196   Task& operator=(Task&& that)
197   {
198     if (vtable_ && vtable_->destroy)
199       vtable_->destroy(code_);
200     std::memcpy(&code_, &that.code_, sizeof(code_));
201     vtable_ = that.vtable_;
202     that.vtable_ = nullptr;
203     return *this;
204   }
205
206   template<class F,
207     typename = typename std::enable_if<bits::isUsableDirectlyInTask<F>()>::type>
208   Task(F const& code)
209   {
210     const static TaskErasureVtable vtable {
211       // Call:
212       [](TaskErasure& erasure, Args... args) -> R {
213         // We need to wrap F un a union because F might not have a default
214         // constructor: this is especially the case for lambdas.
215         union no_ctor {
216           no_ctor() {}
217           ~no_ctor() {}
218           F code ;
219         } code;
220         if (!std::is_empty<F>::value)
221           // AFAIU, this is safe as per [basic.types]:
222           std::memcpy(&code.code, erasure.any.data(), sizeof(code.code));
223         code.code(std::forward<Args>(args)...);
224       },
225       // Destroy:
226       nullptr
227     };
228     if (!std::is_empty<F>::value)
229       std::memcpy(code_.any.data(), &code, sizeof(code));
230     vtable_ = &vtable;
231   }
232
233   template<class F,
234     typename = typename std::enable_if<!bits::isUsableDirectlyInTask<F>()>::type>
235   Task(F code)
236   {
237     const static TaskErasureVtable vtable {
238       // Call:
239       [](TaskErasure& erasure, Args... args) -> R {
240         // Delete F when we go out of scope:
241         std::unique_ptr<F> code(static_cast<F*>(erasure.ptr));
242         (*code)(std::forward<Args>(args)...);
243       },
244       // Destroy:
245       [](TaskErasure& erasure) {
246         F* code = static_cast<F*>(erasure.ptr);
247         delete code;
248       }
249     };
250     code_.ptr = new F(std::move(code));
251     vtable_ = &vtable;
252   }
253
254   template<class F>
255   Task(std::reference_wrapper<F> code)
256   {
257     const static TaskErasureVtable vtable {
258       // Call:
259       [](TaskErasure& erasure, Args... args) -> R {
260         F* code = static_cast<F*>(erasure.ptr);
261         (*code)(std::forward<Args>(args)...);
262       },
263       // Destroy:
264       nullptr
265     };
266     code.code_.ptr = code.get();
267     vtable_ = &vtable;
268   }
269
270   operator bool() const { return vtable_ != nullptr; }
271   bool operator!() const { return vtable_ == nullptr; }
272
273   R operator()(Args... args)
274   {
275     if (!vtable_)
276       throw std::bad_function_call();
277     const TaskErasureVtable* vtable = vtable_;
278     vtable_ = nullptr;
279     return vtable->call(code_, std::forward<Args>(args)...);
280   }
281 };
282
283 template<class F, class... Args>
284 class TaskImpl {
285 private:
286   F code_;
287   std::tuple<Args...> args_;
288   typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
289 public:
290   TaskImpl(F code, std::tuple<Args...> args) :
291     code_(std::move(code)),
292     args_(std::move(args))
293   {}
294   result_type operator()()
295   {
296     return simgrid::xbt::apply(std::move(code_), std::move(args_));
297   }
298 };
299
300 template<class F, class... Args>
301 auto makeTask(F code, Args... args)
302 -> Task< decltype(code(std::move(args)...))() >
303 {
304   TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
305   return std::move(task);
306 }
307
308 }
309 }
310
311 #endif