summaryrefslogtreecommitdiff
path: root/src/index.rs
blob: ed0183e64f66906c3107515199dc8429b86d1f41 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use crate::chunkid::ChunkId;
use std::collections::HashMap;
use std::default::Default;

/// A chunk index.
///
/// A chunk index lets the server quickly find chunks based on a
/// string key/value pair, or whether they are generations.
#[derive(Debug, Default)]
pub struct Index {
    map: HashMap<(String, String), Vec<ChunkId>>,
    generations: Vec<ChunkId>,
}

impl Index {
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn len(&self) -> usize {
        self.map.len()
    }

    pub fn insert(&mut self, id: ChunkId, key: &str, value: &str) {
        let kv = kv(key, value);
        if let Some(v) = self.map.get_mut(&kv) {
            v.push(id)
        } else {
            self.map.insert(kv, vec![id]);
        }
    }

    pub fn find(&self, key: &str, value: &str) -> Vec<ChunkId> {
        let kv = kv(key, value);
        if let Some(v) = self.map.get(&kv) {
            v.clone()
        } else {
            vec![]
        }
    }

    pub fn insert_generation(&mut self, id: ChunkId) {
        self.generations.push(id)
    }

    pub fn find_generations(&self) -> Vec<ChunkId> {
        self.generations.clone()
    }
}

fn kv(key: &str, value: &str) -> (String, String) {
    (key.to_string(), value.to_string())
}

#[cfg(test)]
mod test {
    use super::{ChunkId, Index};

    #[test]
    fn is_empty_initially() {
        let idx = Index::default();
        assert!(idx.is_empty());
    }

    #[test]
    fn remembers_inserted() {
        let id: ChunkId = "id001".parse().unwrap();
        let mut idx = Index::default();
        idx.insert(id.clone(), "sha256", "abc");
        assert!(!idx.is_empty());
        assert_eq!(idx.len(), 1);
        let ids: Vec<ChunkId> = idx.find("sha256", "abc");
        assert_eq!(ids, vec![id]);
    }

    #[test]
    fn does_not_find_uninserted() {
        let id: ChunkId = "id001".parse().unwrap();
        let mut idx = Index::default();
        idx.insert(id, "sha256", "abc");
        assert_eq!(idx.find("sha256", "def").len(), 0)
    }

    #[test]
    fn has_no_generations_initially() {
        let idx = Index::default();
        assert_eq!(idx.find_generations(), vec![]);
    }

    #[test]
    fn remembers_generation() {
        let id: ChunkId = "id001".parse().unwrap();
        let mut idx = Index::default();
        idx.insert_generation(id.clone());
        assert_eq!(idx.find_generations(), vec![id]);
    }
}