Logo AND Algorithmique Numérique Distribuée

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