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
use std::{mem, ptr};
use std::ops::BitOr;

/// 2048 bits long hash.
pub struct Bloom([u8; 256]);

impl From<[u8; 256]> for Bloom {
	fn from(bytes: [u8; 256]) -> Self {
		Bloom(bytes)
	}
}

impl Into<[u8; 256]> for Bloom {
	fn into(self) -> [u8; 256] {
		self.0
	}
}

impl Default for Bloom {
	fn default() -> Self {
		Bloom(unsafe { mem::zeroed() })
	}
}

impl Clone for Bloom {
	fn clone(&self) -> Self {
		let mut bloom = Bloom::default();
		unsafe {
			ptr::copy(self.0.as_ptr(), bloom.0.as_mut_ptr(), self.0.len());
		}
		bloom
	}
}

impl BitOr for Bloom {
	type Output = Bloom;

	fn bitor(self, rhs: Self) -> Bloom {
		let mut bloom = Bloom::default();
		for i in 0..bloom.0.len() {
			bloom.0[i] = self.0[i] | rhs.0[i]
		}
		bloom
	}
}

impl <'a> BitOr for &'a Bloom {
	type Output = Bloom;

	fn bitor(self, rhs: Self) -> Bloom {
		let mut bloom = Bloom::default();
		for i in 0..bloom.0.len() {
			bloom.0[i] = self.0[i] | rhs.0[i]
		}
		bloom
	}
}

/// TODO: this functions should be moved to trait and made generic, for bloom
/// with any size.
impl Bloom {
	/// Quickly checks if this bloom contains the other bloom.
	pub fn contains(&self, bloom: &Bloom) -> bool {
		self.0.iter()
			.zip(bloom.0.iter())
			.all(|(s, b)| &(s & b) == b)
	}
}