Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
cuckoo-filter.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
77#ifndef ALEPH_CUCKOO_FILTER_H
78#define ALEPH_CUCKOO_FILTER_H
79
80#include <cassert>
81#include <cstddef>
82#include <cmath>
83#include <limits>
84#include <optional>
85#include <random>
86#include <algorithm>
87#include <utility>
88#include <hash-fct.H>
89#include <ah-errors.H>
90#include <ahUtils.H>
91#include <tpl_array.H>
92
93namespace Aleph {
107template <typename T, size_t FingerprintBits = 8, size_t EntriesPerBucket = 4> class Cuckoo_Filter
108{
109 static_assert(FingerprintBits > 0 and FingerprintBits <= 32, "Fingerprint bits must be between 1 and 32");
110 static_assert(EntriesPerBucket > 0, "Entries per bucket must be > 0");
111
112 using Fingerprint = uint32_t;
113
114 struct Bucket
115 {
116 Fingerprint slots[EntriesPerBucket];
117
119 {
120 std::fill(slots, slots + EntriesPerBucket, 0);
121 }
122
123 void clear()
124 {
125 std::fill(slots, slots + EntriesPerBucket, 0);
126 }
127
129 {
130 for (size_t i = 0; i < EntriesPerBucket; ++i)
131 if (slots[i] == 0)
132 {
133 slots[i] = fp;
134 return true;
135 }
136 return false;
137 }
138
139 bool contains(Fingerprint fp) const
140 {
141 for (size_t i = 0; i < EntriesPerBucket; ++i)
142 if (slots[i] == fp)
143 return true;
144 return false;
145 }
146
148 {
149 for (size_t i = 0; i < EntriesPerBucket; ++i)
150 if (slots[i] == fp)
151 {
152 slots[i] = 0;
153 return true;
154 }
155 return false;
156 }
157
158 void restore(Fingerprint fp, size_t idx)
159 {
160 slots[idx] = fp;
161 }
162
163 [[nodiscard]] size_t swap_random_slot(Fingerprint &fp, std::mt19937 &rng)
164 {
165 std::uniform_int_distribution<size_t> dist(0, EntriesPerBucket - 1);
166 const size_t idx = dist(rng);
167 std::swap(fp, slots[idx]);
168 return idx;
169 }
170 };
171
173 struct Victim
174 {
175 size_t index = 0;
177 };
178
180 size_t num_items = 0;
181 size_t num_buckets = 0;
182 size_t bucket_mask = 0;
183 mutable std::mt19937 rng_;
184
185 static constexpr size_t max_kicks = 500;
186 static constexpr size_t stash_size = 4;
187 static constexpr double kTargetLoad = 0.9;
189 size_t stash_count_ = 0;
190
191 // Mask to keep only the desired number of bits for fingerprint
192 static constexpr Fingerprint fp_mask = (FingerprintBits == 32) ? 0xFFFFFFFF : (1U << FingerprintBits) - 1;
193
194 [[nodiscard]] Fingerprint get_fingerprint(const T &item) const
195 {
196 auto fp = static_cast<Fingerprint>(dft_hash_fct(item, 0x12345678) & fp_mask);
197 if (fp == 0)
198 fp = 1; // 0 is reserved for empty slot
199 return fp;
200 }
201
202 [[nodiscard]] size_t index_hash(const T &item) const noexcept
203 {
204 return dft_hash_fct(item) & bucket_mask;
205 }
206
207 [[nodiscard]] size_t alt_index(size_t i, Fingerprint fp) const
208 {
209 // h2(x) = h1(x) XOR hash(fp)
210 // Both operands are in [0, bucket_mask], so the XOR result
211 // stays in the same range, preserving perfect reversibility.
212 return i ^ (murmur3hash(fp, 0x87654321) & bucket_mask);
213 }
214
215public:
227 explicit Cuckoo_Filter(size_t capacity,
228 std::optional<std::uint32_t> seed = std::nullopt)
229 : rng_(seed.has_value() ? std::mt19937(seed.value())
230 : std::mt19937(std::random_device{}()))
231 {
232 // The buckets as a double first: for a capacity next to the largest
233 // size_t they are more than a size_t counts, the conversion of such a
234 // double is undefined, and past the largest power of two that a
235 // size_t holds (2^63 where it has 64 bits), which a double holds
236 // exactly, they have no next power of two
237 constexpr double limit = static_cast<double>(std::numeric_limits<size_t>::max() / 2 + 1);
238 const double needed = std::ceil(capacity / (EntriesPerBucket * kTargetLoad));
239 ah_overflow_error_if(needed > limit)
240 << "Cuckoo_Filter: " << capacity << " items ask for more buckets than a size_t counts";
241 const auto needed_buckets = static_cast<size_t>(needed);
242 // Round up to a power of 2 so that bucket_mask works as a modulo
243 num_buckets = next_power_of_2(needed_buckets);
244 if (num_buckets == 0)
245 num_buckets = 1;
247 buckets.putn(num_buckets);
248 }
249
254 Cuckoo_Filter(const Cuckoo_Filter & other) = default;
255
271 {
272 buckets.putn(1);
273 swap(other);
274 }
275
281 Cuckoo_Filter & operator = (const Cuckoo_Filter & other) = default;
282
290 {
291 swap(other);
292 return *this;
293 }
294
298 void swap(Cuckoo_Filter & other) noexcept
299 {
300 buckets.swap(other.buckets);
301 std::swap(num_items, other.num_items);
302 std::swap(num_buckets, other.num_buckets);
303 std::swap(bucket_mask, other.bucket_mask);
304 std::swap(rng_, other.rng_);
305 std::swap(stash_, other.stash_);
306 std::swap(stash_count_, other.stash_count_);
307 }
308
313 [[nodiscard]] size_t size() const noexcept
314 {
315 return num_items;
316 }
317
322 [[nodiscard]] bool empty() const noexcept
323 {
324 return num_items == 0;
325 }
326
331 [[nodiscard]] bool is_empty() const noexcept
332 {
333 return empty();
334 }
335
340 [[nodiscard]] size_t capacity() const noexcept
341 {
342 return num_buckets * EntriesPerBucket + stash_size;
343 }
344
349 [[nodiscard]] double load_factor() const noexcept
350 {
351 return 1.0 * num_items / capacity();
352 }
353
361 bool insert(const T &item)
362 {
363 const Fingerprint fp = get_fingerprint(item);
364 size_t i1 = index_hash(item);
365 size_t i2 = alt_index(i1, fp);
366
367 if (buckets(i1).insert(fp))
368 {
369 ++num_items;
370 return true;
371 }
372
373 if (buckets(i2).insert(fp))
374 {
375 ++num_items;
376 return true;
377 }
378
379 // Both buckets full, start kicking
380 std::uniform_int_distribution<int> coin(0, 1);
381 size_t curr_idx = coin(rng_) ? i1 : i2;
382 Fingerprint curr_fp = fp;
383 struct Kick_Record
384 {
385 size_t bucket_idx = 0;
386 size_t slot_idx = 0;
387 Fingerprint original_fp = 0;
388 };
389 Kick_Record history[max_kicks];
390 size_t history_size = 0;
391
392 for (size_t kick = 0; kick < max_kicks; ++kick)
393 {
394 const size_t slot_idx = buckets(curr_idx).swap_random_slot(curr_fp, rng_);
395 history[history_size++] = {curr_idx, slot_idx, curr_fp};
396 curr_idx = alt_index(curr_idx, curr_fp);
397 if (buckets(curr_idx).insert(curr_fp))
398 {
399 ++num_items;
400 return true;
401 }
402 }
403
404 // Kick chain exhausted — save the displaced fingerprint in the stash
406 {
407 stash_[stash_count_++] = {curr_idx, curr_fp};
408 ++num_items;
409 return true;
410 }
411
412 while (history_size > 0)
413 {
414 const Kick_Record & rec = history[--history_size];
415 buckets(rec.bucket_idx).restore(rec.original_fp, rec.slot_idx);
416 }
417
418 return false; // Filter and stash both full
419 }
420
426 bool append(const T &item)
427 {
428 return insert(item);
429 }
430
438 [[nodiscard]] bool contains(const T &item) const
439 {
440 const Fingerprint fp = get_fingerprint(item);
441 const size_t i1 = index_hash(item);
442 const size_t i2 = alt_index(i1, fp);
443
444 if (buckets(i1).contains(fp) or buckets(i2).contains(fp))
445 return true;
446
447 for (size_t i = 0; i < stash_count_; ++i)
448 if (stash_[i].fp == fp and (stash_[i].index == i1 or stash_[i].index == i2))
449 return true;
450
451 return false;
452 }
453
461 bool remove(const T &item)
462 {
463 const Fingerprint fp = get_fingerprint(item);
464 const size_t i1 = index_hash(item);
465 const size_t i2 = alt_index(i1, fp);
466
467 if (buckets(i1).remove(fp) or buckets(i2).remove(fp))
468 {
469 --num_items;
470 return true;
471 }
472
473 for (size_t i = 0; i < stash_count_; ++i)
474 if (stash_[i].fp == fp and (stash_[i].index == i1 or stash_[i].index == i2))
475 {
476 stash_[i] = stash_[--stash_count_];
477 --num_items;
478 return true;
479 }
480
481 return false;
482 }
483
488 void clear()
489 {
490 for (size_t i = 0; i < num_buckets; ++i)
491 buckets(i).clear();
492 num_items = 0;
493 stash_count_ = 0;
494 }
495};
496} // namespace Aleph
497
498#endif // ALEPH_CUCKOO_FILTER_H
Exception handling system with formatted messages for Aleph-w.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
General utility functions and helpers.
size_t size_t int32_t value
Definition ca-c-api.h:116
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
Industrial-grade Cuckoo Filter implementation.
bool contains(const T &item) const
Test membership.
static constexpr Fingerprint fp_mask
Cuckoo_Filter(size_t capacity, std::optional< std::uint32_t > seed=std::nullopt)
Construct a Cuckoo Filter with a given capacity.
double load_factor() const noexcept
Return the load factor of the filter (relative to capacity()).
void clear()
Clear the filter.
Cuckoo_Filter(Cuckoo_Filter &&other)
Take the items of another filter, which is left as an empty filter of one bucket.
bool empty() const noexcept
Return whether the filter contains no items.
bool is_empty() const noexcept
Synonym for empty() in traditional Aleph style.
Fingerprint get_fingerprint(const T &item) const
bool remove(const T &item)
Remove an item from the filter.
size_t size() const noexcept
Return the number of items currently in the filter.
Cuckoo_Filter(const Cuckoo_Filter &other)=default
Copy the buckets, the stash and the generator of another filter.
size_t alt_index(size_t i, Fingerprint fp) const
Aleph::Array< Bucket > buckets
Cuckoo_Filter & operator=(const Cuckoo_Filter &other)=default
Copy the buckets, the stash and the generator of another filter.
static constexpr size_t stash_size
size_t index_hash(const T &item) const noexcept
static constexpr size_t max_kicks
static constexpr double kTargetLoad
Victim stash_[stash_size]
size_t capacity() const noexcept
Return the total number of fingerprint slots (including stash).
bool insert(const T &item)
Insert an item into the filter.
void swap(Cuckoo_Filter &other) noexcept
Exchange in O(1) the state of this filter and another.
bool append(const T &item)
Alias for insert().
static mt19937 rng
Standard hash functions for Aleph types.
Main namespace for Aleph-w library functions.
size_t next_power_of_2(size_t x)
Return the smallest power of 2 that is not less than x.
Definition ahUtils.H:243
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
size_t dft_hash_fct(const Key &key) noexcept
Primary default hash: best speed/quality trade-off.
Definition hash-fct.H:1030
size_t murmur3hash(const Key &key, std::uint32_t seed)
Definition hash-fct.H:361
STL namespace.
bool remove(Fingerprint fp)
size_t swap_random_slot(Fingerprint &fp, std::mt19937 &rng)
Fingerprint slots[EntriesPerBucket]
bool insert(Fingerprint fp)
void restore(Fingerprint fp, size_t idx)
bool contains(Fingerprint fp) const
Victim entry: a fingerprint displaced during a failed kick chain.
ValueArg< size_t > seed
Definition testHash.C:53
Dynamic array container with automatic resizing.