Cachemere
Modular Caching Library for C++
bloom_filter.h
1 #ifndef CACHEMERE_BLOOM_FILTER_H
2 #define CACHEMERE_BLOOM_FILTER_H
3 
4 #include <cstdint>
5 #include <functional>
6 #include <random>
7 
8 #ifdef _WIN32
9 # pragma warning(push)
10 # pragma warning(disable : 4244)
11 # pragma warning(disable : 4018)
12 #endif
13 
14 #include <boost/dynamic_bitset.hpp>
15 
16 #ifdef _WIN32
17 # pragma warning(pop)
18 #endif
19 
20 #include "hash_mixer.h"
21 
22 namespace cachemere::policy::detail {
23 
29 template<typename ItemHash> class BloomFilter
30 {
31 public:
40  BloomFilter(uint32_t cardinality);
41 
44  template<typename ItemKey> void add(const ItemKey& item);
45 
47  void clear();
48 
54  template<typename ItemKey> [[nodiscard]] bool maybe_contains(const ItemKey& item) const;
55 
58  [[nodiscard]] size_t memory_used() const noexcept;
59 
65  [[nodiscard]] double saturation() const noexcept;
66 
67 private:
68  using BitsetBlock = uint8_t;
69  using BitSet = boost::dynamic_bitset<BitsetBlock>;
70 
71  uint32_t m_cardinality;
72  BitSet m_filter;
73  uint32_t m_nb_hashes;
74 };
75 
76 } // namespace cachemere::policy::detail
77 
78 #include "bloom_filter.hpp"
79 
80 #endif
cachemere::policy::detail::BloomFilter
Probabilistic data structure for representing sets in a space-efficient format.
Definition: bloom_filter.h:29
cachemere::policy::detail::BloomFilter::saturation
double saturation() const noexcept
Get the saturation of the filter.
Definition: bloom_filter.hpp:53
cachemere::policy::detail::BloomFilter::BloomFilter
BloomFilter(uint32_t cardinality)
Constructor.
Definition: bloom_filter.hpp:8
cachemere::policy::detail::BloomFilter::memory_used
size_t memory_used() const noexcept
Get an estimate of the memory consumption of the filter.
Definition: bloom_filter.hpp:48
cachemere::policy::detail::BloomFilter::maybe_contains
bool maybe_contains(const ItemKey &item) const
Test membership of the specified item.
Definition: bloom_filter.hpp:32
cachemere::policy::detail::BloomFilter::clear
void clear()
Clear the filter while keeping the allocated memory.
Definition: bloom_filter.hpp:27
cachemere::policy::detail::BloomFilter::add
void add(const ItemKey &item)
Add an item to the filter.
Definition: bloom_filter.hpp:15