aboutsummaryrefslogtreecommitdiff
path: root/src/vector.rs
blob: dfd2d71fded1f02b6607d18572f70a2f3912a237 (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
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};

/// Represents the content of a cached file.
/// It is stored as a HashMap, because we do not
/// have to store the zeros. With that we save a lot
/// of storage.
#[derive(Clone, Debug)]
pub struct FileVector {
    data : HashMap<u64, u64>
}

impl Deref for FileVector {
    type Target = HashMap<u64, u64>;
    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl DerefMut for FileVector {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}

impl Default for FileVector {
    fn default() -> Self {
        Self::new()
    }
}

impl FileVector {
    pub fn new() -> Self {
        Self { data : HashMap::new() }
    }

    pub fn from_string(hex : &str) -> Self {
        let mut data : HashMap<u64, u64> = HashMap::new();
        let data_chunks : Vec<&str> = hex.split(' ').collect();

        for chunk in data_chunks {
            if !chunk.is_empty() {
                let n : Vec<&str> = chunk.split(';').collect();
                let i : u64 = u64::from_str_radix(n[0], 16).expect("could not extract index");
                let v : u64 = u64::from_str_radix(n[1], 16).expect("could not extract value");
                data.insert(i, v);
            }
        }

        Self { data }
    }

    pub fn stringify(&self) -> String {
        let mut hex = String::new();

        for (i, v) in self.data.iter() {
            hex += &format!("{:x};{:x} ", *i, *v);
        }

        hex.trim().to_string()
    }
}

pub fn scalar_product(a : &FileVector, b : &FileVector) -> u64 {
    let mut c = 0;
    for (i, x) in a.iter() {
        c += x * (b.get(i).unwrap_or(&0));
    }
    c
}