debug_map_sorted/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use itertools::Itertools;
4use std::{collections::HashMap, fmt::Debug, hash::Hash};
5
6/// A wrapper for [`HashMap`] which sorts itself for `Debug` output
7///
8/// You probably want to use a [`BTreeMap`](std::collections::BTreeMap) if you want your
9/// data to be sorted, but if outputting is rare (or is only included transiently for
10/// debugging purposes), it may make more sense to use this trait instead of changing the
11/// underlying type.
12///
13/// Also see [`SortedOutputExt`] for a syntactically cleaner method of constructing this type.
14pub 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
28/// An extension trait for easier production of [`SortedHashMapDebugOutput`] values
29///
30/// This trait is generic because it may be extended in future versions of the crate, but for
31/// now it only applies to [`HashMap`].
32pub trait SortedOutputExt {
33    /// The target type
34    type Sorted<'a>
35    where
36        Self: 'a;
37
38    /// A method which borrows `self` as the given target
39    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    /// Test by comparing the output against the debug of a [`BTreeMap`]
58    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}