Logo AND Algorithmique Numérique Distribuée

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