Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
compact-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
72#ifndef ALEPH_COMPACT_CUCKOO_FILTER_H
73#define ALEPH_COMPACT_CUCKOO_FILTER_H
74
75#include <cassert>
76#include <cstddef>
77#include <cmath>
78#include <limits>
79#include <optional>
80#include <random>
81#include <algorithm>
82#include <utility>
83#include <hash-fct.H>
84#include <ah-errors.H>
85#include <ahUtils.H>
86#include <tpl_array.H>
87#include <bitArray.H>
88
89namespace Aleph {
96template <typename T, size_t FingerprintBits = 8, size_t EntriesPerBucket = 4> class Compact_Cuckoo_Filter
97{
98 static_assert(FingerprintBits > 0 and FingerprintBits <= 32, "Fingerprint bits must be between 1 and 32");
99 static_assert(EntriesPerBucket > 0, "Entries per bucket must be > 0");
100
101 using Fingerprint = uint32_t;
102
103 struct Bucket
104 {
106
107 Bucket() : bits(EntriesPerBucket * FingerprintBits)
108 {
109 }
110
111 void clear()
112 {
113 for (size_t i = 0; i < EntriesPerBucket * FingerprintBits; ++i)
114 bits.write_bit(i, 0);
115 }
116
117 [[nodiscard]] Fingerprint get_slot(const size_t idx) const
118 {
119 const size_t bit_offset = idx * FingerprintBits;
120 Fingerprint fp = 0;
121 for (size_t i = 0; i < FingerprintBits; ++i)
122 if (bits.read_bit(bit_offset + i))
123 fp |= (1U << i);
124 return fp;
125 }
126
127 void set_slot(size_t idx, Fingerprint fp)
128 {
129 const size_t bit_offset = idx * FingerprintBits;
130 for (size_t i = 0; i < FingerprintBits; ++i)
131 {
132 if (fp & (1U << i))
133 bits.write_bit(bit_offset + i, 1);
134 else
135 bits.write_bit(bit_offset + i, 0);
136 }
137 }
138
140 {
141 for (size_t i = 0; i < EntriesPerBucket; ++i)
142 if (get_slot(i) == 0)
143 {
144 set_slot(i, fp);
145 return true;
146 }
147 return false;
148 }
149
150 [[nodiscard]] bool contains(const Fingerprint fp) const
151 {
152 for (size_t i = 0; i < EntriesPerBucket; ++i)
153 if (get_slot(i) == fp)
154 return true;
155 return false;
156 }
157
159 {
160 for (size_t i = 0; i < EntriesPerBucket; ++i)
161 if (get_slot(i) == fp)
162 {
163 set_slot(i, 0);
164 return true;
165 }
166 return false;
167 }
168
169 void restore(Fingerprint fp, size_t idx)
170 {
171 set_slot(idx, fp);
172 }
173
174 [[nodiscard]] size_t swap_random_slot(Fingerprint &fp, std::mt19937 &rng)
175 {
176 std::uniform_int_distribution<size_t> dist(0, EntriesPerBucket - 1);
177 const size_t idx = dist(rng);
178 const Fingerprint old_fp = get_slot(idx);
179 set_slot(idx, fp);
180 fp = old_fp;
181 return idx;
182 }
183 };
184
186 struct Victim
187 {
188 size_t index = 0;
190 };
191
193 size_t num_items = 0;
194 size_t num_buckets = 0;
195 size_t bucket_mask = 0;
196 mutable std::mt19937 rng_;
197
198 static constexpr size_t max_kicks = 500;
199 static constexpr size_t stash_size = 4;
200 static constexpr double kTargetLoad = 0.9;
202 size_t stash_count_ = 0;
203
204 // Mask to keep only the desired number of bits for fingerprint
205 static constexpr Fingerprint fp_mask = (FingerprintBits == 32) ? 0xFFFFFFFF : (1U << FingerprintBits) - 1;
206
207 [[nodiscard]] Fingerprint get_fingerprint(const T &item) const
208 {
209 auto fp = static_cast<Fingerprint>(dft_hash_fct(item, 0x12345678) & fp_mask);
210 if (fp == 0)
211 fp = 1; // 0 is reserved for empty slot
212 return fp;
213 }
214
215 [[nodiscard]] size_t index_hash(const T &item) const noexcept
216 {
217 return dft_hash_fct(item) & bucket_mask;
218 }
219
220 [[nodiscard]] size_t alt_index(const size_t i, Fingerprint fp) const
221 {
222 // h2(x) = h1(x) XOR hash(fp)
223 // Both operands are in [0, bucket_mask], so the XOR result
224 // stays in the same range, preserving perfect reversibility.
225 return i ^ (murmur3hash(fp, 0x87654321) & bucket_mask);
226 }
227
228public:
240 explicit Compact_Cuckoo_Filter(size_t capacity, const std::optional<std::uint32_t> seed = std::nullopt)
241 : rng_(seed.has_value() ? std::mt19937(seed.value())
242 : std::mt19937(std::random_device{}()))
243 {
244 // The buckets as a double first: for a capacity next to the largest
245 // size_t they are more than a size_t counts, the conversion of such a
246 // double is undefined, and past the largest power of two that a
247 // size_t holds (2^63 where it has 64 bits), which a double holds
248 // exactly, they have no next power of two
249 constexpr double limit = static_cast<double>(std::numeric_limits<size_t>::max() / 2 + 1);
250 const double needed = std::ceil(capacity / (EntriesPerBucket * kTargetLoad));
251 ah_overflow_error_if(needed > limit)
252 << "Compact_Cuckoo_Filter: " << capacity << " items ask for more buckets than a size_t counts";
253 const auto needed_buckets = static_cast<size_t>(needed);
254 // Round up to a power of 2 so that bucket_mask works as a modulo
255 num_buckets = next_power_of_2(needed_buckets);
256 if (num_buckets == 0)
257 num_buckets = 1;
259 buckets.putn(num_buckets);
260 }
261
267
280 : buckets(std::move(other.buckets)), num_items(std::exchange(other.num_items, 0)),
281 num_buckets(other.num_buckets), bucket_mask(other.bucket_mask), rng_(other.rng_),
282 stash_count_(std::exchange(other.stash_count_, 0))
283 {
284 std::copy(other.stash_, other.stash_ + stash_size, stash_);
285 }
286
293
301 {
302 swap(other);
303 return *this;
304 }
305
309 void swap(Compact_Cuckoo_Filter & other) noexcept
310 {
311 buckets.swap(other.buckets);
312 std::swap(num_items, other.num_items);
313 std::swap(num_buckets, other.num_buckets);
314 std::swap(bucket_mask, other.bucket_mask);
315 std::swap(rng_, other.rng_);
316 std::swap(stash_, other.stash_);
317 std::swap(stash_count_, other.stash_count_);
318 }
319
324 [[nodiscard]] size_t size() const noexcept
325 {
326 return num_items;
327 }
328
333 [[nodiscard]] bool empty() const noexcept
334 {
335 return num_items == 0;
336 }
337
342 [[nodiscard]] bool is_empty() const noexcept
343 {
344 return empty();
345 }
346
351 [[nodiscard]] size_t capacity() const noexcept
352 {
353 return num_buckets * EntriesPerBucket + stash_size;
354 }
355
360 [[nodiscard]] double load_factor() const noexcept
361 {
362 return 1.0 * num_items / capacity();
363 }
364
370 [[nodiscard]] size_t memory_usage() const noexcept
371 {
372 // Each bucket uses FingerprintBits * EntriesPerBucket bits
373 const size_t bits_per_bucket = FingerprintBits * EntriesPerBucket;
374 const size_t bytes_per_bucket = (bits_per_bucket + 7) / 8;
375 return buckets.size() * bytes_per_bucket;
376 }
377
387 bool insert(const T &item)
388 {
389 if (buckets.is_empty()) // moved from
390 buckets.putn(num_buckets);
391
392 const Fingerprint fp = get_fingerprint(item);
393 size_t i1 = index_hash(item);
394 size_t i2 = alt_index(i1, fp);
395
396 if (buckets(i1).insert(fp))
397 {
398 ++num_items;
399 return true;
400 }
401
402 if (buckets(i2).insert(fp))
403 {
404 ++num_items;
405 return true;
406 }
407
408 // Both buckets full, start kicking
409 std::uniform_int_distribution<int> coin(0, 1);
410 size_t curr_idx = coin(rng_) ? i1 : i2;
411 Fingerprint curr_fp = fp;
412 struct Kick_Record
413 {
414 size_t bucket_idx = 0;
415 size_t slot_idx = 0;
416 Fingerprint original_fp = 0;
417 };
418 Kick_Record history[max_kicks];
419 size_t history_size = 0;
420
421 for (size_t kick = 0; kick < max_kicks; ++kick)
422 {
423 const size_t slot_idx = buckets(curr_idx).swap_random_slot(curr_fp, rng_);
424 history[history_size++] = {curr_idx, slot_idx, curr_fp};
425 curr_idx = alt_index(curr_idx, curr_fp);
426 if (buckets(curr_idx).insert(curr_fp))
427 {
428 ++num_items;
429 return true;
430 }
431 }
432
433 // Kick chain exhausted — save the displaced fingerprint in the stash
435 {
436 stash_[stash_count_++] = {curr_idx, curr_fp};
437 ++num_items;
438 return true;
439 }
440
441 while (history_size > 0)
442 {
443 const Kick_Record & rec = history[--history_size];
444 buckets(rec.bucket_idx).restore(rec.original_fp, rec.slot_idx);
445 }
446
447 return false; // Filter and stash both full
448 }
449
455 bool append(const T &item)
456 {
457 return insert(item);
458 }
459
467 [[nodiscard]] bool contains(const T &item) const
468 {
469 if (num_items == 0) // also a moved-from filter, which has no buckets
470 return false;
471
472 const Fingerprint fp = get_fingerprint(item);
473 const size_t i1 = index_hash(item);
474 const size_t i2 = alt_index(i1, fp);
475
476 if (buckets(i1).contains(fp) or buckets(i2).contains(fp))
477 return true;
478
479 for (size_t i = 0; i < stash_count_; ++i)
480 if (stash_[i].fp == fp and (stash_[i].index == i1 or stash_[i].index == i2))
481 return true;
482
483 return false;
484 }
485
493 bool remove(const T &item)
494 {
495 if (num_items == 0) // also a moved-from filter, which has no buckets
496 return false;
497
498 const Fingerprint fp = get_fingerprint(item);
499 const size_t i1 = index_hash(item);
500 const size_t i2 = alt_index(i1, fp);
501
502 if (buckets(i1).remove(fp) or buckets(i2).remove(fp))
503 {
504 --num_items;
505 return true;
506 }
507
508 // Check the stash
509 for (size_t i = 0; i < stash_count_; ++i)
510 if (stash_[i].fp == fp and (stash_[i].index == i1 or stash_[i].index == i2))
511 {
512 stash_[i] = stash_[--stash_count_]; // swap with last
513 --num_items;
514 return true;
515 }
516
517 return false;
518 }
519
524 void clear()
525 {
526 for (size_t i = 0; i < buckets.size(); ++i)
527 buckets(i).clear();
528 num_items = 0;
529 stash_count_ = 0;
530 }
531};
532} // namespace Aleph
533
534#endif // ALEPH_COMPACT_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.
Space-efficient bit array implementation.
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
Contiguous array of bits.
Definition bitArray.H:201
int read_bit(const size_t i) const
Read bit i.
Definition bitArray.H:409
void write_bit(const size_t i, const unsigned int value)
Write bit i with the value.
Definition bitArray.H:424
Memory-optimized Cuckoo Filter with bit-packed fingerprints.
bool append(const T &item)
Alias for insert().
bool contains(const T &item) const
Test membership.
static constexpr double kTargetLoad
bool is_empty() const noexcept
Synonym for empty() in traditional Aleph style.
size_t size() const noexcept
Return the number of items currently in the filter.
Compact_Cuckoo_Filter(Compact_Cuckoo_Filter &&other) noexcept
Take the items of another filter, which is left as an empty filter of the same capacity,...
bool remove(const T &item)
Remove an item from the filter.
bool insert(const T &item)
Insert an item into the filter.
double load_factor() const noexcept
Return the load factor of the filter (relative to capacity()).
Compact_Cuckoo_Filter(size_t capacity, const std::optional< std::uint32_t > seed=std::nullopt)
Construct a Compact Cuckoo Filter with a given capacity.
static constexpr size_t stash_size
size_t alt_index(const size_t i, Fingerprint fp) const
static constexpr size_t max_kicks
size_t memory_usage() const noexcept
Return approximate memory usage in bytes.
static constexpr Fingerprint fp_mask
bool empty() const noexcept
Return whether the filter contains no items.
Compact_Cuckoo_Filter & operator=(const Compact_Cuckoo_Filter &other)=default
Copy the buckets, the stash and the generator of another filter.
Compact_Cuckoo_Filter(const Compact_Cuckoo_Filter &other)=default
Copy the buckets, the stash and the generator of another filter.
size_t capacity() const noexcept
Return the total number of fingerprint slots (including stash).
Fingerprint get_fingerprint(const T &item) const
void swap(Compact_Cuckoo_Filter &other) noexcept
Exchange in O(1) the state of this filter and another.
size_t index_hash(const T &item) const noexcept
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.
Fingerprint get_slot(const size_t idx) const
size_t swap_random_slot(Fingerprint &fp, std::mt19937 &rng)
void restore(Fingerprint fp, size_t idx)
bool contains(const Fingerprint fp) const
void set_slot(size_t idx, Fingerprint fp)
Victim entry: a fingerprint that was displaced during a failed insert.
ValueArg< size_t > seed
Definition testHash.C:53
Dynamic array container with automatic resizing.