aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/util/gencnt.cpp
blob: da7ad457418745673b0e62132b34d7457230325c (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "gencnt.h"
#include <cassert>

namespace vespalib {

GenCnt &
GenCnt::add(uint32_t n)
{
    uint32_t newVal = _val + n;
    if (newVal < _val) {
        // avoid wrap-around to 0
        newVal++;
    }
    _val = newVal;
    return *this;
}


bool
GenCnt::inRangeInclusive(GenCnt a, GenCnt b) const
{
    if (_val == 0) {
        return (a._val == 0);
    }
    if (b._val >= a._val) {
        //        a--------------|
        // |-------------b
        //        |------|
        return ((_val >= a._val) && (_val <= b._val));
    } else {
        //               a-------|
        // |------b
        // |------|      |-------|
        return ((_val >= a._val) || (_val <= b._val));
    }
}


uint32_t
GenCnt::distance(const GenCnt &other) const
{
    if (other._val == 0) {
        // special case
        assert(_val == 0);
        return 0;
    }
    if (_val <= other._val) {
        // normal case
        return (other._val - _val);
    }
    // wrapped case
    return (other._val - _val - 1);
}


GenCnt &
GenCnt::operator=(const GenCnt &src)
{
    _val = src.getAsInt();
    return *this;
}

} // namespace vespalib