1 /* Copyright (c) 2015-2019. The SimGrid Team. All rights reserved. */
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. */
6 #ifndef XBT_FUNCTIONAL_HPP
7 #define XBT_FUNCTIONAL_HPP
9 #include <xbt/sysdep.h>
10 #include <xbt/utility.hpp>
22 #include <type_traits>
29 template <class F> class MainFunction {
31 std::shared_ptr<const std::vector<std::string>> args_;
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)))
38 void operator()() const
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();
48 code_(argc, argv.get());
54 template <class F> inline std::function<void()> wrap_main(F code, std::vector<std::string>&& args)
56 return MainFunction<F>(std::move(code), std::move(args));
59 template <class F> inline std::function<void()> wrap_main(F code, int argc, const char* const argv[])
61 std::vector<std::string> args(argv, argv + argc);
62 return MainFunction<F>(std::move(code), std::move(args));
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))...))
70 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
74 /** Call a functional object with the values in the given tuple (from C++17)
77 * int foo(int a, bool b);
79 * auto args = std::make_tuple(1, false);
80 * int res = apply(foo, args);
83 template <class F, class Tuple>
84 constexpr auto apply(F&& f, Tuple&& t)
85 -> decltype(simgrid::xbt::bits::apply(
87 std::forward<Tuple>(t),
88 simgrid::xbt::make_index_sequence<
89 std::tuple_size<typename std::decay<Tuple>::type>::value
92 return simgrid::xbt::bits::apply(
94 std::forward<Tuple>(t),
95 simgrid::xbt::make_index_sequence<
96 std::tuple_size<typename std::decay<Tuple>::type>::value
100 template<class T> class Task;
102 /** Type-erased run-once task
104 * * Like std::function but callable only once.
105 * However, it works with move-only types.
107 * * Like std::packaged_task<> but without the shared state.
109 template<class R, class... Args>
110 class Task<R(Args...)> {
111 // Placeholder for some class type:
114 // Union used for storage:
115 typedef typename std::aligned_union<0,
117 std::pair<void(*)(),void*>,
118 std::pair<void(whatever::*)(), whatever*>
121 // Is F suitable for small buffer optimization?
123 static constexpr bool canSBO()
125 return sizeof(F) <= sizeof(TaskUnion) &&
126 alignof(F) <= alignof(TaskUnion);
129 static_assert(canSBO<std::reference_wrapper<whatever>>(),
130 "SBO not working for reference_wrapper");
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);
139 // Vtable of functions for manipulating whatever is in the TaskUnion:
142 destroy_function destroy;
147 const TaskVtable* vtable_ = nullptr;
151 if (vtable_ && vtable_->destroy)
152 vtable_->destroy(buffer_);
156 Task() { /* Nothing to do */}
157 explicit Task(std::nullptr_t) { /* Nothing to do */}
163 Task(Task const&) = delete;
167 if (that.vtable_ && that.vtable_->move)
168 that.vtable_->move(buffer_, that.buffer_);
170 std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
172 vtable_ = that.vtable_;
173 that.vtable_ = nullptr;
175 Task& operator=(Task const& that) = delete;
176 Task& operator=(Task&& that)
179 if (that.vtable_ && that.vtable_->move)
180 that.vtable_->move(buffer_, that.buffer_);
182 std::memcpy(static_cast<void*>(&buffer_), static_cast<void*>(&that.buffer_), sizeof(buffer_));
183 vtable_ = that.vtable_;
184 that.vtable_ = nullptr;
190 typename std::enable_if<canSBO<F>()>::type
193 const static TaskVtable vtable {
195 [](TaskUnion& buffer, Args&&... args) {
196 F* src = reinterpret_cast<F*>(&buffer);
197 F code = std::move(*src);
199 return code(std::forward<Args>(args)...);
202 std::is_trivially_destructible<F>::value ?
203 static_cast<destroy_function>(nullptr) :
204 [](TaskUnion& buffer) {
205 F* code = reinterpret_cast<F*>(&buffer);
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));
216 new(&buffer_) F(std::move(code));
220 template <class F> typename std::enable_if<not canSBO<F>()>::type init(F code)
222 const static TaskVtable vtable {
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)...);
230 [](TaskUnion& buffer) {
231 F* code = *reinterpret_cast<F**>(&buffer);
237 *reinterpret_cast<F**>(&buffer_) = new F(std::move(code));
242 template <class F> explicit Task(F code) { this->init(std::move(code)); }
244 operator bool() const { return vtable_ != nullptr; }
245 bool operator!() const { return vtable_ == nullptr; }
247 R operator()(Args&&... args)
249 if (vtable_ == nullptr)
250 throw std::bad_function_call();
251 const TaskVtable* vtable = vtable_;
253 return vtable->call(buffer_, std::forward<Args>(args)...);
257 template<class F, class... Args>
260 std::tuple<Args...> args_;
261 typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
263 TaskImpl(F code, std::tuple<Args...> args) :
264 code_(std::move(code)),
265 args_(std::move(args))
267 result_type operator()()
269 return simgrid::xbt::apply(std::move(code_), std::move(args_));
273 template <class F, class... Args> auto make_task(F code, Args... args) -> Task<decltype(code(std::move(args)...))()>
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));
280 } // namespace simgrid