Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
inline another VM function, and kill another one, unused
[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  *  @endcode
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 #if 0
118   typedef typename std::aligned_union<0,
119     void*,
120     std::pair<void(*)(),void*>,
121     std::pair<void(whatever::*)(), whatever*>
122   >::type TaskUnion;
123 #else
124   union TaskUnion {
125     void* ptr;
126     std::pair<void(*)(),void*> funcptr;
127     std::pair<void(whatever::*)(), whatever*> memberptr;
128     char any1[sizeof(std::pair<void(*)(),void*>)];
129     char any2[sizeof(std::pair<void(whatever::*)(), whatever*>)];
130     TaskUnion() {}
131     ~TaskUnion() {}
132   };
133 #endif
134
135   // Is F suitable for small buffer optimization?
136   template<class F>
137   static constexpr bool canSBO()
138   {
139     return sizeof(F) <= sizeof(TaskUnion) &&
140       alignof(F) <= alignof(TaskUnion);
141   }
142
143   static_assert(canSBO<std::reference_wrapper<whatever>>(),
144     "SBO not working for reference_wrapper");
145
146   // Call (and possibly destroy) the function:
147   typedef R (*call_function)(TaskUnion&, Args...);
148   // Destroy the function (of needed):
149   typedef void (*destroy_function)(TaskUnion&);
150   // Move the function (otherwise memcpy):
151   typedef void (*move_function)(TaskUnion& dest, TaskUnion& src);
152
153   // Vtable of functions for manipulating whatever is in the TaskUnion:
154   struct TaskVtable {
155     call_function call;
156     destroy_function destroy;
157     move_function move;
158   };
159
160   TaskUnion buffer_;
161   const TaskVtable* vtable_ = nullptr;
162
163   void clear()
164   {
165     if (vtable_ && vtable_->destroy)
166       vtable_->destroy(buffer_);
167   }
168
169 public:
170
171   Task() {}
172   Task(std::nullptr_t) {}
173   ~Task()
174   {
175     this->clear();
176   }
177
178   Task(Task const&) = delete;
179
180   Task(Task&& that)
181   {
182     if (that.vtable_ && that.vtable_->move)
183       that.vtable_->move(buffer_, that.buffer_);
184     else
185       std::memcpy(&buffer_, &that.buffer_, sizeof(buffer_));
186     vtable_ = that.vtable_;
187     that.vtable_ = nullptr;
188   }
189   Task& operator=(Task that)
190   {
191     this->clear();
192     if (that.vtable_ && that.vtable_->move)
193       that.vtable_->move(buffer_, that.buffer_);
194     else
195       std::memcpy(&buffer_, &that.buffer_, sizeof(buffer_));
196     vtable_ = that.vtable_;
197     that.vtable_ = nullptr;
198     return *this;
199   }
200
201 private:
202
203   template<class F>
204   typename std::enable_if<canSBO<F>()>::type
205   init(F code)
206   {
207     const static TaskVtable vtable {
208       // Call:
209       [](TaskUnion& buffer, Args... args) -> R {
210         F* src = reinterpret_cast<F*>(&buffer);
211         F code = std::move(*src);
212         src->~F();
213         code(std::forward<Args>(args)...);
214       },
215       // Destroy:
216       std::is_trivially_destructible<F>::value ?
217       static_cast<destroy_function>(nullptr) :
218       [](TaskUnion& buffer) {
219         F* code = reinterpret_cast<F*>(&buffer);
220         code->~F();
221       },
222       // Move:
223       [](TaskUnion& dst, TaskUnion& src) {
224         F* src_code = reinterpret_cast<F*>(&src);
225         F* dst_code = reinterpret_cast<F*>(&dst);
226         new(dst_code) F(std::move(*src_code));
227         src_code->~F();
228       }
229     };
230     new(&buffer_) F(std::move(code));
231     vtable_ = &vtable;
232   }
233
234   template<class F>
235   typename std::enable_if<!canSBO<F>()>::type
236   init(F code)
237   {
238     const static TaskVtable vtable {
239       // Call:
240       [](TaskUnion& buffer, Args... args) -> R {
241         // Delete F when we go out of scope:
242         std::unique_ptr<F> code(*reinterpret_cast<F**>(&buffer));
243         return (*code)(std::forward<Args>(args)...);
244       },
245       // Destroy:
246       [](TaskUnion& buffer) {
247         F* code = *reinterpret_cast<F**>(&buffer);
248         delete code;
249       },
250       // Move:
251       nullptr
252     };
253     *reinterpret_cast<F**>(&buffer_) = new F(std::move(code));
254     vtable_ = &vtable;
255   }
256
257 public:
258
259   template<class F>
260   Task(F code)
261   {
262     this->init(std::move(code));
263   }
264
265   operator bool() const { return vtable_ != nullptr; }
266   bool operator!() const { return vtable_ == nullptr; }
267
268   R operator()(Args... args)
269   {
270     if (vtable_ == nullptr)
271       throw std::bad_function_call();
272     const TaskVtable* vtable = vtable_;
273     vtable_ = nullptr;
274     return vtable->call(buffer_, std::forward<Args>(args)...);
275   }
276 };
277
278 template<class F, class... Args>
279 class TaskImpl {
280 private:
281   F code_;
282   std::tuple<Args...> args_;
283   typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
284 public:
285   TaskImpl(F code, std::tuple<Args...> args) :
286     code_(std::move(code)),
287     args_(std::move(args))
288   {}
289   result_type operator()()
290   {
291     return simgrid::xbt::apply(std::move(code_), std::move(args_));
292   }
293 };
294
295 template<class F, class... Args>
296 auto makeTask(F code, Args... args)
297 -> Task< decltype(code(std::move(args)...))() >
298 {
299   TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
300   return std::move(task);
301 }
302
303 }
304 }
305
306 #endif