bip_bencode/access/
dict.rs

1use std::borrow::Cow;
2use std::collections::BTreeMap;
3
4/// Trait for working with generic map data structures.
5pub trait BDictAccess<K, V> {
6    /// Convert the dictionary to an unordered list of key/value pairs.
7    fn to_list(&self) -> Vec<(&K, &V)>;
8
9    /// Lookup a value in the dictionary.
10    fn lookup(&self, key: &[u8]) -> Option<&V>;
11
12    /// Lookup a mutable value in the dictionary.
13    fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V>;
14
15    /// Insert a key/value pair into the dictionary.
16    fn insert(&mut self, key: K, value: V) -> Option<V>;
17
18    /// Remove a value from the dictionary and return it.
19    fn remove(&mut self, key: &[u8]) -> Option<V>;
20}
21
22impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> {
23    fn to_list(&self) -> Vec<(&&'a [u8], &V)> {
24        self.iter().map(|(k, v)| (k, v)).collect()
25    }
26
27    fn lookup(&self, key: &[u8]) -> Option<&V> {
28        self.get(key)
29    }
30
31    fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V> {
32        self.get_mut(key)
33    }
34
35    fn insert(&mut self, key: &'a [u8], value: V) -> Option<V> {
36        self.insert(key, value)
37    }
38
39    fn remove(&mut self, key: &[u8]) -> Option<V> {
40        self.remove(key)
41    }
42}
43
44impl<'a, V> BDictAccess<Cow<'a, [u8]>, V> for BTreeMap<Cow<'a, [u8]>, V> {
45    fn to_list(&self) -> Vec<(&Cow<'a, [u8]>, &V)> {
46        self.iter().map(|(k, v)| (k, v)).collect()
47    }
48
49    fn lookup(&self, key: &[u8]) -> Option<&V> {
50        self.get(key)
51    }
52
53    fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V> {
54        self.get_mut(key)
55    }
56
57    fn insert(&mut self, key: Cow<'a, [u8]>, value: V) -> Option<V> {
58        self.insert(key, value)
59    }
60
61    fn remove(&mut self, key: &[u8]) -> Option<V> {
62        self.remove(key)
63    }
64}