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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#[cfg(test)]
mod tests;

use crate::{owned_slice::OwnedSlice, util::range, IndexOutOfBounds, RangeOfSubset, SharedBytes};
use std::{
    borrow::{Borrow, Cow},
    fmt::{self, Debug, Display},
    io,
    net::ToSocketAddrs,
    ops::{Deref, Range, RangeBounds},
    sync::Arc,
};

#[derive(Clone)]
pub struct SharedStr(pub(crate) Flavour);

#[derive(Clone)]
pub(crate) enum Flavour {
    Static(&'static str),
    ArcVecSlice(OwnedSlice<Arc<Vec<u8>>, str>),
    ArcStringSlice(OwnedSlice<Arc<String>, str>),
}

impl SharedStr {
    #[inline]
    pub const fn new() -> Self {
        Self(Flavour::Static(""))
    }

    #[inline]
    pub const fn from_static(x: &'static str) -> Self {
        Self(Flavour::Static(x))
    }

    #[inline]
    pub fn from_string(x: String) -> Self {
        Self::from_arc_string(Arc::new(x))
    }

    #[inline]
    pub fn from_arc_string(x: Arc<String>) -> Self {
        Self(Flavour::ArcStringSlice(OwnedSlice::new(x).unwrap()))
    }

    pub fn from_utf8(bytes: SharedBytes) -> Result<Self, SharedBytes> {
        use crate::shared_bytes::Flavour::*;
        let flavour = match bytes.0 {
            Static(b) => match std::str::from_utf8(b) {
                Ok(string) => Flavour::Static(string),
                Err(_) => return Err(bytes),
            },
            ArcVecSlice(x) => Flavour::ArcVecSlice(
                x.try_map_output()
                    .map_err(|x| SharedBytes(ArcVecSlice(x)))?,
            ),
            ArcStringSlice(x) => Flavour::ArcStringSlice(
                x.try_map_output()
                    .map_err(|x| SharedBytes(ArcStringSlice(x)))?,
            ),
        };
        Ok(Self(flavour))
    }

    pub fn into_string(self) -> String {
        self.into_static_cow().into_owned()
    }

    fn into_static_cow(self) -> Cow<'static, str> {
        match self.0 {
            Flavour::Static(x) => Cow::Borrowed(x),
            Flavour::ArcVecSlice(x) => Cow::Owned(
                x.into_unwrapped(|vec| String::from_utf8(vec).unwrap(), ToOwned::to_owned),
            ),
            Flavour::ArcStringSlice(x) => {
                Cow::Owned(x.into_unwrapped(Into::into, ToOwned::to_owned))
            }
        }
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        self.as_slice()
    }

    #[inline]
    pub fn as_slice(&self) -> &str {
        match &self.0 {
            Flavour::Static(x) => x,
            Flavour::ArcVecSlice(x) => x,
            Flavour::ArcStringSlice(x) => x,
        }
    }

