#![doc = include_str!("../README.md")]
use itertools::Itertools;
use std::{collections::HashMap, fmt::Debug, hash::Hash};
pub struct SortedHashMapDebugOutput<'a, K, V>(pub &'a HashMap<K, V>);
impl<'a, K, V> Debug for SortedHashMapDebugOutput<'a, K, V>
where
K: Ord + Debug + Eq + Hash,
V: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entries(self.0.keys().sorted().map(|k| (k, &self.0[k])))
.finish()
}
}
pub trait SortedOutputExt {
type Sorted<'a>
where
Self: 'a;
fn sorted_debug(&self) -> Self::Sorted<'_>;
}
impl<K, V> SortedOutputExt for HashMap<K, V> {
type Sorted<'a> = SortedHashMapDebugOutput<'a, K, V> where Self: 'a;
fn sorted_debug(&self) -> Self::Sorted<'_> {
SortedHashMapDebugOutput(self)
}
}
#[cfg(test)]
mod tests {
use std::collections::{BTreeMap, HashMap};
use super::SortedHashMapDebugOutput;
use quickcheck_macros::quickcheck;
#[quickcheck]
fn test_output_alphebatized(data: HashMap<isize, isize>) -> bool {
format!("{:?}", SortedHashMapDebugOutput(&data))
== format!(
"{:?}",
data.iter()
.map(|(&k, &v)| (k, v))
.collect::<BTreeMap<_, _>>()
)
}
}