cowstr 1.0.0-beta2

Copy-on-Write shared strings
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
use constptr::ConstPtr;
use std::borrow::Borrow;
use std::fmt;
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(Debug, Clone)]
pub struct SubStr {
    string: CowStr,
    substr: ConstPtr<str>,
}

// `SubStr` are always 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 {
            string: from.clone(),
            substr: ConstPtr::from(&from[..]),
        }
    }

    /// Create and `SubStr` from a `&str` that must be contained an initial `CowStr`.  This is
    /// useful when parsing or splitting a &str that is obtained from a `CowStr`. 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`"
        );
        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 {
                string: 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]
    #[must_use]
    #[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`.
    ///
    /// # Panics
    ///
    /// The range is wider than `from` or does not lie on utf-8 character boundaries.
    ///
    /// # Example
    ///
    /// ```
    /// # use cowstr::*;
    /// let origin = SubStr::from("this is a test string");
    /// let substr = SubStr::sub_range(&origin, 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>,
    {
        if let Some(substr) = unsafe { self.substr.as_ref() }.get(range) {
            Ok(SubStr {
                string: self.string.clone(),
                // Safety: we got a valid 'Some(substr)' above.
                substr: unsafe { ConstPtr::new_unchecked(substr) },
            })
        } else {
            Err(Error::Range)
        }
    }

    /// 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 {
            string: 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.string.deref_static() {
            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.string
    }

    /// 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 {
            string: 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.string, 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 {
            string: 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))
    }
}

#[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");
}

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
    }
}

#[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()
    }
}

#[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
    }
}

#[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;
}

// 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]
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);
}