flexstr 0.11.7

A flexible, simple to use, clone-efficient string type for Rust
Documentation
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
775
776
777
778
use alloc::borrow::{Borrow, Cow};
#[cfg(not(feature = "std"))]
use alloc::{borrow::ToOwned, boxed::Box};
use alloc::{rc::Rc, sync::Arc};
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::ops::{Deref, Index};
use core::slice::SliceIndex;
#[cfg(feature = "std")]
use std::{io, net::ToSocketAddrs};

use flexstr_support::{StringFromBytesMut, StringLike, StringToFromBytes};
use inline_flexstr::InlineFlexStr;
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

// *** Macros ***

macro_rules! partial_eq_impl {
    ($type:ty, $str_type:ty) => {
        impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> PartialEq<$type>
            for FlexStr<'s, S, R>
        where
            S: PartialEq<$str_type>,
        {
            fn eq(&self, other: &$type) -> bool {
                S::eq(self, other)
            }
        }

        impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> PartialEq<FlexStr<'s, S, R>>
            for $type
        where
            S: PartialEq<$str_type>,
        {
            fn eq(&self, other: &FlexStr<'s, S, R>) -> bool {
                S::eq(other, self)
            }
        }
    };
}

pub(crate) use partial_eq_impl;

macro_rules! ref_counted_mut_impl {
    ($str_type:ty) => {
        // NOTE: Cannot be implemented generically because CloneToUninit is needed
        // as a bound to `S`, but is unstable.
        impl RefCountedMut<$str_type> for Arc<$str_type> {
            #[inline]
            fn to_mut(&mut self) -> &mut $str_type {
                Arc::make_mut(self)
            }

            #[inline]
            fn as_mut(&mut self) -> &mut $str_type {
                // PANIC SAFETY: We only use this when we know the Arc is newly created
                Arc::get_mut(self).expect("Arc is shared")
            }

            #[inline]
            fn try_as_mut(&mut self) -> Option<&mut $str_type> {
                Arc::get_mut(self)
            }
        }

        // NOTE: Cannot be implemented generically because CloneToUninit is needed
        // as a bound to `S`, but is unstable.
        impl RefCountedMut<$str_type> for Rc<$str_type> {
            #[inline]
            fn to_mut(&mut self) -> &mut $str_type {
                Rc::make_mut(self)
            }

            #[inline]
            fn as_mut(&mut self) -> &mut $str_type {
                // PANIC SAFETY: We only use this when we know the Rc is newly created
                Rc::get_mut(self).expect("Rc is shared")
            }

            #[inline]
            fn try_as_mut(&mut self) -> Option<&mut $str_type> {
                Rc::get_mut(self)
            }
        }
    };
}

pub(crate) use ref_counted_mut_impl;

// *** ImmutableBytes ***

/// Marker trait for string types that don't provide conversion from bytes to mutable string reference
pub trait ImmutableBytes: StringToFromBytes {}

// *** RefCounted ***

/// Trait for storage that can be reference counted
pub trait RefCounted<S: ?Sized + StringToFromBytes>:
    Deref<Target = S> + for<'a> From<&'a S> + Clone
{
}

impl<S, R> RefCounted<S> for R
where
    R: Deref<Target = S> + for<'a> From<&'a S> + Clone,
    S: ?Sized + StringToFromBytes,
{
}

/// Trait for storage that can be reference counted and mutable
pub trait RefCountedMut<S: ?Sized + StringToFromBytes>: RefCounted<S> {
    /// Borrow the string as a mutable string reference, allocating and copying first, if needed.
    fn to_mut(&mut self) -> &mut S;

    /// Borrow the string as a mutable string reference. It will panic if the string is shared.
    fn as_mut(&mut self) -> &mut S;

    /// Try to borrow the string as a mutable string reference. Returns `None` if the data is shared.
    fn try_as_mut(&mut self) -> Option<&mut S> {
        None
    }
}

