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
/// Used for storing Buffers in a QUIC
#[derive(Debug)]
pub struct SortedVec<K, V> {
    pub data: Vec<(K, V)>,
}

impl<K, V> Default for SortedVec<K, V> {
    fn default() -> Self { Self { data: vec![] } }
}

impl<K, V> SortedVec<K, V>
where
    K: Ord + Copy,
{
    pub fn insert(&mut self, k: K, v: V) {
        self.data.push((k, v));
        self.data.sort_by_key(|&(k, _)| k);
    }

    pub fn delete(&mut self, k: &K) -> Option<V> {
        if let Ok(i) = self.data.binary_search_by_key(k, |&(k, _)| k) {
            Some(self.data.remove(i).1)
        } else {
            None
        }
    }

    pub fn get(&self, k: &K) -> Option<&V> {
        if let Ok(i) = self.data.binary_search_by_key(k, |&(k, _)| k) {
            Some(&self.data[i].1)
        } else {
            None
        }
    }

    pub fn get_mut(&mut self, k: &K) -> Option<&mut V> {
        if let Ok(i) = self.data.binary_search_by_key(k, |&(k, _)| k) {
            Some(&mut self.data[i].1)
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sorted_vec() {
        let mut vec = SortedVec::default();
        vec.insert(10, "Hello");
        println!("{:?}", vec.data);
        vec.insert(30, "World");
        println!("{:?}", vec.data);
        vec.insert(20, " ");
        println!("{:?}", vec.data);
        assert_eq!(vec.data[0].1, "Hello");
        assert_eq!(vec.data[1].1, " ");
        assert_eq!(vec.data[2].1, "World");
        assert_eq!(vec.get(&30), Some(&"World"));
        assert_eq!(vec.get_mut(&20), Some(&mut " "));
        assert_eq!(vec.get(&10), Some(&"Hello"));
        assert_eq!(vec.delete(&40), None);
        assert_eq!(vec.delete(&10), Some("Hello"));
        assert_eq!(vec.delete(&10), None);
        assert_eq!(vec.get(&30), Some(&"World"));
        assert_eq!(vec.get_mut(&20), Some(&mut " "));
        assert_eq!(vec.get(&10), None);
    }
}