    pub fn as_static(&self) -> Option<&'static str> {
        match &self.0 {
            Flavour::Static(x) => Some(x),
            _ => None,
        }
    }

    pub fn len(&self) -> usize {
        self.as_slice().len()
    }

    pub fn is_empty(&self) -> bool {
        self.as_slice().is_empty()
    }

    pub fn clear(&mut self) {
        *self = Self::new()
    }

    pub fn truncate(&mut self, at: usize) {
        self.try_slice_mut(..at)
            .unwrap_or_else(|_| panic!("truncate index '{at}' should be <= len '{}'", self.len()))
    }

    #[must_use = "consider fn truncate if you don't need the other half"]
    pub fn split_off(&mut self, at: usize) -> Self {
        self.try_split_off(at)
            .unwrap_or_else(|| panic!("split index '{at}' should be <= len '{}'", self.len()))
    }

    // may be promoted to a pub fn in the future
    fn try_split_off(&mut self, at: usize) -> Option<Self> {
        self.as_slice().get(at..)?; // ensure `at` is not out of bounds
        let mut split = self.clone();
        split.slice_mut(at..);
        self.slice_mut(..at);
        Some(split)
    }

    pub fn range_of_subset(&self, subset: &str) -> Range<usize> {
        RangeOfSubset::range_of_subset(self.as_slice(), subset)
    }

    pub fn slice_cloned<R: RangeBounds<usize>>(&self, r: R) -> Self {
        self.non_generic_slice_cloned(self.slice_range_from_bounds(r))
    }

    fn non_generic_slice_cloned(&self, range: Range<usize>) -> Self {
        self.non_generic_try_slice_cloned(range.clone())
            .unwrap_or_else(|_| self.out_of_bounds_panic(range))
    }

    pub fn try_slice_cloned<R: RangeBounds<usize>>(&self, r: R) -> Result<Self, IndexOutOfBounds> {
        self.non_generic_try_slice_cloned(self.slice_range_from_bounds(r))
    }

    fn non_generic_try_slice_cloned(&self, range: Range<usize>) -> Result<Self, IndexOutOfBounds> {
        if self.as_slice().get(range.clone()).is_none() {
            return Err(IndexOutOfBounds::new());
        }
        Ok(self.clone().slice_into(range))
    }

    pub fn slice_into<R: RangeBounds<usize>>(self, r: R) -> Self {
        let range = self.slice_range_from_bounds(r);
        self.non_generic_slice_into(range)
    }

    fn non_generic_slice_into(self, range: Range<usize>) -> Self {
        self.non_generic_try_slice_into(range.clone())
            .unwrap_or_else(|this| this.out_of_bounds_panic(range))
    }

    pub fn try_slice_into<R: RangeBounds<usize>>(self, r: R) -> Result<Self, Self> {
        let range = self.slice_range_from_bounds(r);
        self.non_generic_try_slice_into(range)
    }

    fn non_generic_try_slice_into(mut self, range: Range<usize>) -> Result<Self, Self> {
        match self.internal_try_slice_mut(range) {
            Ok(()) => Ok(self),
            Err(()) => Err(self),
        }
    }

    pub fn slice_mut<R: RangeBounds<usize>>(&mut self, r: R) {
        self.non_generic_slice_mut(self.slice_range_from_bounds(r))
    }

    fn non_generic_slice_mut(&mut self, range: Range<usize>) {
        self.internal_try_slice_mut(range.clone())
            .unwrap_or_else(|()| self.out_of_bounds_panic(range))
    }

    pub fn try_slice_mut<R: RangeBounds<usize>>(&mut self, r: R) -> Result<(), IndexOutOfBounds> {
        self.non_generic_try_slice_mut(self.slice_range_from_bounds(r))
    }

    fn non_generic_try_slice_mut(&mut self, range: Range<usize>) -> Result<(), IndexOutOfBounds> {
        self.internal_try_slice_mut(range)
            .map_err(|()| IndexOutOfBounds::new())
    }

    fn slice_range_from_bounds<R: RangeBounds<usize>>(&self, r: R) -> Range<usize> {
        range::from_slice_bounds(r, || self.len())
    }

    fn out_of_bounds_panic<R: RangeBounds<usize> + Debug, T>(&self, range: R) -> T {
        let length = self.len();
        panic!("slice range {range:?} is out of bounds for length {length}")
    }

    #[must_use = "`internal_try_slice_mut` may fail to mutate `self`"]
    fn internal_try_slice_mut(&mut self, range: Range<usize>) -> Result<(), ()> {
        match &mut self.0 {
            Flavour::Static(old) => match old.get(range) {
                None => Err(()),
                Some(new) => {
                    *old = new;
                    Ok(())
                }
            },
            Flavour::ArcVecSlice(x) => x.try_slice_mut(range),
            Flavour::ArcStringSlice(x) => x.try_slice_mut(range),
        }
    }
}

impl AsRef<[u8]> for SharedStr {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_slice().as_bytes()
    }
}

impl AsRef<str> for SharedStr {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_slice()
    }
}

impl Borrow<str> for SharedStr {
    #[inline]
    fn borrow(&self) -> &str {
        self.as_slice()
    }
}

impl Debug for SharedStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(self.as_str(), f)
    }
}

impl Display for SharedStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(self.as_str(), f)
    }
}

impl Default for SharedStr {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Deref for SharedStr {
    type Target = str;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl Eq for SharedStr {}

impl PartialEq for SharedStr {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl<Other: ?Sized> PartialEq<&Other> for SharedStr
where
    Self: PartialEq<Other>,
{
    #[inline]
    fn eq(&self, other: &&Other) -> bool {
        self == *other
    }
}

impl PartialEq<str> for SharedStr {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        self.as_slice() == other
    }
}

impl PartialEq<String> for SharedStr {
    #[inline]
    fn eq(&self, other: &String) -> bool {
        self.as_slice() == other.as_str()
    }
}

impl std::hash::Hash for SharedStr {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state)
    }
}

impl From<&'static str> for SharedStr {
    #[inline]
    fn from(x: &'static str) -> Self {
        Self::from_static(x)
    }
}

impl From<String> for SharedStr {
    #[inline]
    fn from(x: String) -> Self {
        Self::from_string(x)
    }
}

impl From<Arc<String>> for SharedStr {
    #[inline]
    fn from(x: Arc<String>) -> Self {
        Self::from_arc_string(x)
    }
}

impl From<char> for SharedStr {
    #[inline]
    fn from(x: char) -> Self {
        Self::from_string(x.into())
    }
}

impl From<SharedStr> for String {
    fn from(x: SharedStr) -> Self {
        x.into_string()
    }
}

impl FromIterator<char> for SharedStr {
    #[inline]
    fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
        Self::from_string(iter.into_iter().collect())
    }
}

impl<'a> FromIterator<&'a str> for SharedStr {
    #[inline]
    fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
        Self::from_string(iter.into_iter().collect())
    }
}

impl FromIterator<String> for SharedStr {
    #[inline]
    fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
        Self::from_string(iter.into_iter().collect())
    }
}

impl ToSocketAddrs for SharedStr {
    type Iter = <str as ToSocketAddrs>::Iter;

    #[inline]
    fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
        self.as_str().to_socket_addrs()
    }
}