// *** ToOwnedFlexStr ***

/// Trait for types that can be converted to an owned FlexStr
pub trait ToOwnedFlexStr<R, S>
where
    R: RefCounted<S>,
    S: ?Sized + StringToFromBytes,
{
    /// Convert a borrowed string to an owned FlexStr
    fn to_owned_opt(&self) -> FlexStr<'static, S, R>;
}

impl<R, S> ToOwnedFlexStr<R, S> for S
where
    R: RefCounted<S>,
    S: ?Sized + StringToFromBytes,
{
    fn to_owned_opt(&self) -> FlexStr<'static, S, R> {
        FlexStr::from_borrowed(self).into_owned()
    }
}

// *** IntoOptimizedFlexStr ***

/// Trait for types that can be converted to an optimized FlexStr
pub trait IntoOptimizedFlexStr<R, S>
where
    R: RefCounted<S>,
    S: ?Sized + StringToFromBytes,
    Box<S>: From<S::Owned>,
{
    /// Convert a string to an optimized FlexStr
    fn into_opt(self) -> FlexStr<'static, S, R>;
}

impl<R, S> IntoOptimizedFlexStr<R, S> for S::Owned
where
    R: RefCounted<S>,
    S: ?Sized + StringToFromBytes,
    Box<S>: From<S::Owned>,
{
    fn into_opt(self) -> FlexStr<'static, S, R> {
        FlexStr::from_owned(self).optimize()
    }
}

// *** FlexStr ***

#[doc(alias = "SharedStr")]
#[doc(alias = "LocalStr")]
#[doc(alias = "SharedOsStr")]
#[doc(alias = "LocalOsStr")]
#[doc(alias = "SharedPath")]
#[doc(alias = "LocalPath")]
#[doc(alias = "SharedCStr")]
#[doc(alias = "LocalCStr")]
#[doc(alias = "SharedBytes")]
#[doc(alias = "LocalBytes")]
/// Flexible string type that can store a borrowed string, an inline string, a reference counted string, or a boxed string
#[derive(Debug)]
pub enum FlexStr<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> {
    /// Borrowed string - borrowed strings are imported as `&S`
    Borrowed(&'s S),
    /// Inline string - owned strings that are small enough to be stored inline
    Inlined(InlineFlexStr<S>),
    /// Reference counted string - owned strings that are too large for inline storage
    RefCounted(R),
    /// Boxed string - heap allocated strings are imported as `Box<S>`
    Boxed(Box<S>),
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> FlexStr<'s, S, R>
where
    for<'a> &'a S: Default,
{
    /// Create a new empty string. This is a Borrowed variant.
    pub fn empty() -> FlexStr<'s, S, R> {
        FlexStr::Borrowed(Default::default())
    }
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> FlexStr<'s, S, R> {
    fn copy(&self) -> FlexStr<'s, S, R> {
        match self {
            FlexStr::Borrowed(s) => FlexStr::Borrowed(s),
            FlexStr::Inlined(s) => FlexStr::Inlined(*s),
            FlexStr::RefCounted(s) => FlexStr::RefCounted(s.clone()),
            FlexStr::Boxed(s) => FlexStr::copy_into_owned(s),
        }
    }
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> FlexStr<'s, S, R>
where
    Box<S>: From<S::Owned>,
{
    /// Create a new string from an owned string (most likely without copy or allocation).
    /// The result is a Boxed variant.
    pub fn from_owned(s: S::Owned) -> FlexStr<'static, S, R> {
        FlexStr::Boxed(s.into())
    }
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> FlexStr<'s, S, R> {
    /// Create a new string from a borrowed string. This is a const fn because it does not allocate
    /// and results in a Borrowed variant.
    pub const fn from_borrowed(s: &'s S) -> FlexStr<'s, S, R> {
        FlexStr::Borrowed(s)
    }

    /// Create a new string from an inline string. This results in an Inlined variant.
    pub fn from_inline(s: InlineFlexStr<S>) -> FlexStr<'s, S, R> {
        FlexStr::Inlined(s)
    }

