aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Common/HashTable/LRUHashMap.h
blob: 68b585cf553c276b10c9b60bd18539782751d687 (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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#pragma once

#include <base/types.h>

#include <boost/intrusive/trivial_value_traits.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/noncopyable.hpp>

#include <Core/Defines.h>
#include <Common/Exception.h>
#include <Common/HashTable/HashMap.h>
#include <Common/PODArray.h>


template <typename TKey, typename TMapped, typename Hash, bool save_hash_in_cell>
struct LRUHashMapCell :
    public std::conditional_t<save_hash_in_cell,
        HashMapCellWithSavedHash<TKey, TMapped, Hash, HashTableNoState>,
        HashMapCell<TKey, TMapped, Hash, HashTableNoState>>
{
public:
    using Key = TKey;

    using Base = std::conditional_t<save_hash_in_cell,
        HashMapCellWithSavedHash<TKey, TMapped, Hash, HashTableNoState>,
        HashMapCell<TKey, TMapped, Hash, HashTableNoState>>;

    using Mapped = typename Base::Mapped;
    using State = typename Base::State;

    using mapped_type = Mapped;
    using key_type = Key;

    using Base::Base;

    static bool constexpr need_to_notify_cell_during_move = true;

    static void move(LRUHashMapCell * __restrict old_location, LRUHashMapCell * __restrict new_location)
    {
        /** We update new location prev and next pointers because during hash table resize
         *  they can be updated during move of another cell.
         */

        new_location->prev = old_location->prev;
        new_location->next = old_location->next;

        LRUHashMapCell * prev = new_location->prev;
        LRUHashMapCell * next = new_location->next;

        /// Updated previous next and next previous nodes of list to point to new location

        if (prev)
            prev->next = new_location;

        if (next)
            next->prev = new_location;
    }

private:
    template<typename, typename, typename, bool>
    friend class LRUHashMapCellNodeTraits;

    LRUHashMapCell * next = nullptr;
    LRUHashMapCell * prev = nullptr;
};

template<typename Key, typename Value, typename Hash, bool save_hash_in_cell>
struct LRUHashMapCellNodeTraits
{
    using node = LRUHashMapCell<Key, Value, Hash, save_hash_in_cell>;
    using node_ptr = LRUHashMapCell<Key, Value, Hash, save_hash_in_cell> *;
    using const_node_ptr = const LRUHashMapCell<Key, Value, Hash, save_hash_in_cell> *;

    static node * get_next(const node * ptr) { return ptr->next; } /// NOLINT
    static void set_next(node * __restrict ptr, node * __restrict next) { ptr->next = next; } /// NOLINT
    static node * get_previous(const node * ptr) { return ptr->prev; } /// NOLINT
    static void set_previous(node * __restrict ptr, node * __restrict prev) { ptr->prev = prev; } /// NOLINT
};

template <typename TKey, typename TValue, typename Disposer, typename Hash, bool save_hash_in_cells>
class LRUHashMapImpl : private HashMapTable<
                           TKey,
                           LRUHashMapCell<TKey, TValue, Hash, save_hash_in_cells>,
                           Hash,
                           HashTableGrowerWithPrecalculation<>,
                           HashTableAllocator>
{
    using Base = HashMapTable<
        TKey,
        LRUHashMapCell<TKey, TValue, Hash, save_hash_in_cells>,
        Hash,
        HashTableGrowerWithPrecalculation<>,
        HashTableAllocator>;

public:
    using Key = TKey;
    using Value = TValue;

    using Cell = LRUHashMapCell<Key, Value, Hash, save_hash_in_cells>;

    using LRUHashMapCellIntrusiveValueTraits =
        boost::intrusive::trivial_value_traits<
            LRUHashMapCellNodeTraits<Key, Value, Hash, save_hash_in_cells>,
            boost::intrusive::link_mode_type::normal_link>;

    using LRUList = boost::intrusive::list<
        Cell,
        boost::intrusive::value_traits<LRUHashMapCellIntrusiveValueTraits>,
        boost::intrusive::constant_time_size<false>>;

    using LookupResult = typename Base::LookupResult;
    using ConstLookupResult = typename Base::ConstLookupResult;

    using iterator = typename LRUList::iterator;
    using const_iterator = typename LRUList::const_iterator;
    using reverse_iterator = typename LRUList::reverse_iterator;
    using const_reverse_iterator = typename LRUList::const_reverse_iterator;

    explicit LRUHashMapImpl(size_t max_size_, bool preallocate_max_size_in_hash_map = false, Disposer disposer_ = Disposer())
        : Base(preallocate_max_size_in_hash_map ? max_size_ : 32)
        , max_size(max_size_)
        , disposer(std::move(disposer_))
    {
        assert(max_size > 0);
    }

    ~LRUHashMapImpl()
    {
        clear();
    }

    std::pair<Cell *, bool> ALWAYS_INLINE insert(const Key & key, const Value & value)
    {
        return emplace(key, value);
    }

    std::pair<Cell *, bool> ALWAYS_INLINE insert(const Key & key, Value && value)
    {
        return emplace(key, std::move(value));
    }

    template<typename ...Args>
    std::pair<Cell *, bool> emplace(const Key & key, Args&&... args)
    {
        size_t hash_value = Base::hash(key);

        Cell * it = Base::find(key, hash_value);

        if (it)
        {
            /// Cell contains element return it and put to the end of lru list
            lru_list.splice(lru_list.end(), lru_list, lru_list.iterator_to(*it));
            return std::make_pair(it, false);
        }

        if (size() == max_size)
        {
            /// Erase least recently used element from front of the list
            Cell copy_node = lru_list.front();

            const Key & element_to_remove_key = copy_node.getKey();

            lru_list.pop_front();

            [[maybe_unused]] bool erased = Base::erase(element_to_remove_key);
            assert(erased);

            disposer(element_to_remove_key, copy_node.getMapped());
        }

        [[maybe_unused]] bool inserted;

        /// Insert value first try to insert in zero storage if not then insert in buffer
        if (!Base::emplaceIfZero(key, it, inserted, hash_value))
            Base::emplaceNonZero(key, it, inserted, hash_value);

        assert(inserted);

        new (&it->getMapped()) Value(std::forward<Args>(args)...);

        /// Put cell to the end of lru list
        lru_list.insert(lru_list.end(), *it);

        return std::make_pair(it, true);
    }

    LookupResult ALWAYS_INLINE find(const Key & key)
    {
        auto it = Base::find(key);

        if (!it)
            return nullptr;

        /// Put cell to the end of lru list
        lru_list.splice(lru_list.end(), lru_list, lru_list.iterator_to(*it));

        return it;
    }

    ConstLookupResult ALWAYS_INLINE find(const Key & key) const
    {
        return const_cast<std::decay_t<decltype(*this)> *>(this)->find(key);
    }

    Value & ALWAYS_INLINE get(const Key & key)
    {
        auto it = find(key);
        assert(it);

        return it->getMapped();
    }

    const Value & ALWAYS_INLINE get(const Key & key) const
    {
        return const_cast<std::decay_t<decltype(*this)> *>(this)->get(key);
    }

    bool ALWAYS_INLINE contains(const Key & key) const
    {
        return find(key) != nullptr;
    }

    Value & ALWAYS_INLINE operator[](const Key & key)
    {
        auto [it, _] = emplace(key);
        return it->getMapped();
    }

    bool ALWAYS_INLINE erase(const Key & key)
    {
        auto key_hash = Base::hash(key);
        auto it = Base::find(key, key_hash);

        if (!it)
            return false;

        lru_list.erase(lru_list.iterator_to(*it));

        Cell copy_node = *it;
        Base::erase(key, key_hash);
        disposer(copy_node.getKey(), copy_node.getMapped());

        return true;
    }

    void ALWAYS_INLINE clear()
    {
        for (auto & cell : lru_list)
            disposer(cell.getKey(), cell.getMapped());

        lru_list.clear();
        Base::clear();
    }

    using Base::size;

    size_t getMaxSize() const { return max_size; }

    size_t getSizeInBytes() const { return Base::getBufferSizeInBytes(); }

    using Base::hash;

    iterator begin() { return lru_list.begin(); }
    const_iterator begin() const { return lru_list.cbegin(); }
    iterator end() { return lru_list.end(); }
    const_iterator end() const { return lru_list.cend(); }

    reverse_iterator rbegin() { return lru_list.rbegin(); }
    const_reverse_iterator rbegin() const { return lru_list.crbegin(); }
    reverse_iterator rend() { return lru_list.rend(); }
    const_reverse_iterator rend() const { return lru_list.crend(); }

private:
    size_t max_size;
    LRUList lru_list;
    Disposer disposer;
};

template <typename Key, typename Mapped>
struct DefaultLRUHashMapCellDisposer
{
    void operator()(const Key &, const Mapped &) const {}
};

template <typename Key, typename Value, typename Disposer = DefaultLRUHashMapCellDisposer<Key, Value>, typename Hash = DefaultHash<Key>>
using LRUHashMap = LRUHashMapImpl<Key, Value, Disposer, Hash, false>;

template <typename Key, typename Value, typename Disposer = DefaultLRUHashMapCellDisposer<Key, Value>, typename Hash = DefaultHash<Key>>
using LRUHashMapWithSavedHash = LRUHashMapImpl<Key, Value, Disposer, Hash, true>;