aboutsummaryrefslogtreecommitdiff
path: root/database/src/filter/binning.rs
blob: 858831790798b6355e4c043ffa1dbee63b351bdc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use jellyobject::{Object, Path};

/// Sorted list of components to bin objects by filterable values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binning(Vec<BinningComponent>);

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub enum BinningComponent {
    Has(Path),
    Match(Path),
}

impl Binning {
    pub fn new(mut comps: Vec<BinningComponent>) -> Self {
        comps.sort();
        Self(comps)
    }
    pub fn apply(&self, ob: Object<'_>, keys: &mut Vec<Vec<u8>>) {
        for f in &self.0 {
            f.apply(ob, keys);
        }
    }
}
impl BinningComponent {
    pub fn apply(&self, ob: Object<'_>, keys: &mut Vec<Vec<u8>>) {
        match self {
            BinningComponent::Has(path) => {
                let has = path.get_matching_value(ob).is_some();
                for co in keys {
                    co.push(has as u8)
                }
            }
            BinningComponent::Match(path) => {
                let mut new_out = Vec::new();
                for value in path.get_matching_values(ob) {
                    for mut co in keys.clone() {
                        co.extend((co.len() as u32).to_be_bytes());
                        co.extend(value);
                        new_out.push(co);
                    }
                }
                *keys = new_out;
            }
        }
    }
}