Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
memo.hh
Go to the documentation of this file.
1#pragma once
3
4#include "nix/util/fun.hh"
5
6#include <memory>
7#include <mutex>
8#include <optional>
9
10namespace nix {
11
18template<typename T>
19fun<T()> memo(fun<T()> f)
20{
21 struct State
22 {
23 fun<T()> compute;
24 std::once_flag flag;
25 std::optional<T> cached;
26
27 explicit State(fun<T()> compute)
28 : compute(std::move(compute))
29 {
30 }
31 };
32
33 auto state = std::shared_ptr<State>(new State(std::move(f)));
34 return [state]() -> T {
35 std::call_once(state->flag, [&]() { state->cached.emplace(state->compute()); });
36 return *state->cached;
37 };
38}
39
40} // namespace nix
Definition fun.hh:19
fun< T()> memo(fun< T()> f)
Definition memo.hh:19