Skip to content

Commit

Permalink
Add borrow impl for Dname<Vec<u8>>
Browse files Browse the repository at this point in the history
This impl supports users of `domain` that may use `Dname` as keys in
standard library collections, who may want to query those collections
with non-owned `Dname`.

Include a doc comment testing that a collection of `Dname<Vec<u8>>` can
be queried with a `Dname<[u8]>`.
  • Loading branch information
iximeow committed Aug 24, 2023
1 parent 81e09de commit 8f6e37d
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/base/name/dname.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use super::traits::{ToDname, ToLabelIter};
use bytes::Bytes;
use core::ops::{Bound, RangeBounds};
use core::str::FromStr;
use core::{cmp, fmt, hash, str};
use core::{borrow, cmp, fmt, hash, str};
use octseq::builder::{EmptyBuilder, FreezeBuilder, FromBuilder, Truncate};
use octseq::octets::{Octets, OctetsFrom};
use octseq::parse::Parser;
Expand Down Expand Up @@ -835,6 +835,27 @@ impl<Octs: AsRef<[u8]> + ?Sized> fmt::Debug for Dname<Octs> {
}
}

//--- Borrow

/// Containers holding `Dname<Vec<u8>>` may be queried either by `Dname<Vec<u8>>` or borrowed
/// forms. This `Borrow` impl supports user code querying containers with compatible-but-different
/// types like the following example:
/// ```
/// use std::collections::HashMap;
///
/// use domain::base::Dname;
///
/// fn get_description(hash: &HashMap<Dname<Vec<u8>>, String>) -> Option<&str> {
/// let lookup_name: &Dname<[u8]> = Dname::from_slice(b"\x03www\x07example\x03com\0").unwrap();
/// hash.get(lookup_name).map(|x| x.as_ref())
/// }
/// ```
impl<Octs: AsRef<[u8]>> borrow::Borrow<Dname<[u8]>> for Dname<Octs> {
fn borrow(&self) -> &Dname<[u8]> {
self.for_slice()
}
}

//--- Serialize and Deserialize

#[cfg(feature = "serde")]
Expand Down

0 comments on commit 8f6e37d

Please sign in to comment.