    /// Create a new string from a reference counted string. This results in a RefCounted variant.
    pub fn from_ref_counted(s: R) -> FlexStr<'s, S, R> {
        FlexStr::RefCounted(s)
    }

    /// Create a new string from a boxed string. This results in a Boxed variant.
    pub fn from_boxed(s: Box<S>) -> FlexStr<'s, S, R> {
        FlexStr::Boxed(s)
    }

    /// Returns true if this is a borrowed string
    pub fn is_borrowed(&self) -> bool {
        matches!(self, FlexStr::Borrowed(_))
    }

    /// Returns true if this is an inlined string
    pub fn is_inlined(&self) -> bool {
        matches!(self, FlexStr::Inlined(_))
    }

    /// Returns true if this is a reference counted string
    pub fn is_ref_counted(&self) -> bool {
        matches!(self, FlexStr::RefCounted(_))
    }

    /// Returns true if this is a boxed string
    pub fn is_boxed(&self) -> bool {
        matches!(self, FlexStr::Boxed(_))
    }

    /// Returns true if this is a string that is on the heap
    pub fn is_on_heap(&self) -> bool {
        matches!(self, FlexStr::RefCounted(_) | FlexStr::Boxed(_))
    }

    /// Returns true if this is a string that is off the heap
    pub fn is_off_heap(&self) -> bool {
        matches!(self, FlexStr::Borrowed(_) | FlexStr::Inlined(_))
    }

    fn copy_into_owned(s: &S) -> FlexStr<'static, S, R> {
        match InlineFlexStr::try_from_type(s) {
            Ok(inline) => FlexStr::Inlined(inline),
            Err(_) => FlexStr::RefCounted(s.into()),
        }
    }

    /// Optimize the string variant. This is a no-op for Inlined/Borrowed variants. RefCounted
    /// strings will attempt to inline, but otherwise be left as ref counted. Boxed strings will
    /// attempt to inline, but otherwise be converted to a ref counted string.
    pub fn optimize(self) -> FlexStr<'s, S, R> {
        match self {
            // This should be inlined or ref counted
            FlexStr::Boxed(s) => Self::copy_into_owned(&s),
            // There is probably a reason this is ref counted, but we can try to inline it first
            FlexStr::RefCounted(s) => match InlineFlexStr::try_from_type(&*s) {
                Ok(inline) => FlexStr::Inlined(inline),
                Err(_) => FlexStr::RefCounted(s),
            },
            // Borrowed and inlined strings are already optimized
            _ => self,
        }
    }

    /// Convert a string reference to an owned string. Inlined/RefCounted variants are cloned,
    /// Borrowed/Boxed variants are copied into a new Inlined or RefCounted owned string.
    pub fn to_owned(&self) -> FlexStr<'static, S, R> {
        match self {
            FlexStr::Borrowed(s) => FlexStr::copy_into_owned(s),
            FlexStr::Inlined(s) => FlexStr::Inlined(*s),
            FlexStr::RefCounted(s) => FlexStr::RefCounted(s.clone()),
            FlexStr::Boxed(s) => FlexStr::copy_into_owned(s),
        }
    }

    /// Consume a string and convert it to an owned string. Inlined/RefCounted/Boxed variants
    /// are moved, Borrowed variants are copied into a new Inlined or RefCounted owned string.
    pub fn into_owned(self) -> FlexStr<'static, S, R> {
        match self {
            FlexStr::Borrowed(s) => FlexStr::copy_into_owned(s),
            FlexStr::Inlined(s) => FlexStr::Inlined(s),
            FlexStr::RefCounted(s) => FlexStr::RefCounted(s),
            FlexStr::Boxed(s) => FlexStr::Boxed(s),
        }
    }

    /// Borrow a string reference as `&S`
    pub fn as_ref_type(&self) -> &S {
        match self {
            FlexStr::Borrowed(s) => s,
            FlexStr::Inlined(s) => s,
            FlexStr::RefCounted(s) => s,
            FlexStr::Boxed(s) => s,
        }
    }

    /// Convert a string reference to an owned string. `S::to_owned` is called on all variants.
    pub fn to_owned_type(&self) -> S::Owned {
        match self {
            FlexStr::Borrowed(s) => <S as ToOwned>::to_owned(s),
            FlexStr::Inlined(s) => <S as ToOwned>::to_owned(s),
            FlexStr::RefCounted(s) => <S as ToOwned>::to_owned(s),
            FlexStr::Boxed(s) => <S as ToOwned>::to_owned(s),
        }
    }

    /// Borrow the string as a raw byte slice (NOTE: includes trailing NUL for CStr)
    pub fn as_raw_bytes(&self) -> &[u8] {
        match self {
            FlexStr::Borrowed(s) => S::self_as_raw_bytes(s),
            FlexStr::Inlined(s) => s.as_raw_bytes(),
            FlexStr::RefCounted(s) => S::self_as_raw_bytes(s),
            FlexStr::Boxed(s) => S::self_as_raw_bytes(s),
        }
    }

    /// Borrow the string as bytes
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            FlexStr::Borrowed(s) => S::self_as_bytes(s),
            FlexStr::Inlined(s) => s.as_bytes(),
            FlexStr::RefCounted(s) => S::self_as_bytes(s),
            FlexStr::Boxed(s) => S::self_as_bytes(s),
        }
    }
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> FlexStr<'s, S, R>
where
    S::Owned: From<Box<S>>,
{
    /// Consume a string and convert it to an owned string. `S::to_owned` is called on Borrowed/Inlined/RefCounted variants.
    /// Boxed variants are converted directly into `S::Owned` (most likely without copy or allocation).
    pub fn into_owned_type(self) -> S::Owned {
        match self {
            FlexStr::Borrowed(s) => <S as ToOwned>::to_owned(s),
            FlexStr::Inlined(s) => <S as ToOwned>::to_owned(&s),
            FlexStr::RefCounted(s) => <S as ToOwned>::to_owned(&s),
            FlexStr::Boxed(s) => s.into(),
        }
    }
}

