Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Fix compilation
[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 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     // TODO, detect availability std::is_trivially_copyable / workaround
149 #if 1
150     // std::is_trivially_copyable is not available before GCC 5.
151     return false;
152 #else
153     // The only types we can portably store directly in the Task are the
154     // trivially copyable ones (we can memcpy) which are small enough to fit:
155     return std::is_trivially_copyable<F>::value &&
156       sizeof(F) <= sizeof(bits::any_callback);
157 #endif
158   }
159
160 }
161
162 /** Type-erased run-once task
163  *
164  *  * Like std::function but callable only once.
165  *    However, it works with move-only types.
166  *
167  *  * Like std::packaged_task<> but without the shared state.
168  */
169 template<class R, class... Args>
170 class Task<R(Args...)> {
171 private:
172
173   typedef bits::TaskErasure TaskErasure;
174   struct TaskErasureVtable {
175     // Call (and possibly destroy) the function:
176     R (*call)(TaskErasure&, Args...);
177     // Destroy the function:
178     void (*destroy)(TaskErasure&);
179   };
180
181   TaskErasure code_;
182   const TaskErasureVtable* vtable_ = nullptr;
183
184 public:
185   Task() {}
186   Task(std::nullptr_t) {}
187   ~Task()
188   {
189     if (vtable_ && vtable_->destroy)
190       vtable_->destroy(code_);
191   }
192
193   Task(Task const&) = delete;
194   Task& operator=(Task const&) = delete;
195
196   Task(Task&& that)
197   {
198     std::memcpy(&code_, &that.code_, sizeof(code_));
199     vtable_ = that.vtable_;
200     that.vtable_ = nullptr;
201   }
202   Task& operator=(Task&& that)
203   {
204     if (vtable_ && vtable_->destroy)
205       vtable_->destroy(code_);
206     std::memcpy(&code_, &that.code_, sizeof(code_));
207     vtable_ = that.vtable_;
208     that.vtable_ = nullptr;
209     return *this;
210   }
211
212   template<class F,
213     typename = typename std::enable_if<bits::isUsableDirectlyInTask<F>()>::type>
214   Task(F const& code)
215   {
216     const static TaskErasureVtable vtable {
217       // Call:
218       [](TaskErasure& erasure, Args... args) -> R {
219         // We need to wrap F un a union because F might not have a default
220         // constructor: this is especially the case for lambdas.
221         union no_ctor {
222           no_ctor() {}
223           ~no_ctor() {}
224           F code ;
225         } code;
226         if (!std::is_empty<F>::value)
227           // AFAIU, this is safe as per [basic.types]:
228           std::memcpy(&code.code, erasure.any.data(), sizeof(code.code));
229         code.code(std::forward<Args>(args)...);
230       },
231       // Destroy:
232       nullptr
233     };
234     if (!std::is_empty<F>::value)
235       std::memcpy(code_.any.data(), &code, sizeof(code));
236     vtable_ = &vtable;
237   }
238
239   template<class F,
240     typename = typename std::enable_if<!bits::isUsableDirectlyInTask<F>()>::type>
241   Task(F code)
242   {
243     const static TaskErasureVtable vtable {
244       // Call:
245       [](TaskErasure& erasure, Args... args) -> R {
246         // Delete F when we go out of scope:
247         std::unique_ptr<F> code(static_cast<F*>(erasure.ptr));
248         (*code)(std::forward<Args>(args)...);
249       },
250       // Destroy:
251       [](TaskErasure& erasure) {
252         F* code = static_cast<F*>(erasure.ptr);
253         delete code;
254       }
255     };
256     code_.ptr = new F(std::move(code));
257     vtable_ = &vtable;
258   }
259
260   template<class F>
261   Task(std::reference_wrapper<F> code)
262   {
263     const static TaskErasureVtable vtable {
264       // Call:
265       [](TaskErasure& erasure, Args... args) -> R {
266         F* code = static_cast<F*>(erasure.ptr);
267         (*code)(std::forward<Args>(args)...);
268       },
269       // Destroy:
270       nullptr
271     };
272     code.code_.ptr = code.get();
273     vtable_ = &vtable;
274   }
275
276   // TODO, Task(funcptr)
277   // TODO, Task(funcptr, data)
278   // TODO, Task(method, object)
279   // TODO, Task(stateless lambda)
280
281   operator bool() const { return vtable_ != nullptr; }
282   bool operator!() const { return vtable_ == nullptr; }
283
284   R operator()(Args... args)
285   {
286     if (!vtable_)
287       throw std::bad_function_call();
288     const TaskErasureVtable* vtable = vtable_;
289     vtable_ = nullptr;
290     return vtable->call(code_, std::forward<Args>(args)...);
291   }
292 };
293
294 template<class F, class... Args>
295 class TaskImpl {
296 private:
297   F code_;
298   std::tuple<Args...> args_;
299   typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
300 public:
301   TaskImpl(F code, std::tuple<Args...> args) :
302     code_(std::move(code)),
303     args_(std::move(args))
304   {}
305   result_type operator()()
306   {
307     return simgrid::xbt::apply(std::move(code_), std::move(args_));
308   }
309 };
310
311 template<class F, class... Args>
312 auto makeTask(F code, Args... args)
313 -> Task< decltype(code(std::move(args)...))() >
314 {
315   TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
316   return std::move(task);
317 }
318
319 }
320 }
321
322 #endif