Logo AND Algorithmique Numérique Distribuée

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