// NOTE: This implementation is the "slow path" for types that are ImmutableBytes (iow, cannot mutate their raw bytes)
impl<'s, S: ?Sized + ImmutableBytes, R: RefCountedMut<S>> FlexStr<'s, S, R> {
    /// Borrow the string as a mutable string reference, converting if needed. If the string is Borrowed,
    /// it is made into a reference counted string first. RefCounted variants will allocate + copy
    /// if they are shared. In all other cases, the string is borrowed as a mutable reference
    /// directly.
    pub fn to_mut_type_fallback(&mut self) -> &mut S {
        match self {
            // Borrowed strings can't be made mutable - we need to own it first
            // ImmutableBytes strings can't mutate inlined strings, so ref count it
            FlexStr::Borrowed(s) => {
                *self = FlexStr::RefCounted((&**s).into());
                match self {
                    // We know this is brand new, so it is safe to share mutably immediately
                    FlexStr::RefCounted(s) => s.as_mut(),
                    _ => unreachable!("Unexpected variant"),
                }
            }
            // ImmutableBytes strings must be converted before being made mutable
            FlexStr::Inlined(s) => {
                *self = FlexStr::RefCounted((&**s).into());
                match self {
                    // We know this is brand new, so it is safe to share mutably immediately
                    FlexStr::RefCounted(s) => s.as_mut(),
                    _ => unreachable!("Unexpected variant"),
                }
            }
            // Since this might be shared, we need to check before just sharing as mutable
            FlexStr::RefCounted(s) => s.to_mut(),
            // Boxed strings can be made mutable directly
            FlexStr::Boxed(s) => s.as_mut(),
        }
    }
}

