use iddqd::{
Comparable, Equivalent, IdOrdItem, IdOrdMap, id_ord_map::Entry, id_upcast,
};
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq, Eq)]
struct MyStruct {
a: String,
b: usize,
c: PathBuf,
d: Vec<usize>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct MyKey<'a> {
b: usize,
c: &'a Path,
d: &'a [usize],
}
impl IdOrdItem for MyStruct {
type Key<'a> = MyKey<'a>;
fn key(&self) -> Self::Key<'_> {
MyKey { b: self.b, c: &self.c, d: &self.d }
}
id_upcast!();
}
fn main() {
let mut map = IdOrdMap::new();
let item = MyStruct {
a: "example".to_owned(),
b: 20,
c: PathBuf::from("/"),
d: Vec::new(),
};
map.insert_unique(item.clone()).unwrap();
map.insert_unique(MyStruct {
a: "something-else".to_owned(),
b: 20,
c: PathBuf::from("/"),
d: Vec::new(),
})
.unwrap_err();
let item2 = MyStruct {
a: "example".to_owned(),
b: 10,
c: PathBuf::from("/"),
d: Vec::new(),
};
map.insert_unique(item2.clone()).unwrap();
assert_eq!(
map.get(&MyKey { b: 20, c: Path::new("/"), d: &[] }),
Some(&item)
);
{
let mut item =
map.get_mut(&MyKey { b: 20, c: Path::new("/"), d: &[] }).unwrap();
item.a = "changed".to_owned();
}
for item in map.iter() {
println!("{item:?}");
}
let item3 = MyStruct {
a: "example".to_owned(),
b: 20,
c: PathBuf::from("/"),
d: vec![1, 2, 3],
};
for item in [item, item2, item3.clone()] {
let entry = map.entry(item.key());
match entry {
Entry::Occupied(entry) => {
let item = entry.get();
println!("occupied: {item:?}");
}
Entry::Vacant(entry) => {
let item_ref = entry.insert_ref(item);
println!("inserted: {item_ref:?}");
}
}
}
struct MyKeyOwned {
b: usize,
c: PathBuf,
d: Vec<usize>,
}
impl Equivalent<MyKey<'_>> for MyKeyOwned {
fn equivalent(&self, other: &MyKey<'_>) -> bool {
self.b == other.b && self.c == other.c && self.d == other.d
}
}
impl Comparable<MyKey<'_>> for MyKeyOwned {
fn compare(&self, other: &MyKey<'_>) -> std::cmp::Ordering {
self.b
.cmp(&other.b)
.then_with(|| self.c.as_path().cmp(other.c))
.then_with(|| self.d.as_slice().cmp(other.d))
}
}
let key = MyKeyOwned { b: 20, c: PathBuf::from("/"), d: vec![1, 2, 3] };
assert_eq!(map.get(&key), Some(&item3));
}