Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
callback.hh
Go to the documentation of this file.
1#pragma once
3
4#include <cassert>
5#include <future>
6#include <functional>
7
8#include "nix/util/fun.hh"
9
10namespace nix {
11
17template<typename T>
18class Callback
19{
20 nix::fun<void(std::future<T>)> fun;
21 std::atomic_flag done = ATOMIC_FLAG_INIT;
22
23public:
24
25 Callback(nix::fun<void(std::future<T>)> fun)
26 : fun(fun)
27 {
28 }
29
30 // NOTE: std::function is noexcept move-constructible since C++20.
31 Callback(Callback && callback) noexcept(std::is_nothrow_move_constructible_v<decltype(fun)>)
32 : fun(std::move(callback.fun))
33 {
34 auto prev = callback.done.test_and_set();
35 if (prev)
36 done.test_and_set();
37 }
38
39 void operator()(T && t) noexcept
40 {
41 auto prev = done.test_and_set();
42 assert(!prev);
43 std::promise<T> promise;
44 promise.set_value(std::move(t));
45 fun(promise.get_future());
46 }
47
48 void rethrow(const std::exception_ptr & exc = std::current_exception()) noexcept
49 {
50 auto prev = done.test_and_set();
51 assert(!prev);
52 std::promise<T> promise;
53 promise.set_exception(exc);
54 fun(promise.get_future());
55 }
56};
57
58} // namespace nix
Definition fun.hh:19