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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
#![cfg_attr(not(doctest), doc = include_str!("../README.md"))]

use bytes::{Bytes, BytesMut};
use simdutf8::basic::{from_utf8, Utf8Error};
use std::{
    borrow::{Borrow, Cow},
    cmp::Ordering,
    convert::Infallible,
    fmt, hash, iter,
    ops::Deref,
    str::FromStr,
    sync::Arc,
};

/// `FastStr` is a string type that try to avoid the cost of clone.
#[derive(Clone)]
pub struct FastStr(Repr);

#[cfg(all(test, target_pointer_width = "64"))]
mod size_asserts {
    static_assertions::assert_eq_size!(super::FastStr, [u8; 40]); // 40 bytes
}

impl FastStr {
    /// Create a new `FastStr` from any type `T` that can be converted to a string slice
    /// (e.g., `String`, `&str`, `Arc<String>`, `Arc<str>`).
    ///
    /// For small strings (up to 24 bytes), this avoids heap allocation, and copies on stack.
    #[inline]
    pub fn new<T>(text: T) -> Self
    where
        T: AsRef<str>,
    {
        Self(Repr::new(text))
    }

    /// Create a new inline `FastStr` (up to 24 bytes long) from a string slice `s`.
    ///
    /// This constructor panics if the length of `s` is greater than 24.
    ///
    /// Note: the inline length is not guaranteed.
    #[inline]
    #[doc(hidden)]
    #[deprecated(
        since = "0.2.13",
        note = "The inline threshold is not stable. Please use `FastStr::new()` instead."
    )]
    pub fn new_inline(s: &str) -> Self {
        Self(Repr::new_inline(s))
    }

    /// Create a new `FastStr` from a byte slice `v`, returning a
    /// `Result<FastStr, Utf8Error>` if the bytes are not valid UTF-8.
    #[inline]
    pub fn new_u8_slice(v: &[u8]) -> Result<Self, Utf8Error> {
        let s = from_utf8(v)?;
        Ok(Self::new(s))
    }

    /// Create a new `FastStr` from a byte slice `v`. This is an unsafe method because
    /// the caller must ensure that the bytes passed to it are valid UTF-8.
    ///
    /// # Safety
    ///
    /// `v` must be valid UTF-8.
    #[inline]
    pub unsafe fn new_u8_slice_unchecked(v: &[u8]) -> Self {
        let s = unsafe { std::str::from_utf8_unchecked(v) };
        Self::new(s)
    }

    /// Create an empty `FastStr`.
    #[inline]
    pub const fn empty() -> Self {
        Self(Repr::empty())
    }

    /// Create a new `FastStr` from an `Arc<str>`.
    #[inline]
    pub fn from_arc_str(s: Arc<str>) -> Self {
        Self(Repr::from_arc_str(s))
    }

    /// Create a new `FastStr` from a `String`.
    #[inline]
    pub fn from_string(s: String) -> Self {
        Self(Repr::from_string(s))
    }

    /// Create a new `FastStr` from an `Arc<String>`.
    #[inline]
    pub fn from_arc_string(s: Arc<String>) -> Self {
        Self(Repr::from_arc_string(s))
    }

    /// Create a new `FastStr` from a `BytesMut` object, returning a
    /// `Result<FastStr, Utf8Error>` if the bytes are not valid UTF-8.
    #[inline]
    pub fn from_bytes(b: Bytes) -> Result<Self, Utf8Error> {
        from_utf8(&b)?;
        // Safety: we have checked b is utf-8 valid
        Ok(unsafe { Self::from_bytes_unchecked(b) })
    }

    /// Create a new `FastStr` from a `Bytes` object. This is an unsafe method
    /// because the caller must ensure that the bytes passed to it are valid UTF-8.
    ///
    /// # Safety
    ///
    /// `b` must be valid UTF-8.
    #[inline]
    pub unsafe fn from_bytes_unchecked(b: Bytes) -> Self {
        Self(Repr::from_bytes_unchecked(b))
    }

    /// Create a new `FastStr` from a `BytesMut` object, returning a
    /// `Result<FastStr, Utf8Error>` if the bytes are not valid UTF-8.
    #[inline]
    pub fn from_bytes_mut(b: BytesMut) -> Result<Self, Utf8Error> {
        from_utf8(&b)?;
        // Safety: we have checked b is utf-8 valid
        Ok(unsafe { Self::from_bytes_mut_unchecked(b) })
    }

    /// Create a new `FastStr` from a `BytesMut` object. This is an unsafe method
    /// because the caller must ensure that the bytes passed to it are valid UTF-8.
    ///
    /// # Safety
    ///
    /// `b` must be valid UTF-8.
    #[inline]
    pub unsafe fn from_bytes_mut_unchecked(b: BytesMut) -> Self {
        let v = b.freeze();
        Self::from_bytes_unchecked(v)
    }

    /// Create a new `FastStr` from a static string slice.
    #[inline]
    pub const fn from_static_str(s: &'static str) -> Self {
        Self(Repr::StaticStr(s))
    }

    /// Create a new `FastStr` from a `Vec<u8>`, returning a
    /// `Result<FastStr, Utf8Error>` if the bytes are not valid UTF-8.
    #[inline]
    pub fn from_vec_u8(v: Vec<u8>) -> Result<Self, Utf8Error> {
        from_utf8(&v)?;
        // Safety: we have checked b is utf-8 valid
        Ok(unsafe { Self::from_vec_u8_unchecked(v) })
    }

    /// Create a new `FastStr` from a `Vec<u8>`. This is an unsafe method because
    /// the caller must ensure that the bytes passed to it are valid UTF-8.
    ///
    /// # Safety
    ///
    /// `v` must be valid UTF-8.
    #[inline]
    pub unsafe fn from_vec_u8_unchecked(v: Vec<u8>) -> Self {
        Self::from_bytes_unchecked(v.into())
    }

    /// Create a new `FastStr` from a byte slice `v`, returning a
    /// `Result<FastStr, Utf8Error>` if the bytes are not valid UTF-8.
    #[deprecated(
        since = "0.2.13",
        note = "This method is not really zero-cost. Use `new_u8_slice` instead."
    )]
    #[inline]
    pub fn from_u8_slice(v: &[u8]) -> Result<Self, Utf8Error> {
        Self::new_u8_slice(v)
    }

    /// Create a new `FastStr` from a byte slice `v`. This is an unsafe method because
    /// the caller must ensure that the bytes passed to it are valid UTF-8.
    ///
    /// # Safety
    ///
    /// `v` must be valid UTF-8.
    #[deprecated(
        since = "0.2.13",
        note = "This method is not really zero-cost. Use `new_u8_slice_unchecked` instead."
    )]
    #[inline]
    pub unsafe fn from_u8_slice_unchecked(v: &[u8]) -> Self {
        Self::new_u8_slice_unchecked(v)
    }
}

