From 8f6e37d63dfd427154557934f9e088ef22d52777 Mon Sep 17 00:00:00 2001 From: iximeow Date: Tue, 22 Aug 2023 23:04:56 -0700 Subject: [PATCH] Add borrow impl for Dname> 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>` can be queried with a `Dname<[u8]>`. --- src/base/name/dname.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/base/name/dname.rs b/src/base/name/dname.rs index c2c4ddef2..58747ba20 100644 --- a/src/base/name/dname.rs +++ b/src/base/name/dname.rs @@ -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; @@ -835,6 +835,27 @@ impl + ?Sized> fmt::Debug for Dname { } } +//--- Borrow + +/// Containers holding `Dname>` may be queried either by `Dname>` 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>, 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> borrow::Borrow> for Dname { + fn borrow(&self) -> &Dname<[u8]> { + self.for_slice() + } +} + //--- Serialize and Deserialize #[cfg(feature = "serde")]