Skip to content

Instantly share code, notes, and snippets.

@FauxFaux
Last active June 20, 2017 17:29
Show Gist options
  • Select an option

  • Save FauxFaux/76ffce36ea41ce171be13ece2d7b8858 to your computer and use it in GitHub Desktop.

Select an option

Save FauxFaux/76ffce36ea41ce171be13ece2d7b8858 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
use std::collections::hash_map;
#[derive(Debug)]
enum Node {
Dir(HashMap<String, Node>),
File
}
fn list_to_tree(from: Vec<Vec<String>>) -> HashMap<String, Node> {
let mut root = HashMap::new();
for item in from {
let mut paths = item.clone();
let last = paths.pop().unwrap();
let mut curr = &mut root;
for path in paths {
if let &mut Node::Dir(ref mut map) = curr.entry(path)
.or_insert_with(|| Node::Dir(HashMap::new())) {
curr = map;
}
}
curr.insert(last, Node::File);
}
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