impl FastStr {
    /// Return the `FastStr` as a string slice.
    #[inline(always)]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Consumes and converts the `FastStr` into a `Bytes` object.
    #[inline(always)]
    pub fn into_bytes(self) -> Bytes {
        self.0.into_bytes()
    }

    /// Return the `FastStr` length.
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Return `true` if the `FastStr` is empty.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Return a new `FastStr` that represents a subset of the current string.
    #[inline(always)]
    pub fn slice_ref(&self, subset: &str) -> Self {
        Self(self.0.slice_ref(subset.as_bytes()))
    }

    /// Return a new `FastStr` starting at index `start` and ending at index `end`. `[start..end)`
    ///
    /// # Safety
    ///
    /// The caller must guarantee that the string between `start` and `end` is valid utf-8.
    #[inline(always)]
    pub unsafe fn index(&self, start: usize, end: usize) -> Self {
        Self(self.0.slice_ref(&self.as_bytes()[start..end]))
    }

    /// Consumes and converts the `FastStr` into a `String` at best effort.
    #[deprecated(
        since = "0.2.13",
        note = "This method does not really express the `into` semantic. Use `to_string` instead."
    )]
    #[inline(always)]
    pub fn into_string(self) -> String {
        #[allow(deprecated)]
        self.0.into_string()
    }

    /// If the inner repr of FastStr is a Bytes, then it will be deep cloned and returned as a new FastStr.
    /// Otherwise, it will return a new FastStr with the same repr which has no cost.
    ///
    /// This is used to free the original memory of the Bytes.
    ///
    /// This is not stable and may be removed or renamed in the future.
    #[inline]
    #[doc(hidden)]
    pub fn deep_clone_bytes(&self) -> Self {
        Self(self.0.deep_clone_bytes())
    }

    fn from_char_iter<I: iter::Iterator<Item = char>>(mut iter: I) -> Self {
        let (min_size, _) = iter.size_hint();
        if min_size > INLINE_CAP {
            let s: String = iter.collect();
            return Self(Repr::Bytes(Bytes::from(s)));
        }
        let mut len = 0;
        let mut buf = [0u8; INLINE_CAP];
        while let Some(ch) = iter.next() {
            let size = ch.len_utf8();
            if size + len > INLINE_CAP {
                let (min_remaining, _) = iter.size_hint();
                let mut s = String::with_capacity(size + len + min_remaining);
                s.push_str(unsafe { core::str::from_utf8_unchecked(&buf[..len]) });
                s.push(ch);
                s.extend(iter);
                return Self(Repr::Bytes(Bytes::from(s)));
            }
            ch.encode_utf8(&mut buf[len..]);
            len += size;
        }
        Self(Repr::Inline { len, buf })
    }
}

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

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

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

