cowstr 1.2.0

Copy-on-Write shared strings
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
use constptr::ConstPtr;
use std::borrow::Borrow;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::hash::Hash;
use std::hash::Hasher;
use std::ops;
use std::str::FromStr;

use crate::*;

/// Arbitrary immutable text as span from some shared string. `SubStr` holding a reference to
/// the `CowStr` they lie within. This removes the need to pass lifetimes around as memory
/// become reference counted.
#[derive(Clone)]
pub struct SubStr {
    origin: CowStr,
    substr: ConstPtr<str>,
}

// `SubStr` are immutable, thus the can be Send and Sync.
unsafe impl Send for SubStr {}
unsafe impl Sync for SubStr {}

/// A constant for an always empty `SubStr`.
pub const EMPTY_SUBSTR: SubStr = SubStr::from_static("");

impl SubStr {
    /// Create a `SubStr` that spans a complete `CowStr`.
    #[doc(hidden)]
    #[deprecated = "use SubStr::from()"]
    #[mutants::skip]
    #[must_use]
    #[inline]
    pub fn new(from: &CowStr) -> SubStr {
        SubStr {
            origin: from.clone(),
            substr: ConstPtr::from(&from[..]),
        }
    }

    /// Create and `SubStr` from a `&str` that must be contained an initial `CowStr`.  This is
    /// useful when using methods from `&str` that is obtained from a `CowStr` to generates a
    /// `SubStr`. See the `from_raw_parts()` method for a unsafe/unchecked variant.
    ///
    /// # Panics
    ///
    /// `substr` is not within `from`.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = CowStr::from("test string");
    /// let (left, right) = origin.split_once(' ').unwrap();
    /// let left = SubStr::from_contained_str(&origin, left);
    /// let right = SubStr::from_contained_str(&origin, right);
    /// assert_eq!(left, "test");
    /// assert_eq!(right, "string");
    /// ```
    #[inline]
    #[must_use]
    pub fn from_contained_str(from: &CowStr, substr: &str) -> SubStr {
        // We need to check only for the first character, there is no way one can safely
        // construct a &str that spans past the end of a original CowStr
        assert!(
            from.as_bytes().as_ptr_range().contains(&substr.as_ptr()),
            "`substr` is not part of `from`"
        );
        // Safety: we just asserted that the `substr` is part of `from`
        unsafe { Self::from_raw_parts(from.clone(), substr) }
    }

    /// Create and `SubStr` as span of a `CowStr`.
    ///
    /// # Panics
    ///
    /// The range is wider than `from` or does not lie on utf-8 character boundaries.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = CowStr::from("this is a test string");
    /// let substr = SubStr::from_range(&origin, 10..14).unwrap();
    /// assert_eq!(substr, "test");
    /// ```
    pub fn from_range<R>(from: &CowStr, range: R) -> Result<SubStr, Error>
    where
        R: std::slice::SliceIndex<str, Output = str> + Clone,
        Self: ops::Index<R, Output = str>,
    {
        if let Some(substr) = from.get(range) {
            Ok(SubStr {
                origin: from.clone(),
                // Safety: we got a valid 'Some(substr)' above.
                substr: unsafe { ConstPtr::new_unchecked(substr) },
            })
        } else {
            Err(Error::Range)
        }
    }

    #[doc(hidden)]
    #[deprecated = "use SubStr::from_range()"]
    #[mutants::skip]
    #[inline]
    pub fn new_range(from: &CowStr, range: ops::Range<usize>) -> Result<SubStr, Error> {
        Self::from_range(from, range)
    }

