aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/misc/granup.h
blob: d0bc62127688e2c691c29b7f6923733b222d506e (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
#pragma once

#include <util/datetime/base.h>
#include <util/system/guard.h>
#include <util/system/mutex.h>
#include <util/system/spinlock.h>

namespace NBus {
    template <typename TItem, typename TLocker = TSpinLock>
    class TGranUp {
    public:
        TGranUp(TDuration gran)
            : Gran(gran)
            , Next(TInstant::MicroSeconds(0)) 
        {
        }

        template <typename TFunctor>
        void Update(TFunctor functor, TInstant now, bool force = false) {
            if (force || now > Next)
                Set(functor(), now);
        }

        void Update(const TItem& item, TInstant now, bool force = false) {
            if (force || now > Next)
                Set(item, now);
        }

        TItem Get() const noexcept {
            TGuard<TLocker> guard(Lock);

            return Item;
        }

    protected:
        void Set(const TItem& item, TInstant now) {
            TGuard<TLocker> guard(Lock);

            Item = item;

            Next = now + Gran;
        }

    private:
        const TDuration Gran;
        TLocker Lock;
        TItem Item;
        TInstant Next;
    };
}