#![warn(bad_style)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(trivial_casts)]
#![warn(trivial_numeric_casts)]
#![warn(unused)]
#![warn(unused_extern_crates)]
#![warn(unused_import_braces)]
#![warn(unused_qualifications)]
#![warn(unused_results)]
#![cfg_attr(feature = "cargo-clippy", warn(if_not_else))]
#![cfg_attr(feature = "cargo-clippy", warn(invalid_upcast_comparisons))]
#![cfg_attr(feature = "cargo-clippy", warn(items_after_statements))]
#![cfg_attr(feature = "cargo-clippy", warn(mut_mut))]
#![cfg_attr(feature = "cargo-clippy", warn(never_loop))]
#![cfg_attr(feature = "cargo-clippy", warn(nonminimal_bool))]
#![cfg_attr(feature = "cargo-clippy", warn(option_map_unwrap_or))]
#![cfg_attr(feature = "cargo-clippy", warn(option_map_unwrap_or_else))]
#![cfg_attr(feature = "cargo-clippy", warn(option_unwrap_used))]
#![cfg_attr(feature = "cargo-clippy", warn(result_unwrap_used))]
#![cfg_attr(feature = "cargo-clippy", warn(used_underscore_binding))]
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::collections::hash_map::Entry;
use std::fmt;
use std::hash::Hash;
use std::iter::FromIterator;
#[derive(Clone)]
struct Dependency<T> {
num_prec: usize,
succ: HashSet<T>,
}
impl<T: Hash + Eq> Dependency<T> {
fn new() -> Dependency<T> {
Dependency {
num_prec: 0,
succ: HashSet::new(),
}
}
}
#[derive(Clone)]
pub struct TopologicalSort<T> {
top: HashMap<T, Dependency<T>>,
}
impl<T: Hash + Eq + Clone> TopologicalSort<T> {
#[inline]
pub fn new() -> TopologicalSort<T> {
TopologicalSort {
top: HashMap::new(),
}
}
#[inline]
pub fn len(&self) -> usize {
self.top.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.top.is_empty()
}
pub fn add_dependency<P, S>(&mut self, prec: P, succ: S)
where
P: Into<T>,
S: Into<T>,
{
self.add_dependency_impl(prec.into(), succ.into())
}
fn add_dependency_impl(&mut self, prec: T, succ: T) {
match self.top.entry(prec) {
Entry::Vacant(e) => {
let mut dep = Dependency::new();
let _ = dep.succ.insert(succ.clone());
let _ = e.insert(dep);
}
Entry::Occupied(e) => {
if !e.into_mut().succ.insert(succ.clone()) {
return;
}
}
}
match self.top.entry(succ) {
Entry::Vacant(e) => {
let mut dep = Dependency::new();
dep.num_prec += 1;
let _ = e.insert(dep);
}
Entry::Occupied(e) => {
e.into_mut().num_prec += 1;
}
}
}
pub fn add_link(&mut self, link: DependencyLink<T>) {
self.add_dependency(link.prec, link.succ)
}
pub fn insert<U>(&mut self, elt: U) -> bool
where
U: Into<T>,
{
match self.top.entry(elt.into()) {
Entry::Vacant(e) => {
let dep = Dependency::new();
let _ = e.insert(dep);
true
}
Entry::Occupied(_) => false,
}
}
pub fn pop(&mut self) -> Option<T> {
self.peek().map(T::clone).map(|key| {
let _ = self.remove(&key);
key
})
}
pub fn pop_all(&mut self) -> Vec<T> {
let keys = self.top
.iter()
.filter(|&(_, v)| v.num_prec == 0)
.map(|(k, _)| k.clone())
.collect::<Vec<_>>();
for k in &keys {
let _ = self.remove(k);
}
keys
}
pub fn peek(&self) -> Option<&T> {
self.top
.iter()
.filter(|&(_, v)| v.num_prec == 0)
.map(|(k, _)| k)
.next()
}
pub fn peek_all(&self) -> Vec<&T> {
self.top
.iter()
.filter(|&(_, v)| v.num_prec == 0)
.map(|(k, _)| k)
.collect::<Vec<_>>()
}
fn remove(&mut self, prec: &T) -> Option<Dependency<T>> {
let result = self.top.remove(prec);
if let Some(ref p) = result {
for s in &p.succ {
if let Some(y) = self.top.get_mut(s) {
y.num_prec -= 1;
}
}
}
result
}
}
impl<T: PartialOrd + Eq + Hash + Clone> FromIterator<T> for TopologicalSort<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> TopologicalSort<T> {
let mut top = TopologicalSort::new();
let mut seen = Vec::<T>::default();
for item in iter {
let _ = top.insert(item.clone());
for seen_item in seen.iter().cloned() {
match seen_item.partial_cmp(&item) {
Some(Ordering::Less) => {
top.add_dependency(seen_item, item.clone());
}
Some(Ordering::Greater) => {
top.add_dependency(item.clone(), seen_item);
}
_ => (),
}
}
seen.push(item);
}
top
}
}
#[derive(Copy, Clone, Debug)]
pub struct DependencyLink<T> {
pub prec: T,
pub succ: T,
}
impl<T> From<(T, T)> for DependencyLink<T> {
fn from(tuple: (T, T)) -> Self {
DependencyLink {
succ: tuple.0,
prec: tuple.1,
}
}
}
impl<T: Eq + Hash + Clone> FromIterator<DependencyLink<T>> for TopologicalSort<T> {
fn from_iter<I: IntoIterator<Item = DependencyLink<T>>>(iter: I) -> TopologicalSort<T> {
let mut top = TopologicalSort::new();
for link in iter {
top.add_link(link);
}
top
}
}
impl<T: Hash + Eq + Clone> Iterator for TopologicalSort<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.pop()
}
}
impl<T: fmt::Debug + Hash + Eq> fmt::Debug for Dependency<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "prec={}, succ={:?}", self.num_prec, self.succ)
}
}
impl<T: fmt::Debug + Hash + Eq + Clone> fmt::Debug for TopologicalSort<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.top)
}
}
#[cfg(test)]
mod test {
use super::TopologicalSort;
use std::iter::FromIterator;
#[test]
fn from_iter() {
let t = vec![4, 3, 3, 5, 7, 6, 8];
let mut ts = TopologicalSort::<i32>::from_iter(t);
assert_eq!(Some(3), ts.next());
assert_eq!(Some(4), ts.next());
assert_eq!(Some(5), ts.next());
assert_eq!(Some(6), ts.next());
assert_eq!(Some(7), ts.next());
assert_eq!(Some(8), ts.next());
assert_eq!(None, ts.next());
}
#[test]
fn iter() {
let mut ts = TopologicalSort::<i32>::new();
ts.add_dependency(1, 2);
ts.add_dependency(2, 3);
ts.add_dependency(3, 4);
assert_eq!(Some(1), ts.next());
assert_eq!(Some(2), ts.next());
assert_eq!(Some(3), ts.next());
assert_eq!(Some(4), ts.next());
assert_eq!(None, ts.next());
}
#[test]
fn pop_all() {
fn check(result: &[i32], ts: &mut TopologicalSort<i32>) {
let l = ts.len();
let mut v = ts.pop_all();
v.sort();
assert_eq!(result, &v[..]);
assert_eq!(l - result.len(), ts.len());
}
let mut ts = TopologicalSort::new();
ts.add_dependency(7, 11);
assert_eq!(2, ts.len());
ts.add_dependency(7, 8);
assert_eq!(3, ts.len());
ts.add_dependency(5, 11);
assert_eq!(4, ts.len());
ts.add_dependency(3, 8);
assert_eq!(5, ts.len());
ts.add_dependency(3, 10);
assert_eq!(6, ts.len());
ts.add_dependency(11, 2);
assert_eq!(7, ts.len());
ts.add_dependency(11, 9);
assert_eq!(8, ts.len());
ts.add_dependency(11, 10);
assert_eq!(8, ts.len());
ts.add_dependency(8, 9);
assert_eq!(8, ts.len());
check(&[3, 5, 7], &mut ts);
check(&[8, 11], &mut ts);
check(&[2, 9, 10], &mut ts);
check(&[], &mut ts);
}
#[test]
fn cyclic_deadlock() {
let mut ts = TopologicalSort::new();
ts.add_dependency("stone", "sharp");
ts.add_dependency("bucket", "hole");
ts.add_dependency("hole", "straw");
ts.add_dependency("straw", "axe");
ts.add_dependency("axe", "sharp");
ts.add_dependency("sharp", "water");
ts.add_dependency("water", "bucket");
assert_eq!(ts.pop(), Some("stone"));
assert!(ts.pop().is_none());
println!("{:?}", ts);
}
}