pub const FINGERPRINT_SIZE: usize = 1;
pub const BUCKET_SIZE: usize = 4;
const EMPTY_FINGERPRINT_DATA: [u8; FINGERPRINT_SIZE] = [100; FINGERPRINT_SIZE];
#[derive(PartialEq, Copy, Clone, Hash)]
pub struct Fingerprint {
pub data: [u8; FINGERPRINT_SIZE],
}
impl Fingerprint {
pub fn from_data(data: [u8; FINGERPRINT_SIZE]) -> Option<Self> {
let result = Self { data };
if result.is_empty() {
None
} else {
Some(result)
}
}
pub fn empty() -> Self {
Self {
data: EMPTY_FINGERPRINT_DATA,
}
}
pub fn is_empty(&self) -> bool {
self.data == EMPTY_FINGERPRINT_DATA
}
fn slice_copy(&mut self, fingerprint: &[u8]) {
self.data.copy_from_slice(fingerprint);
}
}
#[derive(Clone)]
pub struct Bucket {
pub buffer: [Fingerprint; BUCKET_SIZE],
}
impl Bucket {
pub fn new() -> Self {
Self {
buffer: [Fingerprint::empty(); BUCKET_SIZE],
}
}
pub fn insert(&mut self, fp: Fingerprint) -> bool {
for entry in &mut self.buffer {
if entry.is_empty() {
*entry = fp;
return true;
}
}
false
}
pub fn delete(&mut self, fp: Fingerprint) -> bool {
match self.get_fingerprint_index(fp) {
Some(index) => {
self.buffer[index] = Fingerprint::empty();
true
}
None => false,
}
}
pub fn get_fingerprint_index(&self, fp: Fingerprint) -> Option<usize> {
self.buffer.iter().position(|e| *e == fp)
}
pub fn get_fingerprint_data(&self) -> Vec<u8> {
self.buffer
.iter()
.flat_map(|f| f.data.iter())
.cloned()
.collect()
}
}
impl From<&[u8]> for Bucket {
fn from(fingerprints: &[u8]) -> Self {
let mut buffer = [Fingerprint::empty(); BUCKET_SIZE];
for (idx, value) in fingerprints.chunks(FINGERPRINT_SIZE).enumerate() {
buffer[idx].slice_copy(value);
}
Self { buffer }
}
}