Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
compact-quotient-filter.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
66#ifndef COMPACT_QUOTIENT_FILTER_H
67#define COMPACT_QUOTIENT_FILTER_H
68
69#include <cstdint>
70#include <cstddef>
71#include <cmath>
72#include <algorithm>
73#include <utility>
74
75#include <ah-errors.H>
76#include <bitArray.H>
77#include <hash-fct.H>
78
79namespace Aleph {
80
92template <typename T> class Compact_Quotient_Filter
93{
94 uint8_t q_;
95 uint8_t r_;
96 size_t num_slots_;
97 size_t num_elems_;
98 uint32_t seed_;
99
100 // Bit-packed storage: each slot uses (3 + r) bits.
101 // Layout per slot:
102 // bit 0: is_occupied
103 // bit 1: is_continuation
104 // bit 2: is_shifted
105 // bits 3..(r+2): remainder
106 //
107 // Every constructor reserves the bits of all the slots, and a slot is
108 // indexed below their count: the accesses below are the unchecked ones
109 // of BitArray, fast_read() and fast_write(), which neither test the
110 // range nor may allocate.
112
113 [[nodiscard]] size_t bits_per_slot() const noexcept
114 {
115 return 3 + r_;
116 }
117
118 [[nodiscard]] size_t slot_offset(const size_t i) const noexcept
119 {
120 return i * bits_per_slot();
121 }
122
123 [[nodiscard]] uint64_t rem_mask() const noexcept
124 {
125 return (1ULL << r_) - 1;
126 }
127
128 [[nodiscard]] bool get_bit_at(const size_t slot, const size_t bit_idx) const noexcept
129 {
130 return bits_.fast_read(slot_offset(slot) + bit_idx) != 0;
131 }
132
133 void set_bit_at(const size_t slot, const size_t bit_idx, const bool v) noexcept
134 {
135 bits_.fast_write(slot_offset(slot) + bit_idx, v ? 1 : 0);
136 }
137
138 [[nodiscard]] bool get_occ(const size_t i) const noexcept
139 {
140 return get_bit_at(i, 0);
141 }
142
143 [[nodiscard]] bool get_cont(const size_t i) const noexcept
144 {
145 return get_bit_at(i, 1);
146 }
147
148 [[nodiscard]] bool get_shft(const size_t i) const noexcept
149 {
150 return get_bit_at(i, 2);
151 }
152
153 [[nodiscard]] bool slot_empty(const size_t i) const noexcept
154 {
155 const size_t off = slot_offset(i);
156 for (size_t b = 0; b < bits_per_slot(); ++b)
157 if (bits_.fast_read(off + b))
158 return false;
159 return true;
160 }
161
162 [[nodiscard]] bool has_element(const size_t i) const noexcept
163 {
164 return get_occ(i) or get_cont(i) or get_shft(i);
165 }
166
167 [[nodiscard]] bool is_run_start(const size_t i) const noexcept
168 {
169 return has_element(i) and not get_cont(i);
170 }
171
172 void set_occ(const size_t i, const bool v) noexcept
173 {
174 set_bit_at(i, 0, v);
175 }
176
177 void set_cont(const size_t i, const bool v) noexcept
178 {
179 set_bit_at(i, 1, v);
180 }
181
182 void set_shft(const size_t i, const bool v) noexcept
183 {
184 set_bit_at(i, 2, v);
185 }
186
187 [[nodiscard]] uint64_t get_rem(const size_t i) const noexcept
188 {
189 uint64_t rem = 0;
190 const size_t off = slot_offset(i) + 3;
191 for (size_t b = 0; b < r_; ++b)
192 if (bits_.fast_read(off + b))
193 rem |= (1ULL << b);
194 return rem;
195 }
196
197 void set_rem(const size_t i, const uint64_t rem) noexcept
198 {
199 const size_t off = slot_offset(i) + 3;
200 for (size_t b = 0; b < r_; ++b)
201 bits_.fast_write(off + b, (rem & (1ULL << b)) ? 1 : 0);
202 }
203
204 void set_element(const size_t i, const bool cont, const bool shft, const uint64_t rem) noexcept
205 {
206 const bool occ = get_occ(i);
207 set_cont(i, cont);
208 set_shft(i, shft);
209 set_rem(i, rem);
210 set_occ(i, occ);
211 }
212
213 void clear_element(const size_t i) noexcept
214 {
215 const bool occ = get_occ(i);
216 set_cont(i, false);
217 set_shft(i, false);
218 set_rem(i, 0);
219 set_occ(i, occ);
220 }
221
222 [[nodiscard]] size_t incr(const size_t i) const noexcept
223 {
224 return (i + 1) & (num_slots_ - 1);
225 }
226
227 [[nodiscard]] size_t decr(const size_t i) const noexcept
228 {
229 return (i - 1) & (num_slots_ - 1);
230 }
231
232 [[nodiscard]] std::pair<size_t, uint64_t> fingerprint(const T &item) const
233 {
234 const size_t h = murmur3hash(item, seed_);
235 const size_t fq = h & (num_slots_ - 1);
236 const uint64_t fr = (static_cast<uint64_t>(h) >> q_) & rem_mask();
237 return {fq, fr};
238 }
239
240 [[nodiscard]] size_t find_run_start(const size_t fq) const noexcept
241 {
242 size_t j = fq;
243 while (get_shft(j))
244 j = decr(j);
245
246 size_t i = j;
247 while (j != fq)
248 {
249 do
250 i = incr(i);
251 while (get_cont(i));
252
253 do
254 j = incr(j);
255 while (not get_occ(j));
256 }
257 return i;
258 }
259
260 [[nodiscard]] size_t find_first_unused(const size_t start) const noexcept
261 {
262 size_t i = start;
263 while (has_element(i))
264 i = incr(i);
265 return i;
266 }
267
268 void shift_elements_right(const size_t pos, size_t empty) noexcept
269 {
270 while (empty != pos)
271 {
272 const size_t prev = decr(empty);
273 const bool occ_at_empty = get_occ(empty);
274
275 const bool prev_cont = get_cont(prev);
276 const uint64_t prev_rem = get_rem(prev);
277
278 set_element(empty, prev_cont, true, prev_rem);
279 set_occ(empty, occ_at_empty);
280
281 empty = prev;
282 }
283 }
284
285 // Whether the run of the quotient `fq` holds the remainder `fr`.
286 [[nodiscard]] bool holds(const size_t fq, const uint64_t fr) const noexcept
287 {
288 if (not get_occ(fq))
289 return false;
290
291 size_t s = find_run_start(fq);
292 do
293 {
294 const uint64_t cur = get_rem(s);
295 if (cur == fr)
296 return true;
297 if (cur > fr)
298 return false;
299 s = incr(s);
300 } while (get_cont(s));
301
302 return false;
303 }
304
305 // Calls op(fq, fr) with the quotient and the remainder of each element.
306 template <class Op> void for_each_fingerprint(Op op) const
307 {
308 for (size_t fq = 0; fq < num_slots_; ++fq)
309 {
310 if (not get_occ(fq))
311 continue;
312
313 size_t s = find_run_start(fq);
314 do
315 {
316 op(fq, get_rem(s));
317 s = incr(s);
318 } while (get_cont(s));
319 }
320 }
321
322 enum class Insert_Result
323 {
324 inserted,
325 duplicate,
326 full
327 };
328
329 // Core insert of a pre-computed (fq, fr) pair. The remainder is looked
330 // for before the room: a filter holds its elements once, full or not.
331 [[nodiscard]] Insert_Result do_insert(const size_t fq, const uint64_t fr)
332 {
333 // The canonical slot is completely empty. A full filter has none.
334 if (slot_empty(fq))
335 {
336 set_occ(fq, true);
337 set_rem(fq, fr);
338 ++num_elems_;
340 }
341
342 if (get_occ(fq))
343 {
344 const size_t s = find_run_start(fq);
345 size_t pos = s;
346
347 do
348 {
349 uint64_t cur = get_rem(pos);
350 if (cur == fr)
352 if (cur > fr)
353 break;
354 pos = incr(pos);
355 } while (get_cont(pos));
356
357 if (num_elems_ >= num_slots_)
358 return Insert_Result::full;
359
360 const size_t empty = find_first_unused(pos);
361 shift_elements_right(pos, empty);
362
363 const bool at_run_start = (pos == s);
364 set_element(pos, not at_run_start, pos != fq, fr);
365
366 if (at_run_start)
367 set_cont(incr(pos), true);
368
369 ++num_elems_;
371 }
372
373 if (num_elems_ >= num_slots_)
374 return Insert_Result::full;
375
376 // With occupied(fq) set, find_run_start locates the place of the new
377 // run, of one element.
378 set_occ(fq, true);
379 const size_t s = find_run_start(fq);
380 const size_t empty = find_first_unused(s);
381 shift_elements_right(s, empty);
382
383 set_element(s, false, s != fq, fr);
384 ++num_elems_;
386 }
387
388 // Core delete: shift one slot to the left the elements that follow the
389 // removed one, at `pos`, to the end of its cluster. The occupied bit is
390 // preserved at each index.
391 //
392 // `quot` is the quotient of the run of the removed element, and `promote`
393 // says that the element next to it is a continuation of that run, which
394 // takes its place as the start of the run. A run start is no longer
395 // shifted when it lands on the slot of its own quotient, and the quotient
396 // of each run that moves is the next occupied one after that of the run
397 // before it. The occupied bit of the slot does not tell it: it may be
398 // that of a later run, whose elements are further to the right.
399 void shift_elements_left(const size_t pos, size_t quot, bool promote) noexcept
400 {
401 size_t curr = pos;
402 size_t nxt = incr(curr);
403
404 while (has_element(nxt) and get_shft(nxt))
405 {
406 if (not get_cont(nxt)) // the start of the run of the next quotient
407 do
408 quot = incr(quot);
409 while (not get_occ(quot));
410
411 const bool occ_at_curr = get_occ(curr);
412
413 const bool nxt_cont = get_cont(nxt) and not promote;
414 const uint64_t nxt_rem = get_rem(nxt);
415 promote = false;
416
417 // shifted unless it is a run start that lands on its own slot
418 set_element(curr, nxt_cont, nxt_cont or quot != curr, nxt_rem);
419 set_occ(curr, occ_at_curr);
420
421 curr = nxt;
422 nxt = incr(nxt);
423 }
424
425 clear_element(curr);
426 }
427
428public:
436 Compact_Quotient_Filter(uint8_t q, uint8_t r, uint32_t seed = 0x5F3759DF)
437 : q_(q), r_(r), num_slots_(0), num_elems_(0), seed_(seed), bits_()
438 {
439 ah_domain_error_if(q < 1 or q > 32) << "Compact_Quotient_Filter: q must be in [1, 32] (got " << static_cast<int>(q)
440 << ")";
441 ah_domain_error_if(r < 1 or r > 60) << "Compact_Quotient_Filter: r must be in [1, 60] (got " << static_cast<int>(r)
442 << ")";
443 ah_domain_error_if(q + r > 64) << "Compact_Quotient_Filter: q + r must be <= 64 (got " << static_cast<int>(q + r)
444 << ")";
445
446 num_slots_ = size_t{1} << q;
447 const size_t total_bits = num_slots_ * bits_per_slot();
448 bits_.reserve(total_bits);
449 }
450
456
472 : Compact_Quotient_Filter(1, other.r_, other.seed_)
473 {
474 swap(other);
475 }
476
483
491 {
492 swap(other);
493 return *this;
494 }
495
507 static Compact_Quotient_Filter from_capacity(size_t expected_n, double fp_rate, uint32_t seed = 0x5F3759DF)
508 {
509 ah_domain_error_if(expected_n == 0) << "Compact_Quotient_Filter::from_capacity: expected_n must be > 0";
510 ah_domain_error_if(not (fp_rate > 0.0 and fp_rate < 1.0))
511 << "Compact_Quotient_Filter::from_capacity: fp_rate must be in (0, 1) (got " << fp_rate << ")";
512
513 const auto [q_v, r_v] = estimate(expected_n, fp_rate);
514 return Compact_Quotient_Filter(q_v, r_v, seed);
515 }
516
526 {
527 auto [fq, fr] = fingerprint(item);
529 << "Compact_Quotient_Filter::insert: filter is full (" << num_elems_ << "/" << num_slots_ << ")";
530 return *this;
531 }
532
537 [[nodiscard]] bool contains(const T &item) const noexcept
538 {
539 auto [fq, fr] = fingerprint(item);
540 return holds(fq, fr);
541 }
542
547 bool remove(const T &item) noexcept
548 {
549 auto [fq, fr] = fingerprint(item);
550
551 if (not get_occ(fq))
552 return false;
553
554 size_t s = find_run_start(fq);
555 size_t pos = s;
556
557 do
558 {
559 if (get_rem(pos) == fr)
560 goto found;
561 if (get_rem(pos) > fr)
562 return false;
563 pos = incr(pos);
564 } while (get_cont(pos));
565 return false;
566
567 found: {
568 const bool was_run_start = not get_cont(pos);
569 const size_t nxt = incr(pos);
570 const bool nxt_is_cont = has_element(nxt) and get_cont(nxt);
571
572 if (was_run_start and not nxt_is_cont)
573 set_occ(fq, false);
574
575 // the next of the run, if any, takes the place of its start
576 shift_elements_left(pos, fq, was_run_start and nxt_is_cont);
577 --num_elems_;
578 return true;
579 }
580 }
581
583 [[nodiscard]] size_t size() const noexcept
584 {
585 return num_elems_;
586 }
587
589 [[nodiscard]] size_t capacity() const noexcept
590 {
591 return num_slots_;
592 }
593
595 [[nodiscard]] double load_factor() const noexcept
596 {
597 return static_cast<double>(num_elems_) / num_slots_;
598 }
599
601 [[nodiscard]] bool is_empty() const noexcept
602 {
603 return num_elems_ == 0;
604 }
605
607 [[nodiscard]] uint8_t q() const noexcept
608 {
609 return q_;
610 }
611
613 [[nodiscard]] uint8_t r() const noexcept
614 {
615 return r_;
616 }
617
619 [[nodiscard]] double false_positive_rate() const noexcept
620 {
621 return std::ldexp(1.0, -static_cast<int>(r_));
622 }
623
625 [[nodiscard]] uint32_t seed() const noexcept
626 {
627 return seed_;
628 }
629
631 [[nodiscard]] size_t memory_usage() const noexcept
632 {
633 return (num_slots_ * bits_per_slot() + 7) / 8;
634 }
635
637 void clear() noexcept
638 {
639 const size_t total_bits = num_slots_ * bits_per_slot();
640 for (size_t i = 0; i < total_bits; ++i)
641 bits_.fast_write(i, 0);
642 num_elems_ = 0;
643 }
644
663 {
664 ah_domain_error_if(q_ != other.q_ or r_ != other.r_) << "Compact_Quotient_Filter::merge: parameter mismatch";
665 ah_domain_error_if(seed_ != other.seed_) << "Compact_Quotient_Filter::merge: seed mismatch";
666 if (this == &other) // it holds its elements already
667 return;
668
669 // The elements of the other that this one does not hold are counted
670 // before any of them enters, when the two sizes say that they may not
671 // fit: a filter that cannot take them all is left as it was.
672 const size_t room = num_slots_ - num_elems_;
673 if (other.num_elems_ > room)
674 {
675 size_t missing = 0;
676 other.for_each_fingerprint([this, &missing](const size_t fq, const uint64_t fr)
677 {
678 if (not holds(fq, fr))
679 ++missing;
680 });
681 ah_overflow_error_if(missing > room)
682 << "Compact_Quotient_Filter::merge: " << missing << " elements of the other filter do not fit in the "
683 << room << " free slots of this one";
684 }
685
686 other.for_each_fingerprint([this](const size_t fq, const uint64_t fr) { (void) do_insert(fq, fr); });
687 }
688
704 [[nodiscard]] static std::pair<uint8_t, uint8_t> estimate(size_t n, double fp_rate)
705 {
706 ah_domain_error_if(n == 0) << "Compact_Quotient_Filter::estimate: n must be > 0";
707 ah_domain_error_if(not (fp_rate > 0.0 and fp_rate < 1.0))
708 << "Compact_Quotient_Filter::estimate: fp_rate must be in (0, 1) (got " << fp_rate << ")";
709
710 // as int: a rate may ask for up to 1074 bits, more than a uint8_t holds.
711 // They are counted in its exponent, which is exact: a logarithm rounds
712 // a rate just under a power of two to the power, one bit short
713 const double slots = static_cast<double>(n) / 0.75;
714 const int qv = static_cast<int>(std::max(1.0, std::ceil(std::log2(slots))));
715 const int rv = -std::ilogb(fp_rate);
716
717 ah_domain_error_if(rv > 60) << "Compact_Quotient_Filter::estimate: a rate of " << fp_rate << " asks for " << rv
718 << " remainder bits, and a filter has 60 at most";
719 ah_domain_error_if(qv > 32) << "Compact_Quotient_Filter::estimate: " << n << " elements ask for 2^" << qv
720 << " slots, and a filter has 2^32 at most";
721 ah_domain_error_if(qv + rv > 64) << "Compact_Quotient_Filter::estimate: " << n << " elements at a rate of "
722 << fp_rate << " ask for " << qv + rv << " bits of the hash, which has 64";
723 return {static_cast<uint8_t>(qv), static_cast<uint8_t>(rv)};
724 }
725
727 void swap(Compact_Quotient_Filter &other) noexcept
728 {
729 std::swap(q_, other.q_);
730 std::swap(r_, other.r_);
731 std::swap(num_slots_, other.num_slots_);
732 std::swap(num_elems_, other.num_elems_);
733 std::swap(seed_, other.seed_);
734 bits_.swap(other.bits_);
735 }
736};
737
738} // end namespace Aleph
739
740#endif // COMPACT_QUOTIENT_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
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
Space-efficient bit array implementation.
long double h
Definition btreepic.C:154
Contiguous array of bits.
Definition bitArray.H:201
void fast_write(const size_t i, const unsigned int value)
Write bit i without checking i.
Definition bitArray.H:498
int fast_read(const size_t i) const noexcept
Read bit i without any check.
Definition bitArray.H:482
void reserve(const size_t dim)
Reserve memory in advance for the bit array dim dimension.
Definition bitArray.H:344
void swap(BitArray &array) noexcept
Definition bitArray.H:541
Memory-optimized quotient filter with bit-packed slots.
Compact_Quotient_Filter & operator=(Compact_Quotient_Filter &&other) noexcept
Exchange this filter with another, which is left with the previous state of this one.
Compact_Quotient_Filter(const Compact_Quotient_Filter &other)=default
Copy the parameters and the slots of another filter.
bool is_run_start(const size_t i) const noexcept
size_t find_run_start(const size_t fq) const noexcept
void set_occ(const size_t i, const bool v) noexcept
bool get_occ(const size_t i) const noexcept
double load_factor() const noexcept
Current load factor.
size_t find_first_unused(const size_t start) const noexcept
Insert_Result do_insert(const size_t fq, const uint64_t fr)
void set_cont(const size_t i, const bool v) noexcept
size_t memory_usage() const noexcept
Memory usage in bytes.
void swap(Compact_Quotient_Filter &other) noexcept
Swap in O(1).
uint32_t seed() const noexcept
Hash seed.
Compact_Quotient_Filter(Compact_Quotient_Filter &&other)
Take the elements of another filter, which is left as an empty filter of two slots (q = 1),...
Compact_Quotient_Filter(uint8_t q, uint8_t r, uint32_t seed=0x5F3759DF)
Construct a compact quotient filter.
void clear_element(const size_t i) noexcept
static std::pair< uint8_t, uint8_t > estimate(size_t n, double fp_rate)
The quotient and the remainder bits of a filter for n elements and a target FP rate.
uint8_t q() const noexcept
Quotient bits.
size_t capacity() const noexcept
Number of slots (2^q).
void shift_elements_left(const size_t pos, size_t quot, bool promote) noexcept
void set_bit_at(const size_t slot, const size_t bit_idx, const bool v) noexcept
static Compact_Quotient_Filter from_capacity(size_t expected_n, double fp_rate, uint32_t seed=0x5F3759DF)
Construct from desired capacity and false positive rate.
bool slot_empty(const size_t i) const noexcept
bool is_empty() const noexcept
True if empty.
size_t decr(const size_t i) const noexcept
size_t incr(const size_t i) const noexcept
void clear() noexcept
Remove all elements.
bool holds(const size_t fq, const uint64_t fr) const noexcept
Compact_Quotient_Filter & insert(const T &item)
Insert an element.
bool get_cont(const size_t i) const noexcept
size_t size() const noexcept
Number of elements.
bool get_bit_at(const size_t slot, const size_t bit_idx) const noexcept
void merge(const Compact_Quotient_Filter &other)
Merge another filter (same q, r, seed).
bool remove(const T &item) noexcept
Remove an element.
void set_shft(const size_t i, const bool v) noexcept
uint8_t r() const noexcept
Remainder bits.
std::pair< size_t, uint64_t > fingerprint(const T &item) const
size_t slot_offset(const size_t i) const noexcept
void shift_elements_right(const size_t pos, size_t empty) noexcept
bool contains(const T &item) const noexcept
Test membership.
void set_rem(const size_t i, const uint64_t rem) noexcept
uint64_t get_rem(const size_t i) const noexcept
Compact_Quotient_Filter & operator=(const Compact_Quotient_Filter &other)=default
Copy the parameters and the slots of another filter.
void set_element(const size_t i, const bool cont, const bool shft, const uint64_t rem) noexcept
bool get_shft(const size_t i) const noexcept
bool has_element(const size_t i) const noexcept
double false_positive_rate() const noexcept
Theoretical FP probability ~ 2^{-r}.
Standard hash functions for Aleph types.
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
size_t murmur3hash(const Key &key, std::uint32_t seed)
Definition hash-fct.H:361