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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
#![feature(box_patterns)] #![feature(test)] #[cfg(test)] #[macro_use] extern crate quickcheck; #[cfg(test)] extern crate test; #[cfg(test)] extern crate tempfile; extern crate serde; #[macro_use] extern crate serde_derive; extern crate bincode; use std::fs::OpenOptions; use std::io::{self, BufReader, BufWriter}; use std::collections::HashMap; use bincode::{serialize_into, deserialize_from, Infinite}; pub use bincode::Error as BincodeError; type Result<T> = std::result::Result<T, BincodeError>; #[derive(Default, Debug, PartialEq, Serialize, Deserialize)] pub struct Trie<V> { key: Option<char>, children: HashMap<Option<char>, Trie<V>>, contents: Option<V>, } impl<V> Trie<V> { pub fn load_from_file(path: &str) -> Result<Self> where for<'de> V: serde::Serialize + serde::Deserialize<'de>, { let f = OpenOptions::new() .read(true) .write(true) .create(true) .open(path) .expect("Couldn't open trie file"); let mut br = BufReader::new(f); match deserialize_from(&mut br, Infinite) { Ok(x) => Ok(x), Err(box bincode::ErrorKind::IoError(e)) => { if e.kind() == io::ErrorKind::UnexpectedEof { return Ok(Trie { key: None, children: HashMap::new(), contents: None, }); } Err(Box::new(bincode::ErrorKind::IoError(e))) } Err(e) => Err(e), } } pub fn insert(&mut self, key: &str, contents: V) -> Option<V> { let mut chars = key.chars(); let mut key_i_need = chars.next(); if self.key == key_i_need { if chars.size_hint().0 == 0 { let ret = self.contents.take(); self.contents = Some(contents); return ret; } key_i_need = chars.next(); } if let Some(c) = self.children.get_mut(&key_i_need) { return c.insert(chars.as_str(), contents); } let mut trie = Trie { key: key_i_need, children: HashMap::new(), contents: None, }; trie.insert(chars.as_str(), contents); self.children.insert(key_i_need, trie); None } pub fn get(&self, key: &str) -> Option<&V> { let mut chars = key.chars(); let mut key_i_need = chars.next(); if self.key == key_i_need { if chars.size_hint().0 == 0 { return self.contents.as_ref(); } key_i_need = chars.next(); } if let Some(c) = self.children.get(&key_i_need) { return c.get(chars.as_str()); } None } pub fn get_mut(&mut self, key: &str) -> Option<&mut V> { let mut chars = key.chars(); let mut key_i_need = chars.next(); if self.key == key_i_need { if chars.size_hint().0 == 0 { return self.contents.as_mut(); } key_i_need = chars.next(); } if let Some(c) = self.children.get_mut(&key_i_need) { return c.get_mut(chars.as_str()); } None } pub fn save_to_file(&mut self, path: &str) -> Result<()> where for<'de> V: serde::Serialize + serde::Deserialize<'de>, { let f = OpenOptions::new() .read(true) .write(true) .create(true) .open(path) .expect("Couldn't open trie file"); let mut bw = BufWriter::new(f); serialize_into(&mut bw, self, Infinite) } } #[cfg(test)] mod tests { use super::*; use tempfile::NamedTempFile; use std::collections::BTreeMap; use quickcheck::TestResult; use test::Bencher; fn insertion_test_helper(mut v: Vec<(String, String)>, replace: bool) -> TestResult { let v = v.iter_mut() .map(|&mut (ref i, ref j)| { let v = if !replace { j } else { "this_will_be_replaced" }; (i, v) }) .collect::<Vec<_>>(); let mut t = Trie::default(); let mut bt = BTreeMap::new(); for &(i, j) in v.iter() { assert_eq!(t.insert(i, j), bt.insert(i, j)); } for &(i, _) in v.iter() { assert_eq!(t.get(i), bt.get(i)); } TestResult::from_bool(true) } #[test] fn basic_insertion() -> () { let testcases = vec![ (String::from("def"), String::from("contents1")), (String::from("abc"), String::from("contents2")), (String::from("abf"), String::from("contents3")), ]; insertion_test_helper(testcases, false); } #[test] fn test_get_mut() -> () { let mut trie = Trie::default(); trie.insert("abc", vec!["test1"]); { let thing_to_modify = trie.get_mut("abc").unwrap(); thing_to_modify.push("test2"); } assert_eq!(*trie.get("abc").unwrap(), vec!["test1", "test2"]); } quickcheck! { fn random_insertion(v: Vec<(String, String)>) -> TestResult { insertion_test_helper(v, false) } fn replace_insertion(v: Vec<(String, String)>) -> TestResult { insertion_test_helper(v, true) } } #[test] fn save_to_file_roundtrip() -> () { let trie_file = NamedTempFile::new().expect("failed to create temporary file"); let trie_file_name = trie_file.path().to_str().unwrap(); let mut trie = Trie::default(); trie.insert("abc", String::from("contents1")); trie.insert("abd", String::from("contents2")); trie.insert("hello", String::from("world")); trie.save_to_file(trie_file_name).expect( "Couldn't save trie to file", ); let trie2 = Trie::load_from_file(trie_file_name).expect("Couldn't load trie from file"); assert_eq!(trie, trie2); } #[bench] fn bench_many_children(b: &mut Bencher) { let mut trie = Trie::default(); let utf8_max_char = 128; let last_child = &String::from_utf8(vec![utf8_max_char - 1]).unwrap(); for i in 0..utf8_max_char { trie.insert(&String::from_utf8(vec![i]).unwrap(), ""); } assert_eq!((utf8_max_char) as usize, trie.children.len()); b.iter(|| trie.get(&last_child)); } }