Skip to main content

justssh_wire/
name.rs

1//! The name of a global request, a channel request or a channel type, as bytes.
2
3use core::fmt;
4
5/// A request name or channel type exactly as sent, which need not be UTF-8. It compares equal
6/// to a `str` holding the same bytes, and shows as [`escape_ascii`](slice::escape_ascii) does.
7#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub struct Name(Vec<u8>);
9
10impl Name {
11    pub fn as_bytes(&self) -> &[u8] {
12        &self.0
13    }
14
15    pub fn into_bytes(self) -> Vec<u8> {
16        self.0
17    }
18
19    /// The name as text, if it is UTF-8.
20    pub fn to_str(&self) -> Option<&str> {
21        core::str::from_utf8(&self.0).ok()
22    }
23}
24
25impl From<Vec<u8>> for Name {
26    fn from(bytes: Vec<u8>) -> Self {
27        Name(bytes)
28    }
29}
30
31impl From<&[u8]> for Name {
32    fn from(bytes: &[u8]) -> Self {
33        Name(bytes.to_vec())
34    }
35}
36
37impl From<String> for Name {
38    fn from(s: String) -> Self {
39        Name(s.into_bytes())
40    }
41}
42
43impl From<&str> for Name {
44    fn from(s: &str) -> Self {
45        Name(s.as_bytes().to_vec())
46    }
47}
48
49impl AsRef<[u8]> for Name {
50    fn as_ref(&self) -> &[u8] {
51        &self.0
52    }
53}
54
55impl PartialEq<str> for Name {
56    fn eq(&self, other: &str) -> bool {
57        self.0 == other.as_bytes()
58    }
59}
60
61impl PartialEq<&str> for Name {
62    fn eq(&self, other: &&str) -> bool {
63        self.0 == other.as_bytes()
64    }
65}
66
67impl PartialEq<[u8]> for Name {
68    fn eq(&self, other: &[u8]) -> bool {
69        self.0 == other
70    }
71}
72
73impl PartialEq<Name> for str {
74    fn eq(&self, other: &Name) -> bool {
75        self.as_bytes() == other.0
76    }
77}
78
79impl PartialEq<Name> for &str {
80    fn eq(&self, other: &Name) -> bool {
81        self.as_bytes() == other.0
82    }
83}
84
85impl<const N: usize> PartialEq<[u8; N]> for Name {
86    fn eq(&self, other: &[u8; N]) -> bool {
87        self.0 == other
88    }
89}
90
91impl<const N: usize> PartialEq<&[u8; N]> for Name {
92    fn eq(&self, other: &&[u8; N]) -> bool {
93        self.0 == *other
94    }
95}
96
97impl PartialEq<String> for Name {
98    fn eq(&self, other: &String) -> bool {
99        self.0 == other.as_bytes()
100    }
101}
102
103impl PartialEq<Name> for String {
104    fn eq(&self, other: &Name) -> bool {
105        self.as_bytes() == other.0
106    }
107}
108
109impl core::borrow::Borrow<[u8]> for Name {
110    fn borrow(&self) -> &[u8] {
111        &self.0
112    }
113}
114
115impl fmt::Display for Name {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        f.pad(&self.0.escape_ascii().to_string())
118    }
119}
120
121impl fmt::Debug for Name {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        write!(f, "\"{}\"", self.0.escape_ascii())
124    }
125}