litep2p/types/
protocol.rs

1// Copyright 2023 litep2p developers
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21//! Protocol name.
22
23use std::{
24    fmt::Display,
25    hash::{Hash, Hasher},
26    sync::Arc,
27};
28
29/// Protocol name.
30#[derive(Debug, Clone)]
31pub enum ProtocolName {
32    Static(&'static str),
33    Allocated(Arc<str>),
34}
35
36impl From<&'static str> for ProtocolName {
37    fn from(protocol: &'static str) -> Self {
38        ProtocolName::Static(protocol)
39    }
40}
41
42impl Display for ProtocolName {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            Self::Static(protocol) => protocol.fmt(f),
46            Self::Allocated(protocol) => protocol.fmt(f),
47        }
48    }
49}
50
51impl From<String> for ProtocolName {
52    fn from(protocol: String) -> Self {
53        ProtocolName::Allocated(Arc::from(protocol))
54    }
55}
56
57impl From<Arc<str>> for ProtocolName {
58    fn from(protocol: Arc<str>) -> Self {
59        Self::Allocated(protocol)
60    }
61}
62
63impl std::ops::Deref for ProtocolName {
64    type Target = str;
65
66    fn deref(&self) -> &Self::Target {
67        match self {
68            Self::Static(protocol) => protocol,
69            Self::Allocated(protocol) => protocol,
70        }
71    }
72}
73
74impl Hash for ProtocolName {
75    fn hash<H: Hasher>(&self, state: &mut H) {
76        (self as &str).hash(state)
77    }
78}
79
80impl PartialEq for ProtocolName {
81    fn eq(&self, other: &Self) -> bool {
82        (self as &str) == (other as &str)
83    }
84}
85
86impl Eq for ProtocolName {}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    #[test]
93    fn make_protocol() {
94        let protocol1 = ProtocolName::from(Arc::from(String::from("/protocol/1")));
95        let protocol2 = ProtocolName::from("/protocol/1");
96
97        assert_eq!(protocol1, protocol2);
98    }
99}