1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#![doc = include_str!("../README.md")]
use itertools::Itertools;
use std::{collections::HashMap, fmt::Debug, hash::Hash};
pub struct SortedHashMapDebugOutput<'a, K, V>(&'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<_, _>>()
)
}
}