    /// Create a `SubStr` as range from an existing `SubStr`.
    /// Returns `Err(Error::Range)` when the range is wider self.
    ///
    /// # Panics
    ///
    /// The range is not on utf-8 character boundaries.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = SubStr::from("this is a test string");
    /// let substr = origin.sub_range(10..14).unwrap();
    /// assert_eq!(substr, "test");
    /// ```
    pub fn sub_range<R>(&self, range: R) -> Result<SubStr, Error>
    where
        R: std::slice::SliceIndex<str, Output = str> + Clone,
        Self: ops::Index<R, Output = str>,
    {
        // Safety: self.substr is always a valid pointer
        if let Some(substr) = unsafe { self.substr.as_ref() }.get(range) {
            Ok(SubStr {
                origin: self.origin.clone(),
                // Safety: we got a valid 'Some(substr)' above.
                substr: unsafe { ConstPtr::new_unchecked(substr) },
            })
        } else {
            Err(Error::Range)
        }
    }

    /// Like `SubStr::sub_range()` but modifies a `SubStr` in-place. This can be significantly
    /// more efficient but there is no error handling when the range is wider than `self`.
    ///
    /// # Panics
    ///
    /// The range is wider than `self` or is not on utf-8 character boundaries.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let mut origin = SubStr::from("this is a test string");
    /// origin.sub_range_inplace(10..14);
    /// assert_eq!(origin, "test");
    /// ```
    pub fn sub_range_inplace<R>(&mut self, range: R)
    where
        R: std::slice::SliceIndex<str, Output = str> + Clone,
        Self: ops::Index<R, Output = str>,
    {
        // Safety: self.substr is always a valid pointer, the indexing result is so as well.
        self.substr = unsafe { ConstPtr::new_unchecked(&self.substr.as_ref()[range]) };
    }

    /// Create a `SubStr` that spans all the content from the start of self's origin `CowStr`
    /// to the begin of self.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = SubStr::from("this is a test string");
    /// let substr = SubStr::sub_range(&origin, 10..14).unwrap();
    /// let before = substr.origin_before();
    /// assert_eq!(before, "this is a ");
    /// ```
    #[inline]
    #[must_use]
    pub fn origin_before(&self) -> SubStr {
        SubStr {
            origin: self.origin.clone(),
            substr: unsafe {
                ConstPtr::new_unchecked(
                    &self.origin[..((self.substr.as_ptr() as *const u8)
                        .offset_from(self.origin.as_ptr()))
                        as usize],
                )
            },
        }
    }

    /// Create a `SubStr` that spans all the content from the end of self to the end of self's
    /// origin `CowStr`.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = SubStr::from("this is a test string");
    /// let substr = SubStr::sub_range(&origin, 10..14).unwrap();
    /// let after = substr.origin_after();
    /// assert_eq!(after, " string");
    /// ```
    #[inline]
    #[must_use]
    pub fn origin_after(&self) -> SubStr {
        SubStr {
            origin: self.origin.clone(),
            substr: unsafe {
                ConstPtr::new_unchecked(
                    &self.origin[((self.substr.as_ptr() as *const u8)
                        .offset_from(self.origin.as_ptr()))
                        as usize
                        + self.len()..],
                )
            },
        }
    }

    /// Create a `SubStr` that spans from `self` start to `substr` start. `self` start must
    /// be before `substr` start in the same `CowStr`. They do not need to overlap/contained
    /// within.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = SubStr::from("this is a test string");
    /// let test = SubStr::sub_range(&origin, 10..14).unwrap();
    /// let before = origin.start_to_start_of(&test).unwrap();
    /// assert_eq!(before, "this is a ");
    /// ```
    #[inline]
    pub fn start_to_start_of(&self, substr: &SubStr) -> Result<SubStr, Error> {
        if !self.same_origin(substr) {
            return Err(Error::DifferentOrigin);
        }

        let ops::Range {
            start: self_start, ..
        } = self.origin_range();
        let ops::Range {
            start: substr_start,
            ..
        } = substr.origin_range();

        SubStr::from_range(&self.origin, self_start..substr_start)
    }

