Skip to content

Commit cfb1203

Browse files
Unit tests for range
This gives examples of how to use the class.
1 parent 96b0ff4 commit cfb1203

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

unit/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ SRC += analyses/ai/ai.cpp \
4242
util/message.cpp \
4343
util/optional.cpp \
4444
util/pointer_offset_size.cpp \
45+
util/range.cpp \
4546
util/replace_symbol.cpp \
4647
util/sharing_map.cpp \
4748
util/sharing_node.cpp \

unit/util/range.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*******************************************************************\
2+
3+
Module: Unit tests for range
4+
5+
Author: Romain Brenguier, [email protected]
6+
7+
\*******************************************************************/
8+
9+
#include <vector>
10+
11+
#include <testing-utils/catch.hpp>
12+
#include <util/range.h>
13+
14+
SCENARIO("range tests", "[core][util][range]")
15+
{
16+
GIVEN("A vector with three strings")
17+
{
18+
std::vector<std::string> list;
19+
list.emplace_back("abc");
20+
list.emplace_back("cdef");
21+
list.emplace_back("acdef");
22+
auto range = make_range(list);
23+
std::size_t total_length = 0;
24+
THEN("Use range-for to compute the total length")
25+
{
26+
for(const auto &s : range)
27+
total_length += s.length();
28+
REQUIRE(total_length == 12);
29+
}
30+
THEN("Use map to compute individual lengths")
31+
{
32+
auto length_range = make_range(list).map<std::size_t>(
33+
[](const std::string &s) { return s.length(); });
34+
auto it = length_range.begin();
35+
REQUIRE(*it == 3);
36+
++it;
37+
REQUIRE(*it == 4);
38+
++it;
39+
REQUIRE(*it == 5);
40+
++it;
41+
REQUIRE(it == length_range.end());
42+
}
43+
THEN("Filter using lengths")
44+
{
45+
auto filtered_range = make_range(list).filter(
46+
[&](const std::string &s) { return s.length() == 4; });
47+
auto it = filtered_range.begin();
48+
REQUIRE(*it == "cdef");
49+
++it;
50+
REQUIRE(it == filtered_range.end());
51+
}
52+
THEN("Filter, map and use range-for on the same list")
53+
{
54+
auto range =
55+
make_range(list)
56+
.filter([&](const std::string &s) -> bool { return s[0] == 'a'; })
57+
.map<std::size_t>([&](const std::string &s) { return s.length(); });
58+
// Note that everything is performed on the fly, so none of the filter
59+
// and map functions have been computed yet, and no intermediary container
60+
// is created.
61+
std::size_t total = 0;
62+
for(const auto &l : range)
63+
total += l;
64+
REQUIRE(total == 8);
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)