lsm_tree/table/filter/
mod.rs

1// Copyright (c) 2024-present, fjall-rs
2// This source code is licensed under both the Apache 2.0 and MIT License
3// (found in the LICENSE-* files in the repository)
4
5pub mod bit_array;
6pub mod block;
7pub mod blocked_bloom;
8pub mod standard_bloom;
9
10use standard_bloom::Builder as StandardBloomFilterBuilder;
11
12#[derive(Copy, Clone, Debug, PartialEq)]
13pub enum BloomConstructionPolicy {
14    BitsPerKey(f32),
15    FpRate(f32), // TODO: 3.0.0 rename: FalsePositiveRate?
16}
17
18impl Default for BloomConstructionPolicy {
19    fn default() -> Self {
20        Self::BitsPerKey(10.0)
21    }
22}
23
24impl BloomConstructionPolicy {
25    #[must_use]
26    pub fn init(&self, n: usize) -> StandardBloomFilterBuilder {
27        use standard_bloom::Builder;
28
29        match self {
30            Self::BitsPerKey(bpk) => Builder::with_bpk(n, *bpk),
31            Self::FpRate(fpr) => Builder::with_fp_rate(n, *fpr),
32        }
33    }
34
35    #[must_use]
36    pub fn is_active(&self) -> bool {
37        match self {
38            Self::BitsPerKey(bpk) => *bpk > 0.0,
39            Self::FpRate(fpr) => *fpr > 0.0,
40        }
41    }
42
43    #[must_use]
44    pub fn estimated_key_bits(&self, n: usize) -> f32 {
45        match self {
46            Self::BitsPerKey(bpk) => *bpk,
47            Self::FpRate(fpr) => {
48                let m = StandardBloomFilterBuilder::calculate_m(n, *fpr);
49                (m / n) as f32
50            }
51        }
52    }
53}
54
55#[derive(Copy, Clone, PartialEq, Eq, Debug)]
56enum FilterType {
57    StandardBloom,
58    BlockedBloom,
59}
60
61impl TryFrom<u8> for FilterType {
62    type Error = crate::Error;
63
64    fn try_from(value: u8) -> Result<Self, Self::Error> {
65        match value {
66            0 => Ok(Self::StandardBloom),
67            1 => Ok(Self::BlockedBloom),
68            _ => Err(crate::Error::Decode(crate::DecodeError::InvalidTag((
69                "FilterType",
70                value,
71            )))),
72        }
73    }
74}
75
76impl From<FilterType> for u8 {
77    fn from(value: FilterType) -> Self {
78        match value {
79            FilterType::StandardBloom => 0,
80            FilterType::BlockedBloom => 1,
81        }
82    }
83}