Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
1fefcd84738174b29afbfeab94d5d481ec2b103a
[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   F code_;
31   std::shared_ptr<const std::vector<std::string>> args_;
32
33 public:
34   MainFunction(F code, std::vector<std::string>&& args)
35       : code_(std::move(code)), args_(std::make_shared<const std::vector<std::string>>(std::move(args)))
36   {
37   }
38   void operator()() const
39   {
40     const int argc                = args_->size();
41     std::vector<std::string> args = *args_;
42     if (not args.empty()) {
43       char noarg[] = {'\0'};
44       std::unique_ptr<char* []> argv(new char*[argc + 1]);
45       for (int i = 0; i != argc; ++i)
46         argv[i] = args[i].empty() ? noarg : &args[i].front();
47       argv[argc] = nullptr;
48       code_(argc, argv.get());
49     } else
50       code_(argc, nullptr);
51   }
52 };
53
54 template <class F> inline std::function<void()> wrap_main(F code, std::vector<std::string>&& args)
55 {
56   return MainFunction<F>(std::move(code), std::move(args));
57 }
58
59 template <class F> inline std::function<void()> wrap_main(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   // Placeholder for some class type:
112   struct whatever {};
113
114   // Union used for storage:
115   typedef typename std::aligned_union<0,
116     void*,
117     std::pair<void(*)(),void*>,
118     std::pair<void(whatever::*)(), whatever*>
119   >::type TaskUnion;
120
121   // Is F suitable for small buffer optimization?
122   template<class F>
123   static constexpr bool canSBO()
124   {
125     return sizeof(F) <= sizeof(TaskUnion) &&
126       alignof(F) <= alignof(TaskUnion);
127   }
128
129   static_assert(canSBO<std::reference_wrapper<whatever>>(),
130     "SBO not working for reference_wrapper");
131
132   // Call (and possibly destroy) the function:
133   typedef R (*call_function)(TaskUnion&, Args...);
134   // Destroy the function (of needed):
135   typedef void (*destroy_function)(TaskUnion&);
136   // Move the function (otherwise memcpy):
137   typedef void (*move_function)(TaskUnion& dest, TaskUnion& src);
138
139   // Vtable of functions for manipulating whatever is in the TaskUnion:
140   struct TaskVtable {
141     call_function call;
142     destroy_function destroy;
143     move_function move;
144   };
145
146   TaskUnion buffer_;
147   const TaskVtable* vtable_ = nullptr;
148
149   void clear()
150   {
151     if (vtable_ && vtable_->destroy)
152       vtable_->destroy(buffer_);
153   }
154
155 public:
156   Task() { /* Nothing to do */}
157   explicit Task(std::nullptr_t) { /* Nothing to do */}
158   ~Task()
159   {
160     this->clear();
161   }
162
163   Task(Task const&) = delete;
164
165   Task(Task&& that)
166   {
167     if (that.vtable_ && that.vtable_->move)
168       that.vtable_->move(buffer_, that.buffer_);
169     else
170       std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
171
172     vtable_ = that.vtable_;
173     that.vtable_ = nullptr;
174   }
175   Task& operator=(Task const& that) = delete;
176   Task& operator=(Task&& that)
177   {
178     this->clear();
179     if (that.vtable_ && that.vtable_->move)
180       that.vtable_->move(buffer_, that.buffer_);
181     else
182       std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
183     vtable_ = that.vtable_;
184     that.vtable_ = nullptr;
185     return *this;
186   }
187
188 private:
189   template<class F>
190   typename std::enable_if<canSBO<F>()>::type
191   init(F code)
192   {
193     const static TaskVtable vtable {
194       // Call:
195       [](TaskUnion& buffer, Args&&... args) {
196         F* src = reinterpret_cast<F*>(&buffer);
197         F code = std::move(*src);
198         src->~F();
199         return code(std::forward<Args>(args)...);
200       },
201       // Destroy:
202       std::is_trivially_destructible<F>::value ?
203       static_cast<destroy_function>(nullptr) :
204       [](TaskUnion& buffer) {
205         F* code = reinterpret_cast<F*>(&buffer);
206         code->~F();
207       },
208       // Move:
209       [](TaskUnion& dst, TaskUnion& src) {
210         F* src_code = reinterpret_cast<F*>(&src);
211         F* dst_code = reinterpret_cast<F*>(&dst);
212         new(dst_code) F(std::move(*src_code));
213         src_code->~F();
214       }
215     };
216     new(&buffer_) F(std::move(code));
217     vtable_ = &vtable;
218   }
219
220   template <class F> typename std::enable_if<not canSBO<F>()>::type init(F code)
221   {
222     const static TaskVtable vtable {
223       // Call:
224       [](TaskUnion& buffer, Args&&... args) {
225         // Delete F when we go out of scope:
226         std::unique_ptr<F> code(*reinterpret_cast<F**>(&buffer));
227         return (*code)(std::forward<Args>(args)...);
228       },
229       // Destroy:
230       [](TaskUnion& buffer) {
231         F* code = *reinterpret_cast<F**>(&buffer);
232         delete code;
233       },
234       // Move:
235       nullptr
236     };
237     *reinterpret_cast<F**>(&buffer_) = new F(std::move(code));
238     vtable_ = &vtable;
239   }
240
241 public:
242   template <class F> explicit Task(F code) { this->init(std::move(code)); }
243
244   operator bool() const { return vtable_ != nullptr; }
245   bool operator!() const { return vtable_ == nullptr; }
246
247   R operator()(Args&&... args)
248   {
249     if (vtable_ == nullptr)
250       throw std::bad_function_call();
251     const TaskVtable* vtable = vtable_;
252     vtable_ = nullptr;
253     return vtable->call(buffer_, std::forward<Args>(args)...);
254   }
255 };
256
257 template<class F, class... Args>
258 class TaskImpl {
259   F code_;
260   std::tuple<Args...> args_;
261   typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
262 public:
263   TaskImpl(F code, std::tuple<Args...> args) :
264     code_(std::move(code)),
265     args_(std::move(args))
266   {}
267   result_type operator()()
268   {
269     return simgrid::xbt::apply(std::move(code_), std::move(args_));
270   }
271 };
272
273 template <class F, class... Args> auto make_task(F code, Args... args) -> Task<decltype(code(std::move(args)...))()>
274 {
275   TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
276   return Task<decltype(code(std::move(args)...))()>(std::move(task));
277 }
278
279 } // namespace xbt
280 } // namespace simgrid
281 #endif