// NOTE: This implementation is the "fast path" for types that provide direct mutable access to their bytes
impl<'s, S: ?Sized + StringFromBytesMut, R: RefCountedMut<S>> FlexStr<'s, S, R> {
    /// Borrow the string as a mutable string reference, converting if needed. If the string is borrowed,
    /// it is made into an owned string first. RefCounted variants will allocate + copy
    /// if they are shared. In all other cases, the string is borrowed as a mutable reference
    /// directly.
    pub fn to_mut_type(&mut self) -> &mut S {
        match self {
            // Borrowed strings can't be made mutable - we need to own it first
            FlexStr::Borrowed(s) => {
                *self = FlexStr::copy_into_owned(s);
                // copy_into_owned will never return a borrowed variant
                match self {
                    FlexStr::Inlined(s) => s.as_mut_type(),
                    FlexStr::RefCounted(s) => s.as_mut(),
                    _ => {
                        // PANIC SAFETY: copy_into_owned will never return a borrowed/boxed variant
                        unreachable!("Unexpected borrowed/boxed variant");
                    }
                }
            }
            // Inlined strings can be made mutable directly
            FlexStr::Inlined(s) => s.as_mut_type(),
            // Since this might be shared, we need to check before just sharing as mutable
            FlexStr::RefCounted(s) => s.to_mut(),
            // Boxed strings can be made mutable directly
            FlexStr::Boxed(s) => s.as_mut(),
        }
    }
}

impl<'s, S: ?Sized + StringToFromBytes> FlexStr<'s, S, Arc<S>>
where
    Arc<S>: for<'a> From<&'a S>,
    Rc<S>: for<'a> From<&'a S>,
{
    /// Convert a shared string reference to a local string. The Borrowed/Inlined variants are copied,
    /// RefCounted is copied into a new allocation, and Boxed is copied into an Inlined or RefCounted variant.
    pub fn to_local(&self) -> FlexStr<'s, S, Rc<S>> {
        match self {
            FlexStr::Borrowed(s) => FlexStr::Borrowed(s),
            FlexStr::Inlined(s) => FlexStr::Inlined(*s),
            FlexStr::RefCounted(s) => FlexStr::RefCounted(Rc::from(s)),
            FlexStr::Boxed(s) => FlexStr::copy_into_owned(s),
        }
    }

    /// Consume a shared string and convert it to a local string. The Borrowed/Inlined/Boxed variants are moved,
    /// and RefCounted is copied into a new allocation.
    pub fn into_local(self) -> FlexStr<'s, S, Rc<S>> {
        match self {
            FlexStr::Borrowed(s) => FlexStr::Borrowed(s),
            FlexStr::Inlined(s) => FlexStr::Inlined(s),
            FlexStr::RefCounted(s) => FlexStr::RefCounted(Rc::from(&s)),
            FlexStr::Boxed(s) => FlexStr::Boxed(s),
        }
    }
}

impl<'s, S: ?Sized + StringToFromBytes> FlexStr<'s, S, Rc<S>>
where
    Rc<S>: for<'a> From<&'a S>,
    Arc<S>: for<'a> From<&'a S>,
{
    /// Convert a local string reference to a shared string. The Borrowed/Inlined variants are copied,
    /// RefCounted is copied into a new allocation, and Boxed is copied into an Inlined or RefCounted variant.
    pub fn to_shared(&self) -> FlexStr<'s, S, Arc<S>> {
        match self {
            FlexStr::Borrowed(s) => FlexStr::Borrowed(s),
            FlexStr::Inlined(s) => FlexStr::Inlined(*s),
            FlexStr::RefCounted(s) => FlexStr::RefCounted(Arc::from(s)),
            FlexStr::Boxed(s) => FlexStr::copy_into_owned(s),
        }
    }

    /// Consume a local string and convert it to a shared string. The Borrowed/Inlined/Boxed variants are moved,
    /// and RefCounted is copied into a new allocation.
    pub fn into_shared(self) -> FlexStr<'s, S, Arc<S>> {
        match self {
            FlexStr::Borrowed(s) => FlexStr::Borrowed(s),
            FlexStr::Inlined(s) => FlexStr::Inlined(s),
            FlexStr::RefCounted(s) => FlexStr::RefCounted(Arc::from(&s)),
            FlexStr::Boxed(s) => FlexStr::Boxed(s),
        }
    }
}

