1#![doc = include_str!("../README.md")]
2
3use itertools::Itertools;
4use std::{collections::HashMap, fmt::Debug, hash::Hash};
5
6pub struct SortedHashMapDebugOutput<'a, K, V>(pub &'a HashMap<K, V>);
15
16impl<'a, K, V> Debug for SortedHashMapDebugOutput<'a, K, V>
17where
18 K: Ord + Debug + Eq + Hash,
19 V: Debug,
20{
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 f.debug_map()
23 .entries(self.0.keys().sorted().map(|k| (k, &self.0[k])))
24 .finish()
25 }
26}
27
28pub trait SortedOutputExt {
33 type Sorted<'a>
35 where
36 Self: 'a;
37
38 fn sorted_debug(&self) -> Self::Sorted<'_>;
40}
41
42impl<K, V> SortedOutputExt for HashMap<K, V> {
43 type Sorted<'a> = SortedHashMapDebugOutput<'a, K, V> where Self: 'a;
44 fn sorted_debug(&self) -> Self::Sorted<'_> {
45 SortedHashMapDebugOutput(self)
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use std::collections::{BTreeMap, HashMap};
52
53 use super::SortedHashMapDebugOutput;
54 use quickcheck_macros::quickcheck;
55
56 #[quickcheck]
57 fn test_output_alphebatized(data: HashMap<isize, isize>) -> bool {
59 format!("{:?}", SortedHashMapDebugOutput(&data))
60 == format!(
61 "{:?}",
62 data.iter()
63 .map(|(&k, &v)| (k, v))
64 .collect::<BTreeMap<_, _>>()
65 )
66 }
67}