aboutsummaryrefslogtreecommitdiff
path: root/database/src/kv/binning.rs
blob: d9b173dbbcff3abb2d72dc667de9e8d99fbc98c1 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/*
    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 crate::{Filter, Value};
use jellyobject::{Object, Path};

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

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
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) => {
                if path.get_matching_value(ob).is_none() {
                    keys.clear();
                }
            }
            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((value.len() as u32).to_be_bytes());
                        co.extend(value);
                        new_out.push(co);
                    }
                }
                *keys = new_out;
            }
        }
    }
}

impl Filter<'_> {
    pub fn get_binnings(&self) -> Vec<Binning> {
        self.get_bins_inner()
            .into_iter()
            .map(|e| Binning(e.into_iter().map(|(e, _)| e).collect()))
            .collect()
    }
    pub fn get_bins(&self) -> Vec<(Binning, Vec<u8>)> {
        self.get_bins_inner()
            .into_iter()
            .map(|e| {
                let (a, b): (Vec<BinningComponent>, Vec<Vec<u8>>) = e.into_iter().unzip();
                (Binning(a), b.into_iter().flatten().collect())
            })
            .collect()
    }
    fn get_bins_inner(&self) -> Vec<Vec<(BinningComponent, Vec<u8>)>> {
        match self {
            Filter::True => vec![vec![]],
            Filter::All(filters) => {
                let mut o = vec![vec![]];
                for filter in filters {
                    let mut new_o = Vec::new();
                    for par in filter.get_bins_inner() {
                        for mut prev in o.clone() {
                            prev.extend(par.clone());
                            new_o.push(prev);
                        }
                    }
                    o = new_o;
                }
                o
            }
            Filter::Any(filters) => filters.iter().flat_map(|f| f.get_bins_inner()).collect(),
            Filter::Match(path, value) => {
                vec![vec![(BinningComponent::Match(path.to_owned()), {
                    let mut co = Vec::new();
                    write_value_with_len(value, &mut co);
                    co
                })]]
            }
            Filter::Has(path) => {
                vec![vec![(BinningComponent::Has(path.to_owned()), vec![])]]
            }
        }
    }
}

pub fn write_value_with_len(value: &Value, out: &mut Vec<u8>) {
    match value {
        Value::Tag(tag) => {
            out.extend(4u32.to_be_bytes());
            out.extend(tag.0.to_be_bytes());
        }
        Value::U32(x) => {
            out.extend(4u32.to_be_bytes());
            out.extend(x.to_be_bytes());
        }
        Value::U64(x) => {
            out.extend(8u32.to_be_bytes());
            out.extend(x.to_be_bytes());
        }
        Value::I64(x) => {
            out.extend(8u32.to_be_bytes());
            out.extend(x.to_be_bytes());
        }
        Value::String(s) => {
            out.extend((s.len() as u32).to_be_bytes());
            out.extend(s.as_bytes());
        }
        Value::Binary(s) => {
            out.extend((s.len() as u32).to_be_bytes());
            out.extend(&**s);
        }
    }
}

#[cfg(test)]
mod test {
    use jellyobject::{Path, Tag};

    use crate::{
        Filter,
        kv::binning::{Binning, BinningComponent},
    };

    #[test]
    fn all() {
        let f = Filter::All(vec![
            Filter::Has(Path(vec![Tag(0)])),
            Filter::Has(Path(vec![Tag(1)])),
        ]);
        let bins = vec![Binning(vec![
            BinningComponent::Has(Path(vec![Tag(0)])),
            BinningComponent::Has(Path(vec![Tag(1)])),
        ])];
        assert_eq!(f.get_binnings(), bins)
    }

    #[test]
    fn any() {
        let f = Filter::Any(vec![
            Filter::Has(Path(vec![Tag(0)])),
            Filter::Has(Path(vec![Tag(1)])),
        ]);
        let bins = vec![
            Binning::new(vec![BinningComponent::Has(Path(vec![Tag(0)]))]),
            Binning::new(vec![BinningComponent::Has(Path(vec![Tag(1)]))]),
        ];
        assert_eq!(f.get_binnings(), bins)
    }

    #[test]
    fn nested() {
        let f = Filter::All(vec![
            Filter::Any(vec![
                Filter::Has(Path(vec![Tag(0)])),
                Filter::Has(Path(vec![Tag(1)])),
            ]),
            Filter::Any(vec![
                Filter::Has(Path(vec![Tag(2)])),
                Filter::Has(Path(vec![Tag(3)])),
            ]),
        ]);
        let bins = vec![
            Binning::new(vec![
                BinningComponent::Has(Path(vec![Tag(0)])),
                BinningComponent::Has(Path(vec![Tag(2)])),
            ]),
            Binning::new(vec![
                BinningComponent::Has(Path(vec![Tag(1)])),
                BinningComponent::Has(Path(vec![Tag(2)])),
            ]),
            Binning::new(vec![
                BinningComponent::Has(Path(vec![Tag(0)])),
                BinningComponent::Has(Path(vec![Tag(3)])),
            ]),
            Binning::new(vec![
                BinningComponent::Has(Path(vec![Tag(1)])),
                BinningComponent::Has(Path(vec![Tag(3)])),
            ]),
        ];
        assert_eq!(f.get_binnings(), bins)
    }
}