Logo AND Algorithmique Numérique Distribuée

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