impl Deref for FastStr {
    type Target = str;

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

impl From<FastStr> for String {
    #[inline]
    fn from(val: FastStr) -> Self {
        #[allow(deprecated)]
        val.into_string()
    }
}

impl From<FastStr> for Bytes {
    #[inline]
    fn from(val: FastStr) -> Self {
        val.into_bytes()
    }
}

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

impl Eq for FastStr {}

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

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

impl<'a> PartialEq<&'a str> for FastStr {
    #[inline]
    fn eq(&self, other: &&'a str) -> bool {
        self == *other
    }
}

impl<'a> PartialEq<FastStr> for &'a str {
    #[inline]
    fn eq(&self, other: &FastStr) -> bool {
        *self == other
    }
}

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

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

impl<'a> PartialEq<&'a String> for FastStr {
    #[inline]
    fn eq(&self, other: &&'a String) -> bool {
        self == *other
    }
}

impl<'a> PartialEq<FastStr> for &'a String {
    #[inline]
    fn eq(&self, other: &FastStr) -> bool {
        *self == other
    }
}

impl Ord for FastStr {
    #[inline]
    fn cmp(&self, other: &FastStr) -> Ordering {
        self.as_str().cmp(other.as_str())
    }
}

impl PartialOrd for FastStr {
    #[inline]
    fn partial_cmp(&self, other: &FastStr) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl hash::Hash for FastStr {
    #[inline]
    fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
        self.as_str().hash(hasher)
    }
}

impl fmt::Debug for FastStr {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

impl fmt::Display for FastStr {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self.as_str(), f)
    }
}

impl iter::FromIterator<char> for FastStr {
    #[inline]
    fn from_iter<I: iter::IntoIterator<Item = char>>(iter: I) -> FastStr {
        let iter = iter.into_iter();
        Self::from_char_iter(iter)
    }
}

fn build_from_str_iter<T>(mut iter: impl Iterator<Item = T>) -> FastStr
where
    T: AsRef<str>,
    String: iter::Extend<T>,
{
    let mut len = 0;
    let mut buf = [0u8; INLINE_CAP];
    while let Some(slice) = iter.next() {
        let slice = slice.as_ref();
        let size = slice.len();
        if size + len > INLINE_CAP {
            let mut s = String::with_capacity(size + len);
            s.push_str(unsafe { core::str::from_utf8_unchecked(&buf[..len]) });
            s.push_str(slice);
            s.extend(iter);
            return FastStr(Repr::Bytes(Bytes::from(s)));
        }
        buf[len..][..size].copy_from_slice(slice.as_bytes());
        len += size;
    }
    FastStr(Repr::Inline { len, buf })
}

impl iter::FromIterator<String> for FastStr {
    #[inline]
    fn from_iter<I: iter::IntoIterator<Item = String>>(iter: I) -> FastStr {
        build_from_str_iter(iter.into_iter())
    }
}

impl<'a> iter::FromIterator<&'a String> for FastStr {
    #[inline]
    fn from_iter<I: iter::IntoIterator<Item = &'a String>>(iter: I) -> FastStr {
        FastStr::from_iter(iter.into_iter().map(|x| x.as_str()))
    }
}

impl<'a> iter::FromIterator<&'a str> for FastStr {
    #[inline]
    fn from_iter<I: iter::IntoIterator<Item = &'a str>>(iter: I) -> FastStr {
        build_from_str_iter(iter.into_iter())
    }
}

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

impl FromStr for FastStr {
    type Err = Infallible;

    #[inline]
    fn from_str(s: &str) -> Result<FastStr, Self::Err> {
        Ok(FastStr::new(s))
    }
}

