hopr_transport_protocol/
bloom.rs1use std::sync::Arc;
2
3use async_lock::RwLock;
4use hopr_internal_types::protocol::TagBloomFilter;
5use hopr_platform::file::native::{read_file, write};
6use tracing::{debug, error, info};
7
8#[derive(Debug, Clone)]
9pub struct WrappedTagBloomFilter {
10 path: String,
11 tbf: Arc<RwLock<TagBloomFilter>>,
12}
13
14impl WrappedTagBloomFilter {
15 pub fn new(path: String) -> Self {
16 let tbf = read_file(&path)
17 .and_then(|data| {
18 debug!(path = &path, "Found and loading a tag Bloom filter");
19 TagBloomFilter::from_bytes(&data)
20 .map_err(|e| hopr_platform::error::PlatformError::GeneralError(e.to_string()))
21 })
22 .unwrap_or_else(|_| {
23 debug!(path = &path, "No tag Bloom filter found, using empty");
24 TagBloomFilter::default()
25 });
26
27 Self {
28 path,
29 tbf: Arc::new(RwLock::new(tbf)),
30 }
31 }
32
33 pub async fn with_write_lock<T>(&self, f: impl FnOnce(&mut TagBloomFilter) -> T) -> T {
34 let mut tbf = self.tbf.write().await;
35 f(&mut tbf)
36 }
37
38 pub async fn save(&self) {
39 let bloom = self.tbf.read().await.clone(); if let Err(e) = write(&self.path, bloom.to_bytes()) {
42 error!(erorr = %e, "Tag Bloom filter save failed")
43 } else {
44 info!("Tag Bloom filter saved successfully")
45 };
46 }
47}