1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use crate::MessageConformance;
use std::sync::Arc;

/// Helper for holding either an owned or borrowed string,
/// and where the slice method is aware of that borrowing,
/// allowing for efficient copying and slicing without
/// making extraneous additional copies
pub enum SharedString<'a> {
    Owned(Arc<String>),
    Borrowed(&'a str),
    Sliced {
        other: Arc<String>,
        range: std::ops::Range<usize>,
    },
}

impl<'a> std::cmp::PartialEq<Self> for SharedString<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.as_str().eq(other.as_str())
    }
}

impl<'a> std::cmp::PartialEq<&str> for SharedString<'a> {
    fn eq(&self, other: &&str) -> bool {
        self.as_str().eq(*other)
    }
}

impl<'a> std::fmt::Display for SharedString<'a> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        let str = self.as_str();
        fmt.write_str(str)
    }
}

impl<'a> std::fmt::Debug for SharedString<'a> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        let str = self.as_str();
        write!(fmt, "{str:?}")
    }
}

impl<'a> std::ops::Deref for SharedString<'a> {
    type Target = str;
    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl<'a> std::ops::Index<usize> for SharedString<'a> {
    type Output = u8;
    fn index(&self, index: usize) -> &u8 {
        &self.as_str().as_bytes()[index]
    }
}

impl<'a> Clone for SharedString<'a> {
    fn clone(&self) -> Self {
        match self {
            Self::Owned(s) => Self::Sliced {
                other: Arc::clone(s),
                range: 0..s.len(),
            },
            Self::Borrowed(s) => Self::Borrowed(s),
            Self::Sliced { other, range } => Self::Sliced {
                other: Arc::clone(other),
                range: range.clone(),
            },
        }
    }
}

impl<'a> SharedString<'a> {
    pub fn slice(&self, slice_range: std::ops::Range<usize>) -> Self {
        self.assert_slice(slice_range.clone());
        match self {
            Self::Owned(s) => Self::Sliced {
                other: Arc::clone(s),
                range: slice_range,
            },
            Self::Borrowed(s) => Self::Borrowed(s.get(slice_range).unwrap()),
            Self::Sliced { other, range } => {
                let len = slice_range.end - slice_range.start;
                Self::Sliced {
                    other: Arc::clone(other),
                    range: range.start + slice_range.start..range.start + slice_range.start + len,
                }
            }
        }
    }

    fn assert_slice(&self, slice_range: std::ops::Range<usize>) {
        if self.as_str().get(slice_range.clone()).is_none() {
            panic!("slice range {slice_range:?} is invalid for {self:?}");
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            Self::Owned(s) => s.as_str(),
            Self::Borrowed(s) => s,
            Self::Sliced { other, range } => other.as_str().get(range.clone()).unwrap(),
        }
    }

    pub fn len(&self) -> usize {
        match self {
            Self::Owned(s) => s.len(),
            Self::Borrowed(s) => s.len(),
            Self::Sliced { range, .. } => range.len(),
        }
    }
}

impl<'a> From<String> for SharedString<'a> {
    fn from(s: String) -> Self {
        Self::Owned(Arc::new(s))
    }
}

impl<'a> From<&'a str> for SharedString<'a> {
    fn from(s: &'a str) -> Self {
        Self::Borrowed(s)
    }
}

impl<'a> TryFrom<&'a [u8]> for SharedString<'a> {
    type Error = std::str::Utf8Error;
    fn try_from(s: &'a [u8]) -> Result<Self, Self::Error> {
        let s = std::str::from_utf8(s)?;
        Ok(Self::Borrowed(s))
    }
}

pub trait IntoSharedString<'a> {
    fn into_shared_string(self) -> (SharedString<'a>, MessageConformance);
}

impl<'a> IntoSharedString<'a> for SharedString<'a> {
    fn into_shared_string(self) -> (SharedString<'a>, MessageConformance) {
        (self, MessageConformance::default())
    }
}

impl<'a> IntoSharedString<'a> for String {
    fn into_shared_string(self) -> (SharedString<'a>, MessageConformance) {
        (
            SharedString::Owned(Arc::new(self)),
            MessageConformance::default(),
        )
    }
}

impl<'a> IntoSharedString<'a> for &'a str {
    fn into_shared_string(self) -> (SharedString<'a>, MessageConformance) {
        (SharedString::Borrowed(self), MessageConformance::default())
    }
}

impl<'a> IntoSharedString<'a> for &'a [u8] {
    fn into_shared_string(self) -> (SharedString<'a>, MessageConformance) {
        match std::str::from_utf8(self) {
            Ok(s) => (SharedString::Borrowed(s), MessageConformance::default()),
            Err(_) => (
                SharedString::Owned(Arc::new(String::from_utf8_lossy(self).to_string())),
                MessageConformance::NEEDS_TRANSFER_ENCODING,
            ),
        }
    }
}