Created
June 20, 2017 17:55
-
-
Save FauxFaux/3ec61ae18ca8986f8a1a0324dbc8df70 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::collections::HashMap; | |
| use std::collections::hash_map; | |
| #[derive(Debug)] | |
| enum Node { | |
| Dir(HashMap<String, Node>), | |
| File | |
| } | |
| fn add(into: &mut HashMap<String, Node>, remaining: &[String]) { | |
| match remaining.len() { | |
| 0 => unreachable!(), | |
| 1 => { into.insert(remaining[0].to_string(), Node::File); }, | |
| _ => { | |
| match into.entry(remaining[0].to_string()) { | |
| hash_map::Entry::Occupied(mut exists) => { | |
| if let &mut Node::Dir(ref mut map) = exists.get_mut() { | |
| add(map, &remaining[1..]); | |
| } | |
| } | |
| hash_map::Entry::Vacant(vacant) => { | |
| let mut map = HashMap::new(); | |
| add(&mut map, &remaining[1..]); | |
| vacant.insert(Node::Dir(map)); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| fn list_to_tree(from: Vec<Vec<String>>) -> HashMap<String, Node> { | |
| let mut root = HashMap::new(); | |
| for item in from { | |
| add(&mut root, &item); | |
| } | |
| root | |
| } | |
| fn main() { | |
| let mut example = Vec::new(); | |
| example.push(vec!["foo".to_string(), "bar".to_string()]); | |
| example.push(vec!["foo".to_string(), "baz".to_string()]); | |
| let mut expected = HashMap::new(); | |
| let mut foo = HashMap::new(); | |
| foo.insert("bar".to_string(), Node::File); | |
| foo.insert("baz".to_string(), Node::File); | |
| expected.insert("foo", Node::Dir(foo)); | |
| println!("{:?}", list_to_tree(example)); | |
| println!("{:?}", expected); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment