cowstr 0.6.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
use std::borrow::Borrow;
use std::fmt;
use std::hash::Hash;
use std::hash::Hasher;
use std::num::NonZeroUsize;
use std::ops::Deref;
use std::ptr::NonNull;

use crate::*;

/// A shared string that can be either static or dynamic with copy-on-write semantic.
/// Functions that do copy-on-write are marked as **copy-on-write** below.
#[repr(transparent)]
#[derive(Debug, Eq)]
pub struct CowStr(CowStrInner);

#[derive(Debug, Eq, PartialEq)]
enum CowStrInner {
    /// A static string can be shared immutably without reference counting.
    Static(&'static str),
    /// Shared strings are reference counted String.
    Shared(SharedInner),
}

impl CowStrInner {
    /// Creates a shared/recounted inner from a `RcString` pointer. This also handles the case
    /// when the allocation failed where None was returned from the `RcString` constructors.
    #[inline]
    fn new_shared(ptr: Option<NonNull<RcString>>) -> CowStrInner {
        CowStrInner::Shared(SharedInner(ptr.expect("Out of Memory")))
    }
}

impl CowStr {
    /// Creates a new mutable empty `CowStr`.
    #[must_use]
    pub fn new() -> Self {
        CowStr(CowStrInner::new_shared(RcString::allocate(0)))
    }

    /// Creates a new mutable empty `CowStr` with at least as much pre-allocated capacity.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        CowStr(CowStrInner::new_shared(RcString::allocate(capacity)))
    }

    /// Creates a new `CowStr` that references a static string.
    #[must_use]
    pub fn from_static(s: &'static str) -> Self {
        CowStr(CowStrInner::Static(s))
    }

    /// Gets a mutable reference to the underlying `RcString`, when the the `CowStr` is static
    /// or the reference count is more than one the String will be cloned. When the spare
    /// capacity is not sufficient the string will be resized. This is the copy-on-write
    /// operation.
    fn to_mut(&mut self, reserve: usize) -> &mut RcString {
        match self.rcstring() {
            Ok(r) if r.as_ref().strong_count() > 1 => {
                self.0 = CowStrInner::new_shared(RcString::from_str(r.as_str(), reserve));
            }
            Ok(r) if r.as_ref().spare_capacity() < reserve => {
                self.0 = CowStrInner::new_shared(RcString::grow(r.as_ptr(), reserve));
            }
            Err(s) => {
                self.0 = CowStrInner::new_shared(RcString::from_str(s, reserve));
            }
            Ok(_) => { /* Nothing to do */ }
        }

        if let CowStrInner::Shared(ref mut rc) = self.0 {
            debug_assert_eq!(rc.as_ref().strong_count(), 1);
            rc.as_mut()
        } else {
            /* this is really not reached, above we put a CowStrInner::Shared in place */
            unsafe { std::hint::unreachable_unchecked() }
        }
    }

    #[inline(always)]
    fn rcstring(&self) -> Result<&SharedInner, &str> {
        match &self.0 {
            CowStrInner::Static(s) => Err(s),
            CowStrInner::Shared(rc) => Ok(rc),
        }
    }

    /// pushes a single character to the end of the string. This is **copy-on-write**.
    pub fn push(&mut self, c: char) {
        self.to_mut(c.len_utf8()).push(c);
    }

    /// pushes a string slice to the end of the string. This is **copy-on-write**
    pub fn push_str(&mut self, s: &str) {
        self.to_mut(s.len()).push_str(s);
    }

    /// Create a `SubStr` that from a  complete `CowStr`.
    #[must_use]
    pub fn into_substr(self) -> SubStr {
        let substr = &self[..] as *const str;
        SubStr {
            string: self,
            substr,
        }
    }

    /// Create and `SubStr` as span of a `CowStr`.
    pub fn into_range(self, start: usize, end: usize) -> Result<SubStr, RangeError> {
        if let Some(substr) = self.get(start..end) {
            let substr = substr as *const str;
            Ok(SubStr {
                string: self,
                substr,
            })
        } else {
            Err(RangeError)
        }
    }

    /// Returns `Ok(&'static str)` when the underlying string has static lifetime and
    /// `Err(&'self str)` when it is dynamically allocated.
    pub fn deref_static(&self) -> Result<&'static str, &str> {
        match &self.0 {
            CowStrInner::Static(s) => Ok(s),
            CowStrInner::Shared(s) => Err(s.as_ref().as_str()),
        }
    }

    /// Returns the reference count of the underlying allocation. Will be 'None' when self
    /// refers to a static string.
    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    pub fn strong_count(&self) -> Option<NonZeroUsize> {
        match self.0 {
            CowStrInner::Static(_) => None,
            CowStrInner::Shared(r) => Some(NonZeroUsize::new(r.as_ref().strong_count()).unwrap()),
        }
    }

    /// Returns the string as string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self.deref_static() {
            Ok(s) | Err(s) => s,
        }
    }

    /// Returns the string as mutable string slice. This is **copy-on-write**.
    pub fn as_mut_str(&mut self) -> &mut str {
        self.to_mut(0).as_mut_str()
    }

    /// Returns the capacity of the string, for static strings this equals their length.
    ///
    /// ```
    /// # use cowstr::CowStr;
    /// let cowstr = CowStr::from_static("foobar");
    /// assert_eq!(cowstr.capacity(), 6);
    ///
    /// let cowstr = CowStr::with_capacity(100);
    /// assert!(cowstr.capacity() >= 100);
    /// ```
    #[must_use]
    pub fn capacity(&self) -> usize {
        match self.0 {
            CowStrInner::Static(s) => s.len(),
            CowStrInner::Shared(r) => r.as_ref().capacity(),
        }
    }

    /// Returns the spare capacity of the string, for static strings this is zero.
    ///
    /// ```
    /// # use cowstr::CowStr;
    /// let cowstr = CowStr::from_static("foobar");
    /// assert_eq!(cowstr.spare_capacity(), 0);
    ///
    /// let mut cowstr = CowStr::with_capacity(100);
    /// cowstr.push('x');
    /// assert!(cowstr.capacity() >= 99);
    /// ```
    #[must_use]
    pub fn spare_capacity(&self) -> usize {
        match self.0 {
            CowStrInner::Static(_) => 0,
            CowStrInner::Shared(r) => r.as_ref().spare_capacity(),
        }
    }

    /// Reserves space for at least additional bytes. This is **copy-on-write**.
    ///
    /// ```
    /// # use cowstr::CowStr;
    /// let mut cowstr = CowStr::from_static("foobar");
    /// assert_eq!(cowstr.spare_capacity(), 0);
    ///
    /// cowstr.reserve(100);
    /// assert!(cowstr.spare_capacity() >= 100);
    /// ```
    pub fn reserve(&mut self, additional: usize) {
        self.to_mut(additional);
    }

    /// Shrinks the capacity to `new_capacity` or `self.len()` whatever is larger. When `self`
    /// is already shared or static or `new_capacity` is larger than its current capacity then
    /// this is a no-op. The exact resulting capacity can still have some excess bytes for
    /// alignment.
    ///
    /// ```
    /// # use cowstr::CowStr;
    /// let mut cowstr = CowStr::with_capacity(1000);
    /// assert!(cowstr.capacity() >= 1000);
    ///
    /// cowstr.shrink_to(100);
    /// assert!(cowstr.capacity() >= 100);
    /// assert!(cowstr.capacity() < 1000);
    /// ```
    pub fn shrink_to(&mut self, new_capacity: usize) {
        match self.0 {
            CowStrInner::Shared(r) if r.as_ref().strong_count() == 1 => {
                self.0 = CowStrInner::new_shared(RcString::shrink(r.as_ptr(), new_capacity));
            }
            _ => { /* NOP */ }
        }
    }

    /// Shrinks the capacity to the minimum. This is just a convenience function calling `cowstr.shrink_to(0)`.
    pub fn shrink_to_fit(&mut self) {
        self.shrink_to(0);
    }

    /// Returns the string as bytes slice.
    ///
    /// ```
    /// # use cowstr::CowStr;
    /// let s = CowStr::from("hello");
    ///
    /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
    /// ```
    pub fn as_bytes(&self) -> &[u8] {
        self.as_str().as_bytes()
    }
}

impl Clone for CowStr {
    fn clone(&self) -> Self {
        match self.0 {
            CowStrInner::Static(s) => CowStr(CowStrInner::Static(s)),
            CowStrInner::Shared(rc) => {
                rc.as_ref().increment_strong_count();
                CowStr(CowStrInner::Shared(rc))
            }
        }
    }
}

