pingora_error/
immut_str.rs

1// Copyright 2024 Cloudflare, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16
17/// A data struct that holds either immutable string or reference to static str.
18/// Compared to String or `Box<str>`, it avoids memory allocation on static str.
19#[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}