aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/reverse_geocoder/library/unaligned_iter.h
blob: 827a3e2fd2e4c1ebb4988c931ae7af8f9944a9ee (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
#pragma once

#include <util/system/unaligned_mem.h>
#include <iterator>

namespace NReverseGeocoder {
    /**
     * Random-access iterator over a read-only memory range
     * of trivially copyable items that may be not aligned properly.
     *
     * When dereferencing, a copy of item is returned, not a reference.
     * Be sure that sizeof(T) is small enough.
     *
     * Iterator is useful for LowerBound/UpperBound STL algorithms.
     */
    template <class T>
    class TUnalignedIter: public std::iterator<std::random_access_iterator_tag, T> {
    public:
        using TSelf = TUnalignedIter<T>;

        explicit TUnalignedIter(const T* ptr)
            : Ptr(ptr)
        {
        }

        T operator*() const {
            return ReadUnaligned<T>(Ptr);
        }

        bool operator==(TSelf other) const {
            return Ptr == other.Ptr;
        }

        bool operator<(TSelf other) const {
            return Ptr < other.Ptr;
        }

        TSelf operator+(ptrdiff_t delta) const {
            return TSelf{Ptr + delta};
        }

        ptrdiff_t operator-(TSelf other) const {
            return Ptr - other.Ptr;
        }

        TSelf& operator+=(ptrdiff_t delta) {
            Ptr += delta;
            return *this;
        }

        TSelf& operator++() {
            ++Ptr;
            return *this;
        }

    private:
        const T* Ptr;
    };

    template <class T>
    TUnalignedIter<T> UnalignedIter(const T* ptr) {
        return TUnalignedIter<T>(ptr);
    }
}