summaryrefslogtreecommitdiffstats
path: root/library/cpp/iterator/ut/mapped_ut.cpp
blob: 15a8196edede6ca15114b492f7dcd119fc54c568 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <library/cpp/iterator/mapped.h>

#include <library/cpp/testing/gtest/gtest.h>

#include <util/generic/map.h>
#include <util/generic/vector.h>

using namespace testing;

namespace {
    struct TSelectFirst {
        const auto& operator()(const auto& pair) const {
            return pair.first;
        }
    };
}

TEST(TIterator, TMappedIteratorTest) {
    TVector<int> x = {1, 2, 3, 4, 5};
    auto it = MakeMappedIterator(x.begin(), [](int x) { return x + 7; });

    EXPECT_EQ(*it, 8);
    EXPECT_EQ(it[2], 10);

    TVector<std::pair<int, int>> pairs = {{1, 2}, {3, 4}, {5, 6}};
    auto firstIt = MakeMappedIterator(pairs.begin(), TSelectFirst{});
    EXPECT_EQ(*std::next(firstIt, 0), 1);
    EXPECT_EQ(*std::next(firstIt, 1), 3);
    EXPECT_EQ(*std::next(firstIt, 2), 5);
#if defined(_compiler_clang_) && defined(_linux_)
    static_assert(sizeof(pairs.begin()) == sizeof(firstIt), "empty mapper should not add size overhead");  // this check expected to hold, but not guaranteed to
#endif
}

TEST(TIterator, TMappedRangeTest) {
    TVector<int> x = {1, 2, 3, 4, 5};

    EXPECT_THAT(
        MakeMappedRange(
            x,
            [](int x) { return x + 3; }
        ),
        ElementsAre(4, 5, 6, 7, 8)
    );
}

//TODO: replace with dedicated IterateKeys / IterateValues methods
TEST(TIterator, TMutableMappedRangeTest) {
    TMap<int, int> points = {{1, 2}, {3, 4}};

    EXPECT_THAT(
        MakeMappedRange(
            points.begin(), points.end(),
            [](TMap<int, int>::value_type& kv) -> int& { return kv.second; }
        ),
        ElementsAre(2, 4)
    );
}

TEST(TIterator, TOwningMappedMethodTest) {
    auto range = MakeMappedRange(
        TVector<std::pair<int, int>>{std::make_pair(1, 2), std::make_pair(3, 4)},
        [](auto& point) -> int& {
            return point.first;
        }
    );
    EXPECT_EQ(range[0], 1);
    range[0] += 1;
    EXPECT_EQ(range[0], 2);
    (*range.begin()) += 1;
    EXPECT_EQ(range[0], 3);
    for (int& y : range) {
        y += 7;
    }

    EXPECT_EQ(*range.begin(), 10);
    EXPECT_EQ(*(range.begin() + 1), 10);
}