aboutsummaryrefslogtreecommitdiffstats
path: root/util/generic/iterator_range.h
blob: 9f4d02da2953999eca10802611b4c6e880cd921f (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#pragma once

#include <util/system/yassert.h>

#include <iterator>
#include <utility>

template <typename TBegin, typename TEnd = TBegin>
struct TIteratorRange {
    using TElement = std::remove_reference_t<decltype(*std::declval<TBegin>())>;

    TIteratorRange(TBegin begin, TEnd end)
        : Begin_(begin)
        , End_(end)
    {
    }

    TIteratorRange()
        : TIteratorRange(TBegin{}, TEnd{})
    {
    }

    TBegin begin() const {
        return Begin_;
    }

    TEnd end() const {
        return End_;
    }

    bool empty() const {
        // because range based for requires exactly '!='
        return !(Begin_ != End_);
    }

private:
    TBegin Begin_;
    TEnd End_;
};

template <class TIterator>
class TIteratorRange<TIterator, TIterator> {
public:
    using iterator = TIterator;
    using const_iterator = TIterator;
    using value_type = typename std::iterator_traits<iterator>::value_type;
    using reference = typename std::iterator_traits<iterator>::reference;
    using const_reference = typename std::iterator_traits<const_iterator>::reference;
    using difference_type = typename std::iterator_traits<iterator>::difference_type;
    using size_type = std::size_t;

    TIteratorRange()
        : Begin_()
        , End_()
    {
    }

    TIteratorRange(TIterator begin, TIterator end)
        : Begin_(begin)
        , End_(end)
    {
    }

    TIterator begin() const {
        return Begin_;
    }

    TIterator end() const {
        return End_;
    }

    Y_PURE_FUNCTION bool empty() const {
        return Begin_ == End_;
    }

    size_type size() const {
        return End_ - Begin_;
    }

    reference operator[](size_t at) const {
        Y_ASSERT(at < size());

        return *(Begin_ + at);
    }

private:
    TIterator Begin_;
    TIterator End_;
};

template <class TIterator>
TIteratorRange<TIterator> MakeIteratorRange(TIterator begin, TIterator end) {
    return TIteratorRange<TIterator>(begin, end);
}

template <class TIterator>
TIteratorRange<TIterator> MakeIteratorRange(const std::pair<TIterator, TIterator>& range) {
    return TIteratorRange<TIterator>(range.first, range.second);
}

template <class TBegin, class TEnd>
TIteratorRange<TBegin, TEnd> MakeIteratorRange(TBegin begin, TEnd end) {
    return {begin, end};
}