From c895cb100927eb3c217406ec58edf250ad7e566c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Sch=C3=A4fer?= Date: Mon, 15 Apr 2024 17:09:49 +0200 Subject: [PATCH] jid: implement Borrow on FullJid and BareJid This allows to use them interchangably when looking up keys in hash sets and dicts. --- jid/src/lib.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/jid/src/lib.rs b/jid/src/lib.rs index fde640a..e687080 100644 --- a/jid/src/lib.rs +++ b/jid/src/lib.rs @@ -31,7 +31,7 @@ //! mixing left-to-write and right-to-left characters use core::num::NonZeroU16; -use std::borrow::Cow; +use std::borrow::{Borrow, Cow}; use std::fmt; use std::ops::Deref; use std::str::FromStr; @@ -482,6 +482,18 @@ impl Deref for BareJid { } } +impl Borrow for FullJid { + fn borrow(&self) -> &Jid { + &self.inner + } +} + +impl Borrow for BareJid { + fn borrow(&self) -> &Jid { + &self.inner + } +} + impl fmt::Debug for FullJid { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_tuple("FullJid").field(&self.inner).finish() @@ -826,7 +838,7 @@ impl From for Node { mod tests { use super::*; - use std::collections::HashMap; + use std::collections::{HashMap, HashSet}; macro_rules! assert_size ( ($t:ty, $sz:expr) => ( @@ -1137,4 +1149,46 @@ mod tests { other => panic!("unexpected result: {:?}", other), }; } + + #[test] + fn lookup_jid_by_full_jid() { + let mut map: HashSet = HashSet::new(); + let jid1 = Jid::new("foo@bar").unwrap(); + let jid2 = Jid::new("foo@bar/baz").unwrap(); + let jid3 = FullJid::new("foo@bar/baz").unwrap(); + + map.insert(jid1); + assert!(!map.contains(&jid2)); + assert!(!map.contains(&jid3)); + map.insert(jid2); + assert!(map.contains(&jid3)); + } + + #[test] + fn lookup_full_jid_by_jid() { + let mut map: HashSet = HashSet::new(); + let jid1 = FullJid::new("foo@bar/baz").unwrap(); + let jid2 = FullJid::new("foo@bar/fnord").unwrap(); + let jid3 = Jid::new("foo@bar/fnord").unwrap(); + + map.insert(jid1); + assert!(!map.contains(&jid2)); + assert!(!map.contains(&jid3)); + map.insert(jid2); + assert!(map.contains(&jid3)); + } + + #[test] + fn lookup_bare_jid_by_jid() { + let mut map: HashSet = HashSet::new(); + let jid1 = BareJid::new("foo@bar").unwrap(); + let jid2 = BareJid::new("foo@baz").unwrap(); + let jid3 = Jid::new("foo@baz").unwrap(); + + map.insert(jid1); + assert!(!map.contains(&jid2)); + assert!(!map.contains(&jid3)); + map.insert(jid2); + assert!(map.contains(&jid3)); + } }