litep2p/types/
protocol.rs1use std::{
24 fmt::Display,
25 hash::{Hash, Hasher},
26 sync::Arc,
27};
28
29#[derive(Debug, Clone)]
31#[cfg_attr(feature = "fuzz", derive(serde::Serialize, serde::Deserialize))]
32pub enum ProtocolName {
33 #[cfg(not(feature = "fuzz"))]
34 Static(&'static str),
35 Allocated(Arc<str>),
36}
37
38#[cfg(not(feature = "fuzz"))]
39impl From<&'static str> for ProtocolName {
40 fn from(protocol: &'static str) -> Self {
41 ProtocolName::Static(protocol)
42 }
43}
44#[cfg(feature = "fuzz")]
45impl From<&'static str> for ProtocolName {
46 fn from(protocol: &'static str) -> Self {
47 ProtocolName::Allocated(Arc::from(protocol.to_string()))
48 }
49}
50
51impl Display for ProtocolName {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 match self {
54 #[cfg(not(feature = "fuzz"))]
55 Self::Static(protocol) => protocol.fmt(f),
56 Self::Allocated(protocol) => protocol.fmt(f),
57 }
58 }
59}
60
61impl From<String> for ProtocolName {
62 fn from(protocol: String) -> Self {
63 ProtocolName::Allocated(Arc::from(protocol))
64 }
65}
66
67impl From<Arc<str>> for ProtocolName {
68 fn from(protocol: Arc<str>) -> Self {
69 Self::Allocated(protocol)
70 }
71}
72
73impl std::ops::Deref for ProtocolName {
74 type Target = str;
75
76 fn deref(&self) -> &Self::Target {
77 match self {
78 #[cfg(not(feature = "fuzz"))]
79 Self::Static(protocol) => protocol,
80 Self::Allocated(protocol) => protocol,
81 }
82 }
83}
84
85impl Hash for ProtocolName {
86 fn hash<H: Hasher>(&self, state: &mut H) {
87 (self as &str).hash(state)
88 }
89}
90
91impl PartialEq for ProtocolName {
92 fn eq(&self, other: &Self) -> bool {
93 (self as &str) == (other as &str)
94 }
95}
96
97impl Eq for ProtocolName {}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102
103 #[test]
104 fn make_protocol() {
105 let protocol1 = ProtocolName::from(Arc::from(String::from("/protocol/1")));
106 let protocol2 = ProtocolName::from("/protocol/1");
107
108 assert_eq!(protocol1, protocol2);
109 }
110}