Skip to content

Instantly share code, notes, and snippets.

@nicolashahn
Created December 8, 2019 22:19
Show Gist options
  • Save nicolashahn/60558091785d211d5fafb2fb1543a154 to your computer and use it in GitHub Desktop.
Save nicolashahn/60558091785d211d5fafb2fb1543a154 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use KeyDiff::{Added, Changed, Removed};
#[derive(Debug)]
enum KeyDiff<V: PartialEq> {
Added(V),
Removed(V),
Changed(V, V),
}
fn ddiff<K: Hash + Eq + Clone, V: PartialEq + Clone>(
a: &HashMap<K, V>,
b: &HashMap<K, V>,
) -> HashMap<K, KeyDiff<V>> {
let mut d = HashMap::new();
let mut keys = vec![];
for k in a.keys() {
keys.push(k.clone())
}
for k in b.keys() {
keys.push(k.clone())
}
for k in keys {
match (a.get(&k), b.get(&k)) {
(Some(av), Some(bv)) => {
if av != bv {
d.insert(k, Changed(av.clone(), bv.clone()));
}
}
(None, Some(bv)) => {
d.insert(k, Added(bv.clone()));
}
(Some(av), None) => {
d.insert(k, Removed(av.clone()));
}
(None, None) => {}
}
}
d
}
fn pprint_diff<K: Hash + Eq + Clone + Debug, V: PartialEq + Clone + Debug>(
a: &HashMap<K, V>,
b: &HashMap<K, V>,
) {
let d = ddiff(a, b);
println!("{{");
for (k, v) in a {
if d.get(k).is_none() {
println!(" {:?}: {:?},", k, v);
}
}
for (k, v) in d {
match v {
Changed(av, bv) => {
println!(" ~ {:?}: {:?} -> {:?},", k, av, bv);
}
Added(bv) => {
println!(" + {:?}: {:?},", k, bv);
}
Removed(av) => {
println!(" - {:?}: {:?},", k, av);
}
}
}
println!("}}");
}
fn main() {
let mut a = HashMap::new();
a.insert("a", 1);
a.insert("b", 2);
a.insert("c", 3);
let mut b = HashMap::new();
b.insert("a", 1);
b.insert("b", 3);
b.insert("d", 4);
pprint_diff(&a, &b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment