|
| 1 | +use crate::syntax::map::UnorderedMap as Map; |
| 2 | +use std::hash::Hash; |
| 3 | + |
| 4 | +pub struct Hierarchy<'a, K, T> { |
| 5 | + direct: Vec<&'a T>, |
| 6 | + nested: Vec<(&'a K, Hierarchy<'a, K, T>)>, |
| 7 | +} |
| 8 | + |
| 9 | +impl<'a, K, T> Hierarchy<'a, K, T> { |
| 10 | + pub fn new<F, I>(items: Vec<&'a T>, keyfn: F) -> Self |
| 11 | + where |
| 12 | + K: Hash + Eq, |
| 13 | + F: Fn(&'a T) -> I, |
| 14 | + I: IntoIterator<Item = &'a K>, |
| 15 | + { |
| 16 | + sort_by_level(items, &keyfn, 0) |
| 17 | + } |
| 18 | + |
| 19 | + pub fn direct_content(&self) -> &[&'a T] { |
| 20 | + &self.direct |
| 21 | + } |
| 22 | + |
| 23 | + pub fn nested_content(&self) -> impl Iterator<Item = (&'a K, &Hierarchy<'a, K, T>)> { |
| 24 | + self.nested.iter().map(|(k, entries)| (*k, entries)) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +fn sort_by_level<'a, K, T, F, I>(items: Vec<&'a T>, keyfn: &F, depth: usize) -> Hierarchy<'a, K, T> |
| 29 | +where |
| 30 | + K: Hash + Eq, |
| 31 | + F: Fn(&'a T) -> I, |
| 32 | + I: IntoIterator<Item = &'a K>, |
| 33 | +{ |
| 34 | + let mut direct = Vec::new(); |
| 35 | + let mut nested_levels = Vec::new(); |
| 36 | + let mut index_of_levels = Map::new(); |
| 37 | + |
| 38 | + for item in items { |
| 39 | + if let Some(elem) = keyfn(item).into_iter().nth(depth) { |
| 40 | + match index_of_levels.get(elem) { |
| 41 | + None => { |
| 42 | + index_of_levels.insert(elem, nested_levels.len()); |
| 43 | + nested_levels.push((elem, vec![item])); |
| 44 | + } |
| 45 | + Some(&index) => nested_levels[index].1.push(item), |
| 46 | + } |
| 47 | + continue; |
| 48 | + } |
| 49 | + direct.push(item); |
| 50 | + } |
| 51 | + |
| 52 | + let nested = nested_levels |
| 53 | + .into_iter() |
| 54 | + .map(|(k, items)| (k, sort_by_level(items, keyfn, depth + 1))) |
| 55 | + .collect(); |
| 56 | + |
| 57 | + Hierarchy { direct, nested } |
| 58 | +} |
0 commit comments