    /// Create a `SubStr` that spans from `self` start to `substr` end. `self` start must
    /// be before `substr` end in the same `CowStr`. They do not need to overlap/contained
    /// within.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = SubStr::from("this is a test string");
    /// let test = SubStr::sub_range(&origin, 10..14).unwrap();
    /// let before = origin.start_to_end_of(&test).unwrap();
    /// assert_eq!(before, "this is a test");
    /// ```
    #[inline]
    pub fn start_to_end_of(&self, substr: &SubStr) -> Result<SubStr, Error> {
        if !self.same_origin(substr) {
            return Err(Error::DifferentOrigin);
        }

        let ops::Range {
            start: self_start, ..
        } = self.origin_range();
        let ops::Range {
            end: substr_end, ..
        } = substr.origin_range();

        SubStr::from_range(&self.origin, self_start..substr_end)
    }

    /// Create a `SubStr` that spans from `self` end to `substr` start. `self` end must
    /// be before `substr` start in the same `CowStr`. They must not to overlap/contained
    /// within.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = SubStr::from("this is a test string");
    /// let this = SubStr::sub_range(&origin, 0..4).unwrap();
    /// let test = SubStr::sub_range(&origin, 10..14).unwrap();
    /// let between = this.end_to_start_of(&test).unwrap();
    /// assert_eq!(between, " is a ");
    /// ```
    #[inline]
    pub fn end_to_start_of(&self, substr: &SubStr) -> Result<SubStr, Error> {
        if !self.same_origin(substr) {
            return Err(Error::DifferentOrigin);
        }

        let ops::Range { end: self_end, .. } = self.origin_range();
        let ops::Range {
            start: substr_start,
            ..
        } = substr.origin_range();

        SubStr::from_range(&self.origin, self_end..substr_start)
    }

    /// Create a `SubStr` that spans from `self` end to `substr` end. `self` end must
    /// be before `substr` end in the same `CowStr`. They do not need to overlap/contained
    /// within.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = SubStr::from("this is a test string");
    /// let test = SubStr::sub_range(&origin, 10..14).unwrap();
    /// let after = test.end_to_end_of(&origin).unwrap();
    /// assert_eq!(after, " string");
    /// ```
    #[inline]
    pub fn end_to_end_of(&self, substr: &SubStr) -> Result<SubStr, Error> {
        if !self.same_origin(substr) {
            return Err(Error::DifferentOrigin);
        }

        let ops::Range { end: self_end, .. } = self.origin_range();
        let ops::Range {
            end: substr_end, ..
        } = substr.origin_range();

        SubStr::from_range(&self.origin, self_end..substr_end)
    }

    #[inline]
    #[must_use]
    fn origin_range(&self) -> ops::Range<usize> {
        self.origin.range_of(self)
    }

    /// Create a `SubStr` that spans a complete `'static str`.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let static_substr = SubStr::from_static("test string");
    /// assert_eq!(static_substr, "test string");
    /// ```
    #[must_use]
    #[inline]
    pub const fn from_static(from: &'static str) -> SubStr {
        SubStr {
            origin: CowStr::from_static(from),
            // Safety: 'from' is a valid reference.
            substr: unsafe { ConstPtr::new_unchecked(from) },
        }
    }

