use std::collections::{BTreeMap, BTreeSet};
use crate::{Error, Result};
pub fn precedence(list: &[String], depends: &BTreeMap<String, Vec<String>>) -> Result<Vec<String>> {
let names: BTreeSet<&str> = list.iter().map(String::as_str).collect();
let mut placed: BTreeSet<&str> = BTreeSet::new();
let mut out = Vec::new();
while out.len() < list.len() {
let next = list.iter().find(|n| {
!placed.contains(n.as_str())
&& depends.get(n.as_str()).is_none_or(|deps| {
deps.iter()
.all(|d| !names.contains(d.as_str()) || placed.contains(d.as_str()))
})
});
let Some(next) = next else {
let cycle: Vec<&str> = list
.iter()
.map(String::as_str)
.filter(|n| !placed.contains(n))
.collect();
return Err(Error::Pack(format!(
"the dependencies of the packs {} form a cycle",
cycle.join(", ")
)));
};
placed.insert(next);
out.push(next.clone());
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn order(list: &[&str], deps: &[(&str, &[&str])]) -> Result<Vec<String>> {
let list: Vec<String> = list.iter().map(|s| s.to_string()).collect();
let deps = deps
.iter()
.map(|(n, d)| (n.to_string(), d.iter().map(|s| s.to_string()).collect()))
.collect();
precedence(&list, &deps)
}
#[test]
fn a_pack_comes_after_its_dependencies_and_the_list_orders_the_rest() {
assert_eq!(order(&["a", "b"], &[]).unwrap(), ["a", "b"]);
assert_eq!(
order(&["rust", "base"], &[("rust", &["base"])]).unwrap(),
["base", "rust"]
);
assert_eq!(
order(&["c", "b", "a"], &[("c", &["b"]), ("b", &["a"])]).unwrap(),
["a", "b", "c"]
);
assert_eq!(
order(&["x", "base", "rust"], &[("rust", &["base"])]).unwrap(),
["x", "base", "rust"]
);
assert_eq!(order(&["a"], &[("a", &["gone"])]).unwrap(), ["a"]);
let e = order(&["a", "b", "c"], &[("a", &["b"]), ("b", &["a"])])
.unwrap_err()
.to_string();
assert!(e.contains("the packs a, b form a cycle"), "{e}");
}
}