// *** StringLike ***

impl<S: ?Sized + StringToFromBytes, R: RefCounted<S>> StringLike<S> for FlexStr<'_, S, R> {
    fn as_ref_type(&self) -> &S {
        <Self>::as_ref_type(self)
    }

    fn as_bytes(&self) -> &[u8] {
        <Self>::as_bytes(self)
    }

    fn into_owned_type(self) -> S::Owned
    where
        S::Owned: From<Box<S>>,
    {
        <Self>::into_owned_type(self)
    }

    fn to_owned_type(&self) -> S::Owned {
        <Self>::to_owned_type(self)
    }
}

// *** Default ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> Default for FlexStr<'s, S, R>
where
    for<'a> &'a S: Default,
{
    /// Create a new string from a default value
    fn default() -> FlexStr<'s, S, R> {
        FlexStr::empty()
    }
}

// *** From ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> From<&'s S> for FlexStr<'s, S, R> {
    fn from(s: &'s S) -> Self {
        FlexStr::from_borrowed(s)
    }
}

// NOTE: Could not be implemented more generically because of From<S::Owned>
impl<'s, S: ?Sized + StringToFromBytes> From<Rc<S>> for FlexStr<'s, S, Rc<S>>
where
    Rc<S>: for<'a> From<&'a S>,
{
    fn from(s: Rc<S>) -> Self {
        FlexStr::from_ref_counted(s)
    }
}

// NOTE: Could not be implemented more generically because of From<S::Owned>
impl<'s, S: ?Sized + StringToFromBytes> From<Arc<S>> for FlexStr<'s, S, Arc<S>>
where
    Arc<S>: for<'a> From<&'a S>,
{
    fn from(s: Arc<S>) -> Self {
        FlexStr::from_ref_counted(s)
    }
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> From<Box<S>> for FlexStr<'s, S, R> {
    fn from(s: Box<S>) -> Self {
        FlexStr::from_boxed(s)
    }
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> From<InlineFlexStr<S>>
    for FlexStr<'s, S, R>
{
    fn from(s: InlineFlexStr<S>) -> Self {
        FlexStr::from_inline(s)
    }
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> From<Cow<'s, S>> for FlexStr<'s, S, R>
where
    Box<S>: From<S::Owned>,
{
    fn from(s: Cow<'s, S>) -> Self {
        match s {
            Cow::Borrowed(s) => FlexStr::from_borrowed(s),
            Cow::Owned(s) => FlexStr::from_owned(s),
        }
    }
}

// *** Clone ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> Clone for FlexStr<'s, S, R> {
    fn clone(&self) -> Self {
        self.copy()
    }
}

// *** Hash ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> Hash for FlexStr<'s, S, R>
where
    S: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_ref_type().hash(state);
    }
}

// *** Deref<Target = S> ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> Deref for FlexStr<'s, S, R> {
    type Target = S;

    fn deref(&self) -> &Self::Target {
        self.as_ref_type()
    }
}

// *** Display ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> fmt::Display for FlexStr<'s, S, R>
where
    S: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        S::fmt(self.as_ref_type(), f)
    }
}

// *** Borrow ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> Borrow<S> for FlexStr<'s, S, R> {
    fn borrow(&self) -> &S {
        self.as_ref_type()
    }
}

// *** PartialEq / Eq ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> PartialEq for FlexStr<'s, S, R>
where
    S: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        S::eq(self.as_ref_type(), other.as_ref_type())
    }
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> Eq for FlexStr<'s, S, R> where S: Eq {}

