pingora_error/
immut_str.rs1use std::fmt;
16
17#[derive(Debug, PartialEq, Eq, Clone)]
20pub enum ImmutStr {
21 Static(&'static str),
22 Owned(Box<str>),
23}
24
25impl ImmutStr {
26 #[inline]
27 pub fn as_str(&self) -> &str {
28 match self {
29 ImmutStr::Static(s) => s,
30 ImmutStr::Owned(s) => s.as_ref(),
31 }
32 }
33
34 pub fn is_owned(&self) -> bool {
35 match self {
36 ImmutStr::Static(_) => false,
37 ImmutStr::Owned(_) => true,
38 }
39 }
40}
41
42impl fmt::Display for ImmutStr {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 write!(f, "{}", self.as_str())
45 }
46}
47
48impl From<&'static str> for ImmutStr {
49 fn from(s: &'static str) -> Self {
50 ImmutStr::Static(s)
51 }
52}
53
54impl From<String> for ImmutStr {
55 fn from(s: String) -> Self {
56 ImmutStr::Owned(s.into_boxed_str())
57 }
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
65 fn test_static_vs_owned() {
66 let s: ImmutStr = "test".into();
67 assert!(!s.is_owned());
68 let s: ImmutStr = "test".to_string().into();
69 assert!(s.is_owned());
70 }
71}