// We need to wait for specilization to be stable to implement this.
// impl<T> From<T> for FastStr
// where
//     T: AsRef<str>,
// {
//     #[inline]
//     fn from(text: T) -> Self {
//         Self::new(text)
//     }
// }

impl From<Arc<str>> for FastStr {
    #[inline]
    fn from(val: Arc<str>) -> Self {
        Self::from_arc_str(val)
    }
}

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

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

impl From<&'static str> for FastStr {
    #[inline]
    fn from(val: &'static str) -> Self {
        Self::from_static_str(val)
    }
}

impl From<Cow<'static, str>> for FastStr {
    #[inline]
    fn from(val: Cow<'static, str>) -> Self {
        match val {
            Cow::Borrowed(s) => Self::from_static_str(s),
            Cow::Owned(s) => Self::from_string(s),
        }
    }
}

const INLINE_CAP: usize = 24;

#[derive(Clone)]
enum Repr {
    Empty,
    Bytes(Bytes),
    ArcStr(Arc<str>),
    ArcString(Arc<String>),
    StaticStr(&'static str),
    Inline { len: usize, buf: [u8; INLINE_CAP] },
}

impl Repr {
    #[inline]
    fn new<T>(text: T) -> Self
    where
        T: AsRef<str>,
    {
        let text = text.as_ref();
        if text.is_empty() {
            return Self::Empty;
        }
        {
            let len = text.len();
            if len <= INLINE_CAP {
                // Safety: we have checked the length of text <= `INLINE_CAP`.
                return unsafe { Self::new_inline_impl(text) };
            }
        }

        Self::Bytes(Bytes::copy_from_slice(text.as_bytes()))
    }

    fn new_inline(s: &str) -> Self {
        if s.len() > INLINE_CAP {
            panic!("[FastStr] string is too long to inline");
        }
        // Safety: we have checked the length of s <= `INLINE_CAP`.
        unsafe { Self::new_inline_impl(s) }
    }

    /// # Safety
    ///
    /// The length of `s` must be <= `INLINE_CAP`.
    unsafe fn new_inline_impl(s: &str) -> Self {
        let mut buf = [0u8; INLINE_CAP];
        std::ptr::copy_nonoverlapping(s.as_ptr(), buf.as_mut_ptr(), s.len());
        Self::Inline { len: s.len(), buf }
    }

    #[inline]
    const fn empty() -> Self {
        Self::Empty
    }

    #[inline]
    fn from_arc_str(s: Arc<str>) -> Self {
        Self::ArcStr(s)
    }

    #[inline]
    fn from_string(s: String) -> Self {
        let v = s.into_bytes();
        // Safety: s is a `String`, thus we can assume it's valid utf-8
        unsafe { Self::from_bytes_unchecked(v.into()) }
    }

    #[inline]
    fn from_arc_string(s: Arc<String>) -> Self {
        match Arc::try_unwrap(s) {
            Ok(s) => Self::from_string(s),
            Err(s) => Self::ArcString(s),
        }
    }

    /// Safety: the caller must guarantee that the bytes `v` are valid UTF-8.
    #[inline]
    unsafe fn from_bytes_unchecked(bytes: Bytes) -> Self {
        Self::Bytes(bytes)
    }

    #[inline]
    fn len(&self) -> usize {
        match self {
            Self::Empty => 0,
            Self::Bytes(bytes) => bytes.len(),
            Self::ArcStr(arc_str) => arc_str.len(),
            Self::ArcString(arc_string) => arc_string.len(),
            Self::StaticStr(s) => s.len(),
            Self::Inline { len, .. } => *len,
        }
    }

    #[inline]
    fn is_empty(&self) -> bool {
        match self {
            Self::Empty => true,
            Self::Bytes(bytes) => bytes.is_empty(),
            Self::ArcStr(arc_str) => arc_str.is_empty(),
            Self::ArcString(arc_string) => arc_string.is_empty(),
            Self::StaticStr(s) => s.is_empty(),
            Self::Inline { len, .. } => *len == 0,
        }
    }

    #[inline]
    fn as_str(&self) -> &str {
        match self {
            Self::Empty => "",
            // Safety: this is guaranteed by the user when creating the `FastStr`.
            Self::Bytes(bytes) => unsafe { std::str::from_utf8_unchecked(bytes) },
            Self::ArcStr(arc_str) => arc_str,
            Self::ArcString(arc_string) => arc_string,
            Self::StaticStr(s) => s,
            Self::Inline { len, buf } => unsafe { std::str::from_utf8_unchecked(&buf[..*len]) },
        }
    }

