aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/codecs/tls_cache.h
blob: 0184e4bb6c201b78f1e80c5fa090c4c93b3934e4 (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
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
100
#pragma once

#include <util/generic/buffer.h>
#include <util/generic/deque.h>
#include <util/generic/noncopyable.h>
#include <util/generic/strbuf.h>
#include <util/system/tls.h>
#include <util/thread/singleton.h>

namespace NCodecs {
    template <class TItem>
    struct TClear {
        void operator()(TItem& item) const {
            item.Clear();
        }
    };

    template <class TItem, class TCleaner = TClear<TItem>>
    class TTlsCache {
        using TSelf = TTlsCache<TItem, TCleaner>;

        struct TItemHolder: public TIntrusiveListItem<TItemHolder> {
            TItemHolder(TSelf& factory)
                : Factory(factory)
            {
            }

            void Release() {
                Factory.Release(*this);
            }

            TSelf& Factory;
            TItem Item;
        };

        class TItemGuard {
        public:
            explicit TItemGuard(TSelf& fact)
                : Holder(fact.Acquire())
            {
            }

            TItemGuard(TItemGuard&& other) noexcept {
                *this = std::move(other);
            }

            TItemGuard& operator=(TItemGuard&& other) noexcept {
                if (&other != this) {
                    std::swap(Holder, other.Holder);
                }
                return *this;
            }

            ~TItemGuard() {
                if (Holder) {
                    Holder->Release();
                }
            }

            TItem& Get() & {
                Y_ASSERT(Holder);
                return Holder->Item;
            }

            TItem& Get() && = delete;

        private:
            TItemHolder* Holder = nullptr;
        };

    public:
        TItemGuard Item() {
            return TItemGuard(*this);
        }

        static TSelf& TlsInstance() {
            return *FastTlsSingleton<TSelf>();
        }

    private:
        TItemHolder* Acquire() {
            if (Free.Empty()) {
                return new TItemHolder(*this);
            } else {
                return Free.PopBack();
            }
        }

        void Release(TItemHolder& item) {
            Cleaner(item.Item);
            Free.PushBack(&item);
        }

    private:
        TIntrusiveListWithAutoDelete<TItemHolder, TDelete> Free;
        TCleaner Cleaner;
    };

    using TBufferTlsCache = TTlsCache<TBuffer>;
}