libp2prs_multiaddr/
onion_addr.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::fmt::Debug;
4
5/// Represents an Onion v3 address
6#[derive(Clone)]
7pub struct Onion3Addr<'a>(Cow<'a, [u8; 35]>, u16);
8
9impl<'a> Onion3Addr<'a> {
10    /// Return the hash of the public key as bytes
11    pub fn hash(&self) -> &[u8; 35] {
12        self.0.as_ref()
13    }
14
15    /// Return the port
16    pub fn port(&self) -> u16 {
17        self.1
18    }
19
20    /// Consume this instance and create an owned version containing the same address
21    pub fn acquire<'b>(self) -> Onion3Addr<'b> {
22        Onion3Addr(Cow::Owned(self.0.into_owned()), self.1)
23    }
24}
25
26impl PartialEq for Onion3Addr<'_> {
27    fn eq(&self, other: &Self) -> bool {
28        self.1 == other.1 && self.0[..] == other.0[..]
29    }
30}
31
32impl Eq for Onion3Addr<'_> {}
33
34impl From<([u8; 35], u16)> for Onion3Addr<'_> {
35    fn from(parts: ([u8; 35], u16)) -> Self {
36        Self(Cow::Owned(parts.0), parts.1)
37    }
38}
39
40impl<'a> From<(&'a [u8; 35], u16)> for Onion3Addr<'a> {
41    fn from(parts: (&'a [u8; 35], u16)) -> Self {
42        Self(Cow::Borrowed(parts.0), parts.1)
43    }
44}
45
46impl Debug for Onion3Addr<'_> {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
48        f.debug_tuple("Onion3Addr")
49            .field(&format!("{:02x?}", &self.0[..]))
50            .field(&self.1)
51            .finish()
52    }
53}