// *** PartialOrd / Ord ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> PartialOrd for FlexStr<'s, S, R>
where
    S: PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        S::partial_cmp(self.as_ref_type(), other.as_ref_type())
    }
}

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> Ord for FlexStr<'s, S, R>
where
    S: Ord,
{
    fn cmp(&self, other: &Self) -> Ordering {
        S::cmp(self.as_ref_type(), other.as_ref_type())
    }
}

// *** Index ***

impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>, I: SliceIndex<S>> Index<I>
    for FlexStr<'s, S, R>
where
    S: Index<I>,
{
    type Output = S::Output;

    fn index(&self, index: I) -> &Self::Output {
        S::index(self.as_ref_type(), index)
    }
}

// *** ToSocketAddrs ***

#[cfg(feature = "std")]
impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> ToSocketAddrs for FlexStr<'s, S, R>
where
    S: ToSocketAddrs,
{
    type Iter = <S as ToSocketAddrs>::Iter;

    fn to_socket_addrs(&self) -> io::Result<<S as ToSocketAddrs>::Iter> {
        self.as_ref_type().to_socket_addrs()
    }
}

// *** Serialize ***

#[cfg(feature = "serde")]
impl<'s, S: ?Sized + StringToFromBytes, R: RefCounted<S>> Serialize for FlexStr<'s, S, R>
where
    S: Serialize,
{
    fn serialize<SER: Serializer>(&self, serializer: SER) -> Result<SER::Ok, SER::Error> {
        S::serialize(self.as_ref_type(), serializer)
    }
}

// *** Deserialize ***

#[cfg(feature = "serde")]
impl<'de, S: ?Sized + StringToFromBytes, R: RefCounted<S>> Deserialize<'de>
    for FlexStr<'static, S, R>
where
    Box<S>: Deserialize<'de>,
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // TODO: See TODO in InlineFlexStr::deserialize for more details.
        // This one isn't as egregious since Boxed isn't inherently wrong here.
        Box::deserialize(deserializer)
            .map(FlexStr::Boxed)
            .map(FlexStr::optimize)
    }
}

// *** Zeroize ***

/// Zero the raw bytes of a DST behind a mutable reference.
///
/// The zeroed value remains valid for all supported string types: all-zero bytes
/// produce valid `str` (NUL is valid UTF-8), `[u8]`, `CStr` (NUL terminator),
/// `OsStr`, and `Path`. None of these types have `Drop` impls, so subsequent
/// deallocation (via Box/Arc/Rc drop) only needs the pointer and size.
#[cfg(feature = "zeroize")]
fn zeroize_raw_bytes<S: ?Sized + StringToFromBytes>(s: &mut S) {
    let len = S::self_as_raw_bytes(s).len();
    let ptr = s as *mut S as *mut u8;
    // SAFETY: We have exclusive ownership (`&mut S`). The pointer and length are valid
    // because we obtained them from the living reference.
    unsafe {
        zeroize::Zeroize::zeroize(core::slice::from_raw_parts_mut(ptr, len));
    }
}

#[cfg(feature = "zeroize")]
impl<'s, S: ?Sized + StringToFromBytes, R: RefCountedMut<S>> zeroize::TryZeroize
    for FlexStr<'s, S, R>
{
    fn try_zeroize(&mut self) -> bool {
        match self {
            FlexStr::Inlined(s) => {
                zeroize::Zeroize::zeroize(s);
            }
            FlexStr::Boxed(s) => {
                zeroize_raw_bytes(&mut **s);
            }
            FlexStr::RefCounted(rc) => {
                if let Some(s) = rc.try_as_mut() {
                    zeroize_raw_bytes(s);
                } else {
                    // Shared reference — cannot zero the underlying data
                    return false;
                }
            }
            // Borrowed data is not owned by us — cannot zero
            FlexStr::Borrowed(_) => return false,
        }
        *self = FlexStr::Inlined(InlineFlexStr::zeroed());
        true
    }
}