impl Drop for CowStr {
    fn drop(&mut self) {
        match self.0 {
            CowStrInner::Shared(rc) => unsafe {
                if rc.as_ref().decrement_strong_count() == 0 {
                    RcString::dealloc(rc.0);
                }
            },
            CowStrInner::Static(_) => { /* NOP */ }
        }
    }
}

impl Default for CowStr {
    fn default() -> Self {
        Self::new()
    }
}

impl From<&str> for CowStr {
    fn from(source: &str) -> Self {
        CowStr(CowStrInner::new_shared(RcString::from_str(source, 0)))
    }
}

/// `CowStr` dereferences to `&str`.
impl Deref for CowStr {
    type Target = str;

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

impl AsRef<str> for CowStr {
    fn as_ref(&self) -> &str {
        self
    }
}

impl Borrow<str> for CowStr {
    fn borrow(&self) -> &str {
        self
    }
}

impl PartialEq for CowStr {
    fn eq(&self, other: &Self) -> bool {
        self.as_ref() == other.as_ref()
    }
}

impl PartialOrd for CowStr {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.as_ref().partial_cmp(other.as_ref())
    }
}

impl Ord for CowStr {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_ref().cmp(other.as_ref())
    }
}

impl Hash for CowStr {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}

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

/// Always valid pointer to a `RcString`.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
struct SharedInner(NonNull<RcString>);

impl SharedInner {
    #[inline]
    fn as_ptr(&self) -> NonNull<RcString> {
        self.0
    }

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

    #[inline]
    fn as_ref(&self) -> &RcString {
        unsafe { self.0.as_ref() }
    }

    #[inline]
    fn as_mut(&mut self) -> &mut RcString {
        unsafe { self.0.as_mut() }
    }
}

#[test]
fn smoke() {
    let _empty_string = CowStr::new();
    let _static_string = CowStr::from_static("test string");
    let _dynamic_string = CowStr::from("test string");
}

#[test]
#[should_panic(expected = "Capacity overflow")]
fn over_capacity() {
    let _boom = CowStr::with_capacity(usize::MAX);
}

#[test]
#[cfg(not(miri))] // miri doesn't like this test
#[should_panic(expected = "Out of Memory")]
fn allocation_failure() {
    let _boom = CowStr::with_capacity(usize::MAX - 1000);
}

#[test]
fn push_char() {
    let mut my_string = CowStr::from_static("test string");

    my_string.push(' ');
    assert_eq!(&*my_string, "test string ");
    my_string.push('1');
    my_string.push('2');
    my_string.push('3');
    my_string.push('4');
    my_string.push('5');
    my_string.push('6');
    my_string.push('7');
    my_string.push('8');
    assert_eq!(&*my_string, "test string 12345678");
}

#[test]
fn push_str() {
    let mut my_string = CowStr::from_static("test string");

    my_string.push_str(" foo");
    assert_eq!(&*my_string, "test string foo");

    my_string.push_str(" bar");
    assert_eq!(&*my_string, "test string foo bar");
}

#[test]
fn clone_static() {
    let my_string = CowStr::from_static("test string");
    assert_eq!(my_string.strong_count(), None);
    assert!(my_string.deref_static().is_ok());

    let my_string2 = my_string.clone();
    assert!(my_string.deref_static().is_ok());
    assert_eq!(&*my_string2, "test string");

    drop(my_string);
    assert_eq!(&*my_string2, "test string");
}

#[test]
fn clone_dynamic() {
    let my_string = CowStr::from("test string");

    let my_string2 = my_string.clone();
    assert_eq!(
        my_string.strong_count(),
        Some(NonZeroUsize::new(2).unwrap())
    );
    assert_eq!(
        my_string2.strong_count(),
        Some(NonZeroUsize::new(2).unwrap())
    );
    assert_eq!(&*my_string2, "test string");

    let my_string3 = my_string.clone();
    assert_eq!(
        my_string3.strong_count(),
        Some(NonZeroUsize::new(3).unwrap())
    );

    drop(my_string);
    assert_eq!(
        my_string2.strong_count(),
        Some(NonZeroUsize::new(2).unwrap())
    );
}

#[test]
fn cmp() {
    let my_static_string = CowStr::from_static("test string");
    let my_dynamic_string = CowStr::from("test string");
    let my_dynamic_string2 = CowStr::from("test string");
    assert_eq!(my_static_string, my_dynamic_string);
    assert_eq!(my_dynamic_string, my_dynamic_string2);
}

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