summaryrefslogtreecommitdiffstats
path: root/library/cpp/ipreg/merge.cpp
blob: d31e9dce5d30d0910e5971e1ffef747a94af294d (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
#include "merge.h"

namespace NIPREG {

void MergeIPREGS(TReader &a, TReader& b, std::function<void(const TAddress& first, const TAddress& last, const TString *a, const TString *b)>&& proc) {
    bool hasA = a.Next();
    bool hasB = b.Next();

    TAddress top = TAddress::Lowest();
    TAddress bottom;

    do {
        // tweak ranges we've passed
        if (hasA && top > a.Get().Last)
            hasA = a.Next();
        if (hasB && top > b.Get().Last)
            hasB = b.Next();

        if (!hasA && !hasB) {
            // both rangesets have ended
            bottom = TAddress::Highest();
            proc(top, bottom, nullptr, nullptr);
            break;
        }

        const bool inA = hasA && a.Get().First <= top;
        const bool inB = hasB && b.Get().First <= top;

        if (!hasA) {
            // rangeset a has ended
            if (inB) {
                bottom = b.Get().Last;
                proc(top, bottom, nullptr, &b.Get().Data);
            } else {
                bottom = b.Get().First.Prev();
                proc(top, bottom, nullptr, nullptr);
            }
        } else if (!hasB) {
            // rangeset b has ended
            if (inA) {
                bottom = a.Get().Last;
                proc(top, bottom, &a.Get().Data, nullptr);
            } else {
                bottom = a.Get().First.Prev();
                proc(top, bottom, nullptr, nullptr);
            }
        } else if (inA && inB) {
            // inside both ranges
            bottom = Min(a.Get().Last, b.Get().Last);
            proc(top, bottom, &a.Get().Data, &b.Get().Data);
        } else if (inA) {
            // only in range a
            bottom = Min(a.Get().Last, b.Get().First.Prev());
            proc(top, bottom, &a.Get().Data, nullptr);
        } else if (inB) {
            // only in range b
            bottom = Min(b.Get().Last, a.Get().First.Prev());
            proc(top, bottom, nullptr, &b.Get().Data);
        } else {
            // outside both ranges
            bottom = Min(a.Get().First.Prev(), a.Get().First.Prev());
            proc(top, bottom, nullptr, nullptr);
        }

        top = bottom.Next();
    } while (bottom != TAddress::Highest());
}

}