    #[inline]
    #[deprecated]
    fn into_string(self) -> String {
        match self {
            Self::Empty => String::new(),
            Self::Bytes(bytes) => unsafe { String::from_utf8_unchecked(bytes.into()) },
            Self::ArcStr(arc_str) => arc_str.to_string(),
            Self::ArcString(arc_string) => {
                Arc::try_unwrap(arc_string).unwrap_or_else(|arc| (*arc).clone())
            }
            Self::StaticStr(s) => s.to_string(),
            Self::Inline { len, buf } => unsafe {
                String::from_utf8_unchecked(buf[..len].to_vec())
            },
        }
    }

    #[inline]
    fn into_bytes(self) -> Bytes {
        match self {
            Self::Empty => Bytes::new(),
            Self::Bytes(bytes) => bytes,
            Self::ArcStr(arc_str) => Bytes::from(arc_str.as_bytes().to_vec()),
            Self::ArcString(arc_string) => {
                Bytes::from(Arc::try_unwrap(arc_string).unwrap_or_else(|arc| (*arc).clone()))
            }
            Self::StaticStr(s) => Bytes::from_static(s.as_bytes()),
            Self::Inline { len, buf } => Bytes::from(buf[..len].to_vec()),
        }
    }

    #[inline]
    fn deep_clone_bytes(&self) -> Self {
        match self {
            Self::Empty => Self::Empty,
            // Safety: this is guaranteed by the user when creating the `FastStr`.
            Self::Bytes(bytes) => unsafe { Self::new(std::str::from_utf8_unchecked(bytes)) },
            Self::ArcStr(arc_str) => Self::ArcStr(Arc::clone(arc_str)),
            Self::ArcString(arc_string) => Self::ArcString(Arc::clone(arc_string)),
            Self::StaticStr(s) => Self::StaticStr(s),
            Self::Inline { len, buf } => Self::Inline {
                len: *len,
                buf: *buf,
            },
        }
    }

    #[inline]
    fn slice_ref(&self, subset: &[u8]) -> Self {
        if subset.is_empty() {
            return Self::Empty;
        }
        let bytes_p = self.as_ref().as_ptr() as usize;
        let bytes_len = self.len();

        let sub_p = subset.as_ptr() as usize;
        let sub_len = subset.len();

        assert!(
            sub_p >= bytes_p,
            "subset pointer ({:p}) is smaller than self pointer ({:p})",
            subset.as_ptr(),
            self.as_ref().as_ptr(),
        );
        assert!(
            sub_p + sub_len <= bytes_p + bytes_len,
            "subset is out of bounds: self = ({:p}, {}), subset = ({:p}, {})",
            self.as_ref().as_ptr(),
            bytes_len,
            subset.as_ptr(),
            sub_len,
        );

        let sub_offset = sub_p - bytes_p;
        match self {
            Repr::Empty => panic!("invalid slice ref, self is empty but subset is not"),
            Repr::Bytes(b) => Self::Bytes(b.slice_ref(subset)),
            Repr::ArcStr(s) => Self::Bytes(Bytes::copy_from_slice(
                s[sub_offset..sub_offset + sub_len].as_bytes(),
            )),
            Repr::ArcString(s) => Self::Bytes(Bytes::copy_from_slice(
                s[sub_offset..sub_offset + sub_len].as_bytes(),
            )),
            Repr::StaticStr(s) => Self::StaticStr(unsafe {
                std::str::from_utf8_unchecked(&s.as_bytes()[sub_offset..sub_offset + sub_len])
            }),
            Repr::Inline { len: _, buf } => Self::Inline {
                len: sub_len,
                buf: {
                    let mut new_buf = [0; INLINE_CAP];
                    new_buf[..sub_len].copy_from_slice(&buf[sub_offset..sub_offset + sub_len]);
                    new_buf
                },
            },
        }
    }
}

impl AsRef<[u8]> for Repr {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        match self {
            Self::Empty => &[],
            Self::Bytes(bytes) => bytes.as_ref(),
            Self::ArcStr(arc_str) => arc_str.as_bytes(),
            Self::ArcString(arc_string) => arc_string.as_bytes(),
            Self::StaticStr(s) => s.as_bytes(),
            Self::Inline { len, buf } => &buf[..*len],
        }
    }
}
#[cfg(feature = "redis")]
mod redis;

#[cfg(feature = "serde")]
mod serde;