Jlm
Loading...
Searching...
No Matches
IteratorWrapperTests.cpp
Go to the documentation of this file.
1/*
2 * Copyright 2025 HÃ¥vard Krogstie <krogstie.havard@gmail.com>
3 * See COPYING for terms of redistribution.
4 */
5
6#include <gtest/gtest.h>
7
10
11#include <memory>
12#include <unordered_set>
13#include <vector>
14
15TEST(IteratorWrapperTests, TestPtrVector)
16{
17 int a = 10;
18 int b = 20;
19 int c = 30;
20
21 std::vector<int *> ints = { &a, &b, &c };
22 using ItType = jlm::util::PtrIterator<int, decltype(ints)::iterator>;
23
24 // Act 1 + Assert 1 - iterate manually using operator ++
25 ItType it(ints.begin());
26 EXPECT_EQ(*it, 10);
27 it++;
28 EXPECT_EQ(*it, 20);
29 it++;
30 EXPECT_NE(it, ItType(ints.end()));
31 it++;
32 EXPECT_EQ(it, ItType(ints.end()));
33
34 // Act 2 - modify targets through range based for loop
35 jlm::util::IteratorRange range(ItType(ints.begin()), ItType(ints.end()));
36 for (auto & i : range)
37 {
38 i++;
39 }
40
41 // Assert 2
42 EXPECT_EQ(a, 11);
43 EXPECT_EQ(b, 21);
44 EXPECT_EQ(c, 31);
45}
46
47TEST(IteratorWrapperTests, TestPtrUnorderedSet)
48{
49 int a = 10;
50 int b = 20;
51 int c = 30;
52
53 std::unordered_set<int *> set = { &a, &b, &c };
54 using ItType = jlm::util::PtrIterator<int, decltype(set)::iterator>;
55
56 // Act - modify targets through range based for loop
57 jlm::util::IteratorRange range(ItType(set.begin()), ItType(set.end()));
58 for (auto & i : range)
59 {
60 i++;
61 }
62
63 // Assert
64 EXPECT_EQ(a, 11);
65 EXPECT_EQ(b, 21);
66 EXPECT_EQ(c, 31);
67}
68
69TEST(IteratorWrapperTests, TestUniquePtrVector)
70{
71 // Arrange
72 std::vector<std::unique_ptr<int>> vector;
73 vector.emplace_back(std::make_unique<int>(10));
74 vector.emplace_back(std::make_unique<int>(20));
75 vector.emplace_back(std::make_unique<int>(30));
76
77 // The iterator still works with a const_iterator, as the pointer itself is not const
78 using ItType = jlm::util::PtrIterator<int, decltype(vector)::const_iterator>;
79
80 // Act
81 jlm::util::IteratorRange range(ItType(vector.begin()), ItType(vector.end()));
82 for (auto & i : range)
83 {
84 i++;
85 }
86
87 // Assert
88 EXPECT_EQ(*vector[0], 11);
89 EXPECT_EQ(*vector[1], 21);
90 EXPECT_EQ(*vector[2], 31);
91}
92
93TEST(IteratorWrapperTests, TestMapValuePtr)
94{
95 // Arrange
96 std::unordered_map<size_t, std::unique_ptr<int>> map;
97 map.insert({ 1, std::make_unique<int>(10) });
98 map.insert({ 2, std::make_unique<int>(20) });
99 map.insert({ 3, std::make_unique<int>(30) });
100
101 // The iterator still works with a const_iterator, as the pointer itself is not const
102 using ItType = jlm::util::MapValuePtrIterator<int, decltype(map)::const_iterator>;
103
104 // Act
105 jlm::util::IteratorRange range(ItType(map.begin()), ItType(map.end()));
106 for (auto & i : range)
107 {
108 i++;
109 }
110
111 // Assert
112 EXPECT_EQ(*map[1], 11);
113 EXPECT_EQ(*map[2], 21);
114 EXPECT_EQ(*map[3], 31);
115}
TEST(IteratorWrapperTests, TestPtrVector)