    /// Returns `Ok(&'static str)` when the underlying string has static lifetime and
    /// `Err(&'self str)` when it is dynamically allocated.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let static_substr = SubStr::from_static("test string");
    /// assert_eq!(static_substr.deref_static(), Ok("test string"));
    ///
    /// let dynamic_substr = SubStr::from("test string");
    /// assert_eq!(dynamic_substr.deref_static(), Err("test string"));
    /// ```
    #[inline]
    pub fn deref_static(&self) -> Result<&'static str, &str> {
        match self.origin.deref_static() {
            // Safety: self.substr is always a valid pointer
            Ok(_) => Ok(unsafe { self.substr.as_ref() }),
            Err(_) => Err(unsafe { self.substr.as_ref() }),
        }
    }

    /// Get a reference to the original `CowStr` from which this `SubStr` is constructed.
    #[inline]
    #[must_use]
    pub fn origin(&self) -> &CowStr {
        &self.origin
    }

    /// Returns 'true' when two `SubStrs` share the same original `CowStr`.
    #[inline]
    #[must_use]
    pub fn same_origin(&self, other: &Self) -> bool {
        self.origin().is_same_as(other.origin())
    }

    /// Create a `SubStr` from its raw components.
    ///
    /// # Safety
    ///
    /// `substr` must be slice inside of `from`.
    #[inline]
    #[must_use]
    pub unsafe fn from_raw_parts(from: CowStr, substr: *const str) -> SubStr {
        debug_assert!(
            from.as_bytes()
                .as_ptr_range()
                .contains(&substr.cast::<u8>()),
            "`substr` is not part of `from`"
        );
        SubStr {
            origin: from,
            substr: ConstPtr::new_unchecked(substr),
        }
    }

    /// Deconstructs the `Substr` into its raw parts. Note that the returned `ConstPtr<str>`
    /// will only be valid as long the owning `CowStr` is not mutated or dropped. The only
    /// exception here are the `try_push_*()` methods which neither reallocate nor mutate the
    /// slice that is referenced by the `ConstPtr<str>`.
    #[inline]
    #[must_use]
    pub fn into_raw_parts(self) -> (CowStr, *const str) {
        (self.origin, self.substr.as_ptr())
    }
}

impl fmt::Display for SubStr {
    #[inline]
    #[mutants::skip] /* we just pretend it works */
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl ops::Deref for SubStr {
    type Target = str;

    #[inline]
    fn deref(&self) -> &Self::Target {
        // Safety: substr is always valid
        unsafe { self.substr.as_ref() }
    }
}

impl From<&str> for SubStr {
    #[inline]
    fn from(s: &str) -> Self {
        SubStr::from(CowStr::from(s))
    }
}

impl From<&mut str> for SubStr {
    #[inline]
    fn from(s: &mut str) -> Self {
        SubStr::from(CowStr::from(s))
    }
}

impl From<CowStr> for SubStr {
    #[inline]
    fn from(cow: CowStr) -> Self {
        SubStr::from(&cow)
    }
}

impl From<&CowStr> for SubStr {
    #[inline]
    fn from(from: &CowStr) -> Self {
        SubStr {
            origin: from.clone(),
            substr: ConstPtr::from(&from[..]),
        }
    }
}

impl From<String> for SubStr {
    #[inline]
    fn from(s: String) -> Self {
        SubStr::from(&*s)
    }
}

impl From<&String> for SubStr {
    #[inline]
    fn from(s: &String) -> Self {
        SubStr::from(&**s)
    }
}

impl From<char> for SubStr {
    #[inline]
    fn from(c: char) -> Self {
        SubStr::from(CowStr::from(c))
    }
}

#[allow(clippy::useless_conversion)]
#[test]
fn from() {
    assert_eq!(SubStr::from(String::from("foobar").as_mut_str()), "foobar");
    assert_eq!(SubStr::from(String::from("foobar")), "foobar");
    assert_eq!(SubStr::from(&String::from("foobar")), "foobar");
    assert_eq!(SubStr::from('x'), "x");
    let cowstr = SubStr::from("cowstr");
    assert_eq!(SubStr::from(cowstr), "cowstr");
    assert_eq!(SubStr::from(SubStr::from("cowstr")), "cowstr");
}

#[mutants::skip]
impl Debug for SubStr {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.debug_struct("SubStr")
            .field("origin", &self.origin)
            .field("substr", unsafe { &self.substr.as_ref() })
            .finish()
    }
}

impl Eq for SubStr {}

impl ops::Index<ops::RangeFull> for SubStr {
    type Output = str;

    #[inline]
    fn index(&self, _index: ops::RangeFull) -> &str {
        self
    }
}

impl ops::Index<ops::Range<usize>> for SubStr {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::Range<usize>) -> &str {
        &(**self)[index]
    }
}

