Skip to content

Commit 1b4de42

Browse files
Merge pull request #5090 from romainbrenguier/feature/lazy
Add a lazyt class for delaying computations
2 parents a60f45c + 8dbbca1 commit 1b4de42

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

src/util/lazy.h

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*******************************************************************\
2+
3+
Module: Util
4+
5+
Author: Romain Brenguier, [email protected]
6+
7+
\*******************************************************************/
8+
9+
#ifndef CPROVER_UTIL_LAZY_H
10+
#define CPROVER_UTIL_LAZY_H
11+
12+
#include <functional>
13+
#include <util/optional.h>
14+
15+
template <typename valuet>
16+
class lazyt
17+
{
18+
public:
19+
/// Delay the computation of \p fun to the next time the \c force method
20+
/// is called.
21+
static lazyt from_fun(std::function<valuet()> fun)
22+
{
23+
return lazyt{std::move(fun)};
24+
}
25+
26+
/// Force the computation of the value. If it was already computed,
27+
/// return the same result.
28+
valuet force()
29+
{
30+
if(value)
31+
return *value;
32+
value = evaluation_function();
33+
return *value;
34+
}
35+
36+
private:
37+
optionalt<valuet> value;
38+
std::function<valuet()> evaluation_function;
39+
40+
explicit lazyt(std::function<valuet()> fun)
41+
: evaluation_function(std::move(fun))
42+
{
43+
}
44+
};
45+
46+
#endif // CPROVER_UTIL_LAZY_H

unit/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ SRC += analyses/ai/ai.cpp \
7474
util/irep_sharing.cpp \
7575
util/json_array.cpp \
7676
util/json_object.cpp \
77+
util/lazy.cpp \
7778
util/memory_info.cpp \
7879
util/message.cpp \
7980
util/optional.cpp \

unit/util/lazy.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*******************************************************************\
2+
3+
Module: Unit tests for lazy
4+
5+
Author: Romain Brenguier, [email protected]
6+
7+
\*******************************************************************/
8+
9+
#include <testing-utils/use_catch.h>
10+
#include <util/lazy.h>
11+
12+
SCENARIO("lazy test", "[core][util][lazy]")
13+
{
14+
std::size_t call_counter = 0;
15+
auto length_with_counter = [&call_counter](const std::string &s) {
16+
++call_counter;
17+
return s.length();
18+
};
19+
auto lazy_length =
20+
lazyt<int>::from_fun([&]() { return length_with_counter("foo"); });
21+
22+
REQUIRE(call_counter == 0);
23+
auto result = lazy_length.force();
24+
REQUIRE(call_counter == 1);
25+
REQUIRE(result == 3);
26+
result = lazy_length.force();
27+
REQUIRE(call_counter == 1);
28+
REQUIRE(result == 3);
29+
}

0 commit comments

Comments
 (0)