Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
implement some more getters in surf::Link and s4u::Link
[simgrid.git] / include / xbt / functional.hpp
1 /* Copyright (c) 2015-2017. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #ifndef XBT_FUNCTIONAL_HPP
7 #define XBT_FUNCTIONAL_HPP
8
9 #include <cstddef>
10 #include <cstdlib>
11 #include <cstring>
12
13 #include <array>
14 #include <exception>
15 #include <functional>
16 #include <memory>
17 #include <string>
18 #include <tuple>
19 #include <type_traits>
20 #include <utility>
21 #include <vector>
22
23 #include "xbt/sysdep.h"
24 #include "xbt/utility.hpp"
25
26 namespace simgrid {
27 namespace xbt {
28
29 template<class F>
30 class MainFunction {
31 private:
32   F code_;
33   std::shared_ptr<const std::vector<std::string>> args_;
34 public:
35   MainFunction(F code, std::vector<std::string> args) :
36     code_(std::move(code)),
37     args_(std::make_shared<const std::vector<std::string>>(std::move(args)))
38   {}
39   void operator()() const
40   {
41     const int argc = args_->size();
42     std::vector<std::string> args = *args_;
43     if (not args.empty()) {
44       char noarg[] = {'\0'};
45       std::unique_ptr<char* []> argv(new char*[argc + 1]);
46       for (int i = 0; i != argc; ++i)
47         argv[i]  = args[i].empty() ? noarg : &args[i].front();
48       argv[argc] = nullptr;
49       code_(argc, argv.get());
50     } else
51       code_(argc, nullptr);
52   }
53 };
54
55 template<class F> inline
56 std::function<void()> wrapMain(F code, std::vector<std::string> args)
57 {
58   return MainFunction<F>(std::move(code), std::move(args));
59 }
60
61 template<class F> inline
62 std::function<void()> wrapMain(F code, int argc, const char*const argv[])
63 {
64   std::vector<std::string> args(argv, argv + argc);
65   return MainFunction<F>(std::move(code), std::move(args));
66 }
67
68 namespace bits {
69 template <class F, class Tuple, std::size_t... I>
70 constexpr auto apply(F&& f, Tuple&& t, simgrid::xbt::index_sequence<I...>)
71   -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...))
72 {
73   return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
74 }
75 }
76
77 /** Call a functional object with the values in the given tuple (from C++17)
78  *
79  *  @code{.cpp}
80  *  int foo(int a, bool b);
81  *
82  *  auto args = std::make_tuple(1, false);
83  *  int res = apply(foo, args);
84  *  @endcode
85  **/
86 template <class F, class Tuple>
87 constexpr auto apply(F&& f, Tuple&& t)
88   -> decltype(simgrid::xbt::bits::apply(
89     std::forward<F>(f),
90     std::forward<Tuple>(t),
91     simgrid::xbt::make_index_sequence<
92       std::tuple_size<typename std::decay<Tuple>::type>::value
93     >()))
94 {
95   return simgrid::xbt::bits::apply(
96     std::forward<F>(f),
97     std::forward<Tuple>(t),
98     simgrid::xbt::make_index_sequence<
99       std::tuple_size<typename std::decay<Tuple>::type>::value
100     >());
101 }
102
103 template<class T> class Task;
104
105 /** Type-erased run-once task
106  *
107  *  * Like std::function but callable only once.
108  *    However, it works with move-only types.
109  *
110  *  * Like std::packaged_task<> but without the shared state.
111  */
112 template<class R, class... Args>
113 class Task<R(Args...)> {
114 private:
115
116   // Placeholder for some class type:
117   struct whatever {};
118
119   // Union used for storage:
120 #if 0
121   typedef typename std::aligned_union<0,
122     void*,
123     std::pair<void(*)(),void*>,
124     std::pair<void(whatever::*)(), whatever*>
125   >::type TaskUnion;
126 #else
127   union TaskUnion {
128     void* ptr;
129     std::pair<void(*)(),void*> funcptr;
130     std::pair<void(whatever::*)(), whatever*> memberptr;
131     char any1[sizeof(std::pair<void(*)(),void*>)];
132     char any2[sizeof(std::pair<void(whatever::*)(), whatever*>)];
133     TaskUnion() { /* Nothing to do */}
134     ~TaskUnion() { /* Nothing to do */}
135   };
136 #endif
137
138   // Is F suitable for small buffer optimization?
139   template<class F>
140   static constexpr bool canSBO()
141   {
142     return sizeof(F) <= sizeof(TaskUnion) &&
143       alignof(F) <= alignof(TaskUnion);
144   }
145
146   static_assert(canSBO<std::reference_wrapper<whatever>>(),
147     "SBO not working for reference_wrapper");
148
149   // Call (and possibly destroy) the function:
150   typedef R (*call_function)(TaskUnion&, Args...);
151   // Destroy the function (of needed):
152   typedef void (*destroy_function)(TaskUnion&);
153   // Move the function (otherwise memcpy):
154   typedef void (*move_function)(TaskUnion& dest, TaskUnion& src);
155
156   // Vtable of functions for manipulating whatever is in the TaskUnion:
157   struct TaskVtable {
158     call_function call;
159     destroy_function destroy;
160     move_function move;
161   };
162
163   TaskUnion buffer_;
164   const TaskVtable* vtable_ = nullptr;
165
166   void clear()
167   {
168     if (vtable_ && vtable_->destroy)
169       vtable_->destroy(buffer_);
170   }
171
172 public:
173   Task() { /* Nothing to do */}
174   Task(std::nullptr_t) { /* Nothing to do */}
175   ~Task()
176   {
177     this->clear();
178   }
179
180   Task(Task const&) = delete;
181
182   Task(Task&& that)
183   {
184     if (that.vtable_ && that.vtable_->move)
185       that.vtable_->move(buffer_, that.buffer_);
186     else
187       std::memcpy(&buffer_, &that.buffer_, sizeof(buffer_));
188     vtable_ = that.vtable_;
189     that.vtable_ = nullptr;
190   }
191   Task& operator=(Task that)
192   {
193     this->clear();
194     if (that.vtable_ && that.vtable_->move)
195       that.vtable_->move(buffer_, that.buffer_);
196     else
197       std::memcpy(&buffer_, &that.buffer_, sizeof(buffer_));
198     vtable_ = that.vtable_;
199     that.vtable_ = nullptr;
200     return *this;
201   }
202
203 private:
204
205   template<class F>
206   typename std::enable_if<canSBO<F>()>::type
207   init(F code)
208   {
209     const static TaskVtable vtable {
210       // Call:
211       [](TaskUnion& buffer, Args... args) {
212         F* src = reinterpret_cast<F*>(&buffer);
213         F code = std::move(*src);
214         src->~F();
215         return code(std::forward<Args>(args)...);
216       },
217       // Destroy:
218       std::is_trivially_destructible<F>::value ?
219       static_cast<destroy_function>(nullptr) :
220       [](TaskUnion& buffer) {
221         F* code = reinterpret_cast<F*>(&buffer);
222         code->~F();
223       },
224       // Move:
225       [](TaskUnion& dst, TaskUnion& src) {
226         F* src_code = reinterpret_cast<F*>(&src);
227         F* dst_code = reinterpret_cast<F*>(&dst);
228         new(dst_code) F(std::move(*src_code));
229         src_code->~F();
230       }
231     };
232     new(&buffer_) F(std::move(code));
233     vtable_ = &vtable;
234   }
235
236   template <class F> typename std::enable_if<not canSBO<F>()>::type init(F code)
237   {
238     const static TaskVtable vtable {
239       // Call:
240       [](TaskUnion& buffer, Args... args) {
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