impl ops::Index<ops::RangeFrom<usize>> for SubStr {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::RangeFrom<usize>) -> &str {
        &(**self)[index]
    }
}

impl ops::Index<ops::RangeTo<usize>> for SubStr {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::RangeTo<usize>) -> &str {
        &(**self)[index]
    }
}

impl ops::Index<ops::RangeInclusive<usize>> for SubStr {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
        &(**self)[index]
    }
}

impl ops::Index<ops::RangeToInclusive<usize>> for SubStr {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
        &(**self)[index]
    }
}

#[test]
fn index() {
    let substr = SubStr::from("fööbär");

    assert_eq!(&substr[..], "fööbär");
    assert_eq!(&substr[5..8], "bä");
    assert_eq!(&substr[5..], "bär");
    assert_eq!(&substr[..6], "fööb");
    assert_eq!(&substr[5..=8], "bär");
    assert_eq!(&substr[..=4], "föö");
}

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

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

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

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

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

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

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

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

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

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

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

#[allow(clippy::disallowed_names)]
#[test]
fn partial_eq() {
    let foo = SubStr::from("foo");
    let foo2 = SubStr::from("foo");
    let bar = SubStr::from("bar");
    let cowfoo = CowStr::from("foo");
    let cowbar = CowStr::from("bar");

    assert_partial_eq!(foo, foo2, bar);
    assert_partial_eq!(foo, "foo", "bar");
    assert_partial_eq!(&foo, foo2, bar);
    assert_partial_eq!(&foo, "foo", "bar");
    assert_partial_eq!(foo, cowfoo, cowbar);
    assert_partial_eq!(&foo, cowfoo, cowbar);
}

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

impl PartialOrd for SubStr {
    #[mutants::skip] /* infallible, cant be coverage tested  */
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        (**self).partial_cmp(other)
    }
}

impl PartialOrd<&str> for SubStr {
    #[mutants::skip] /* infallible, cant be coverage tested  */
    #[inline]
    fn partial_cmp(&self, other: &&str) -> Option<std::cmp::Ordering> {
        (**self).partial_cmp(*other)
    }
}

impl PartialOrd<SubStr> for &str {
    #[mutants::skip] /* infallible, cant be coverage tested  */
    #[inline]
    fn partial_cmp(&self, other: &SubStr) -> Option<std::cmp::Ordering> {
        (**self).partial_cmp(other)
    }
}

impl PartialOrd<CowStr> for SubStr {
    #[mutants::skip] /* infallible, cant be coverage tested  */
    #[inline]
    fn partial_cmp(&self, other: &CowStr) -> Option<std::cmp::Ordering> {
        (**self).partial_cmp(other)
    }
}

impl PartialOrd<SubStr> for CowStr {
    #[mutants::skip] /* infallible, cant be coverage tested  */
    #[inline]
    fn partial_cmp(&self, other: &SubStr) -> Option<std::cmp::Ordering> {
        (**self).partial_cmp(other)
    }
}

#[test]
fn partial_ord() {
    let a = SubStr::from("a");
    let b = SubStr::from("b");
    let c = SubStr::from("c");
    let cowa = CowStr::from("a");
    let cowc = CowStr::from("c");
    assert_partial_ord!(a, b, c);
    assert_partial_ord!("a", b, "c");
    assert_partial_ord!(cowa, b, cowc);
}

impl FromStr for SubStr {
    type Err = core::convert::Infallible;
    #[inline]
    fn from_str(s: &str) -> Result<SubStr, Self::Err> {
        Ok(SubStr::from(s))
    }
}

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

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

#[allow(clippy::disallowed_names)]
#[test]
fn as_ref() {
    let foo = SubStr::from("foo");
    let bar = SubStr::from("bar");
    assert_eq!(<substr::SubStr as AsRef<str>>::as_ref(&foo), "foo");
    assert_ne!(<substr::SubStr as AsRef<str>>::as_ref(&bar), "foo");
    assert_eq!(
        <substr::SubStr as AsRef<[u8]>>::as_ref(&foo),
        [102, 111, 111]
    );
    assert_ne!(<substr::SubStr as AsRef<[u8]>>::as_ref(&bar), [1, 2, 3]);
}

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

