aboutsummaryrefslogtreecommitdiff
path: root/src/libutil/notifying-counter.hh
blob: dc58aac91789ffbfd4aa6c3f8b8bd8909495d60f (plain)
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
#pragma once
/// @file

#include <cassert>
#include <functional>
#include <memory>

namespace nix {

template<std::integral T>
class NotifyingCounter
{
private:
    T counter;
    std::function<void()> notify;

public:
    class Bump
    {
        friend class NotifyingCounter;

        struct SubOnFree
        {
            T delta;

            void operator()(NotifyingCounter * c) const
            {
                c->add(-delta);
            }
        };

        // lightly misuse unique_ptr to get RAII types with destructor callbacks
        std::unique_ptr<NotifyingCounter<T>, SubOnFree> at;

        Bump(NotifyingCounter<T> & at, T delta) : at(&at, {delta}) {}

    public:
        Bump() = default;
        Bump(decltype(nullptr)) {}

        T delta() const
        {
            return at ? at.get_deleter().delta : 0;
        }

        void reset()
        {
            at.reset();
        }
    };

    explicit NotifyingCounter(std::function<void()> notify, T initial = 0)
        : counter(initial)
        , notify(std::move(notify))
    {
        assert(this->notify);
    }

    // bumps hold pointers to this, so we should neither copy nor move.
    NotifyingCounter(const NotifyingCounter &) = delete;
    NotifyingCounter & operator=(const NotifyingCounter &) = delete;
    NotifyingCounter(NotifyingCounter &&) = delete;
    NotifyingCounter & operator=(NotifyingCounter &&) = delete;

    T get() const
    {
        return counter;
    }

    operator T() const
    {
        return counter;
    }

    void add(T delta)
    {
        counter += delta;
        notify();
    }

    NotifyingCounter & operator+=(T delta)
    {
        add(delta);
        return *this;
    }

    NotifyingCounter & operator++(int)
    {
        return *this += 1;
    }

    Bump addTemporarily(T delta)
    {
        add(delta);
        return Bump{*this, delta};
    }
};

}