Logo AND Algorithmique Numérique Distribuée

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