#[allow(clippy::disallowed_names)]
#[test]
fn borrow() {
    let foo = SubStr::from("foo");
    let bar = SubStr::from("bar");
    assert_eq!(<substr::SubStr as Borrow<str>>::borrow(&foo), "foo");
    assert_ne!(<substr::SubStr as Borrow<str>>::borrow(&bar), "foo");
}

/// A trait for converting a value to a `SubStr`.
///
/// This trait is automatically implemented for any type which implements the
/// [`Display`] trait. As such, `ToSubStr` shouldn't be implemented directly:
/// [`Display`] should be implemented instead, and you get the `ToSubStr`
/// implementation for free.
///
/// [`Display`]: fmt::Display
pub trait ToSubStr {
    /// Converts the given value to a `SubStr`.
    ///
    /// # Examples
    ///
    /// ```
    /// use cowstr::ToSubStr;
    ///
    /// let i = 5;
    /// assert_eq!(i.to_substr(), "5");
    /// ```
    fn to_substr(&self) -> SubStr;
}

impl Hash for SubStr {
    #[inline]
    #[mutants::skip] /* we just pretend it works */
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}

// PLANNED: specialization like stdlib does
impl<T: fmt::Display + ?Sized> ToSubStr for T {
    #[inline]
    fn to_substr(&self) -> SubStr {
        let mut buf = CowStr::new();
        fmt::write(&mut buf, format_args!("{}", self)).unwrap();
        SubStr::from(buf)
    }
}

#[test]
#[ignore]
fn debug() {
    let my_string = SubStr::from_static("static string");
    println!("static_string = {my_string:#?}");
    let my_string = SubStr::from("dynamic string");
    println!("dynamic_string = {my_string:#?}");
}

#[test]
fn empty() {
    assert_eq!(EMPTY_SUBSTR, "");
}

#[test]
fn from_ref() {
    let origin = CowStr::from("test string");
    let substr = SubStr::from(&origin);
    assert_eq!(substr, "test string");
}

#[test]
#[should_panic]
fn from_panic() {
    let origin = CowStr::from("test string");
    let _substr = SubStr::from_range(&origin, 10..100).unwrap();
}

#[test]
fn deref_static_static() {
    let static_origin = CowStr::from_static("test string");
    let static_substr = SubStr::from(&static_origin);
    assert_eq!(static_substr.deref_static(), Ok("test string"));
}

#[test]
fn deref_static_dynamic() {
    let dynamic_origin = CowStr::from("test string");
    let dynamic_substr = SubStr::from(&dynamic_origin);
    assert_eq!(dynamic_substr.deref_static(), Err("test string"));
}

#[test]
fn same_origin() {
    let origin = CowStr::from("foobar");
    let sub1 = SubStr::from_range(&origin, 0..3).unwrap();
    let sub2 = SubStr::from_range(&origin, 3..6).unwrap();
    assert_eq!(sub1, "foo");
    assert_eq!(sub2, "bar");
    assert!(sub1.same_origin(&sub2));
}

#[test]
fn different_origin() {
    let sub1 = SubStr::from("foo");
    let sub2 = SubStr::from("bar");
    assert!(!sub1.same_origin(&sub2));
}

#[test]
fn clone_increments_refcount() {
    let sub1 = SubStr::from("foo");
    assert_eq!(sub1.origin().strong_count().unwrap().get(), 1);
    let sub2 = sub1.clone();
    assert!(sub1.same_origin(&sub2));
    assert_eq!(sub1.origin().strong_count().unwrap().get(), 2);
    assert_eq!(sub2.origin().strong_count().unwrap().get(), 2);
}