usiem/components/dataset/
text_set.rs

1use crate::prelude::types::LogString;
2use crossbeam_channel::Sender;
3use serde::Serialize;
4use std::collections::BTreeSet;
5use std::sync::Arc;
6#[derive(Serialize, Debug)]
7pub enum UpdateTextSet {
8    Add(LogString),
9    Remove(LogString),
10    Replace(TextSetDataset),
11}
12#[derive(Debug, Clone)]
13pub struct TextSetSynDataset {
14    dataset: Arc<TextSetDataset>,
15    comm: Sender<UpdateTextSet>,
16}
17impl TextSetSynDataset {
18    pub fn new(dataset: Arc<TextSetDataset>, comm: Sender<UpdateTextSet>) -> Self {
19        Self { dataset, comm }
20    }
21    pub fn empty() -> Self {
22        let (sender, _) = crossbeam_channel::bounded(1);
23        Self {
24            dataset: Arc::new(TextSetDataset::new()),
25            comm: sender,
26        }
27    }
28    pub fn insert<S>(&self, val: S)
29    where
30        S: Into<LogString>,
31    {
32        // Todo: improve with local cache to send retries
33        let _ = self.comm.try_send(UpdateTextSet::Add(val.into()));
34    }
35    pub fn remove<S>(&self, val: S)
36    where
37        S: Into<LogString>,
38    {
39        // Todo: improve with local cache to send retries
40        let _ = self.comm.try_send(UpdateTextSet::Remove(val.into()));
41    }
42    pub fn update(&self, data: TextSetDataset) {
43        // Todo: improve with local cache to send retries
44        let _ = self.comm.try_send(UpdateTextSet::Replace(data));
45    }
46    pub fn contains(&self, val: &LogString) -> bool {
47        // Todo improve with cached content
48        self.dataset.contains(val)
49    }
50}
51#[derive(Serialize, Debug, Default)]
52pub struct TextSetDataset {
53    data: BTreeSet<LogString>,
54}
55
56impl TextSetDataset {
57    pub fn new() -> Self {
58        Self::default()
59    }
60    pub fn insert<S>(&mut self, val: S)
61    where
62        S: Into<LogString>,
63    {
64        self.data.insert(val.into());
65    }
66    pub fn contains(&self, val: &LogString) -> bool {
67        self.data.contains(val)
68    }
69    pub fn internal_ref(&self) -> &BTreeSet<LogString> {
70        &self.data
71    }
72}
73
74#[cfg(test)]
75mod tests {
76
77    use super::*;
78    #[test]
79    fn should_be_in_set() {
80        let mut dataset = TextSetDataset::new();
81        dataset.insert(LogString::Borrowed("192.168.1.1"));
82        assert_eq!(dataset.contains(&LogString::Borrowed("192.168.1.1")), true);
83    }
84}