hipstr 0.8.0

Yet another string for Rust: zero-cost borrow and slicing, inline representation for small strings, (atomic) reference counting
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
//! Cross-platform path.
//!
//! This module provides the [`HipPath`] type as well as the associated helper type [`RefMut`].

use alloc::fmt;
use core::hash::Hash;
use core::ops::{Deref, DerefMut};
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};

use crate::bytes::HipByt;
use crate::os_string::HipOsStr;
use crate::string::HipStr;
use crate::Backend;

mod cmp;
mod convert;

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

#[cfg(test)]
mod tests;

/// Smart path, i.e. shared and cheaply clonable path.
///
/// Internally used the same representations as [`HipByt`].
///
/// # Examples
///
/// You can create a `HipPath` from anything that implements [`OsStr`], typically:
///
/// - string slices ([`&str`], [`&OsStr`], [`&Path`]),
/// - owned strings ([`String`], [`OsString`], [`PathBuf`], [`Box<str>`][Box]),
/// - clone-on-write smart pointers ([`Cow`][std::borrow::Cow]) to string slice,
/// - “Hip”-strings ([`HipStr`], [`HipOsStr`], [`HipPath`]),
///
/// with [`From`]:
///
/// ```
/// # use hipstr::HipPath;
/// let hello = HipPath::from("Hello");
/// ```
///
/// When possible, `HipPath::from` takes ownership of the underlying string
/// buffer:
///
/// ```
/// # use hipstr::HipPath;
/// # use std::path::PathBuf;
/// let world_os = PathBuf::from("World");
/// let world = HipPath::from(world_os); // here there is only one heap-allocation
/// ```
///
/// For borrowing string slice, you can also use the no-copy [`HipPath::borrowed`]
/// (like [`Cow::Borrowed`](std::borrow::Cow)):
///
/// ```
/// # use hipstr::HipPath;
/// let hello = HipPath::borrowed("Hello, world!");
/// ```
///
/// # Representations
///
/// Like `HipByt`, `HipPath` has three possible internal representations:
///
/// * borrow
/// * inline string
/// * shared heap allocated string
///
/// [`&OsStr`]: std::ffi::OsStr
/// [`&Path`]: std::path::Path
/// [`String`]: std::string::String
/// [Box]: std::boxed::Box
/// [`HipStr`]: crate::string::HipStr
/// [`HipOsStr``]: crate::string::HipOsStr
#[repr(transparent)]
#[allow(clippy::module_name_repetitions)]
pub struct HipPath<'borrow, B>(HipOsStr<'borrow, B>)
where
    B: Backend;

impl<'borrow, B> HipPath<'borrow, B>
where
    B: Backend,
{
    /// Creates an empty `HipPath`.
    ///
    /// Function provided for [`OsString::new`] replacement.
    ///
    /// # ⚠️ Stability warning!
    ///
    /// The used representation of the empty string is unspecified.
    /// It may be *borrowed* or *inlined* but will never be allocated.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// let s = HipPath::new();
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self(HipOsStr::new())
    }

    /// Creates a new `HipPath` from an OS string slice without copying the
    /// slice.
    ///
    /// Requires only `impl AsRef<Path>`: it accepts `&str`, `&OsStr`, and
    /// `&Path` for instance.
    ///
    /// To create a `HipPath` from a `'static` string slice `const`-ly, see
    /// [`HipPath::from_static`].
    ///
    /// # Representation
    ///
    /// The created `HipPath` is _borrowed_.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// # use std::path::Path;
    /// let s = HipPath::borrowed("hello");
    /// assert_eq!(s, Path::new("hello"));
    /// ```
    #[must_use]
    #[inline]
    pub fn borrowed<P: AsRef<Path> + ?Sized>(value: &'borrow P) -> Self {
        Self(HipOsStr::borrowed(value.as_ref().as_os_str()))
    }

    /// Returns `true` if this `HipPath` uses the inline representation, `false` otherwise.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// let s = HipPath::borrowed("hello");
    /// assert!(!s.is_inline());
    ///
    /// let s = HipPath::from("hello");
    /// assert!(s.is_inline());
    ///
    /// let s = HipPath::from("hello".repeat(10));
    /// assert!(!s.is_inline());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_inline(&self) -> bool {
        self.0.is_inline()
    }

    /// Returns `true` if this `HipPath` is a static string borrow, `false` otherwise.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// let s = HipPath::borrowed("hello");
    /// assert!(s.is_borrowed());
    ///
    /// let s = HipPath::from("hello");
    /// assert!(!s.is_borrowed());
    ///
    /// let s = HipPath::from("hello".repeat(10));
    /// assert!(!s.is_borrowed());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_borrowed(&self) -> bool {
        self.0.is_borrowed()
    }

    /// Returns `true` if this `HipPath` is a shared heap-allocated string, `false` otherwise.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// let s = HipPath::borrowed("hello");
    /// assert!(!s.is_allocated());
    ///
    /// let s = HipPath::from("hello");
    /// assert!(!s.is_allocated());
    ///
    /// let s = HipPath::from("hello".repeat(10));
    /// assert!(s.is_allocated());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_allocated(&self) -> bool {
        self.0.is_allocated()
    }

    /// Converts `self` into a path slice with the `'borrow` lifetime if this
    /// `HipPath` is backed by a borrow.
    ///
    /// # Errors
    ///
    /// Returns `Err(self)` if this `HipPath` is not borrowed.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// # use std::path::Path;
    /// let borrowed: &'static Path = "hipstr".as_ref();
    /// let s = HipPath::borrowed(borrowed);
    /// let c = s.into_borrowed();
    /// assert_eq!(c, Ok(borrowed));
    /// assert!(std::ptr::eq(borrowed, c.unwrap()));
    /// ```
    #[inline]
    pub fn into_borrowed(self) -> Result<&'borrow Path, Self> {
        self.0.into_borrowed().map(Path::new).map_err(Self)
    }

    /// Returns the borrowed slice if this `Path` is actually borrowed, `None`
    /// otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// # use std::path::Path;
    /// let abc: &'static Path = Path::new("abc");
    /// let s = HipPath::borrowed(abc);
    /// let c: Option<&'static Path> = s.as_borrowed();
    /// assert_eq!(c, Some(abc));
    /// assert!(std::ptr::eq(abc, c.unwrap()));
    ///
    /// let s2 = HipPath::from(abc);
    /// assert!(s2.as_borrowed().is_none());
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_borrowed(&self) -> Option<&'borrow Path> {
        match self.0.as_borrowed() {
            Some(slice) => {
                // SAFETY: type invariant
                // `transmute` used in order to be "const"
                // `Path` is *transparent*
                Some(unsafe { core::mem::transmute::<&OsStr, &Path>(slice) })
            }
            None => None,
        }
    }

    /// Converts a `HipPath` into a `HipOsStr`.
    ///
    /// It consumes the `HipPath` without copying the content
    /// (if [shared][HipPath::is_allocated] or [borrowed][HipPath::is_borrowed]).
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// # use std::path::Path;
    /// let s = HipPath::from("hello");
    /// let b = s.into_os_str();
    ///
    /// assert_eq!(b, Path::new("hello"));
    /// ```
    #[allow(clippy::missing_const_for_fn)] // cannot const it for now, clippy bug
    #[must_use]
    pub fn into_os_str(self) -> HipOsStr<'borrow, B> {
        self.0
    }

    /// Yields a [`Path`] slice of the entire `HipPath`.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// # use std::path::Path;
    /// let s = HipPath::from("foobar");
    ///
    /// assert_eq!(Path::new("foobar"), s.as_path());
    /// ```
    #[inline]
    #[must_use]
    pub fn as_path(&self) -> &Path {
        Path::new(self.0.as_os_str())
    }

    /// Yields an [`OsStr`] slice of the entire `HipPath`.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// # use std::path::Path;
    /// let s = HipPath::from("foobar");
    ///
    /// assert_eq!(Path::new("foobar"), s.as_os_str());
    /// ```
    #[inline]
    #[must_use]
    pub fn as_os_str(&self) -> &OsStr {
        self.0.as_os_str()
    }

    /// Returns the maximal length (in bytes) of inline string.
    #[inline]
    #[must_use]
    pub const fn inline_capacity() -> usize {
        HipByt::<B>::inline_capacity()
    }

    /// Returns the total number of bytes the backend can hold.
    ///
    /// # Example
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// let mut s: String = String::with_capacity(42);
    /// s.extend('a'..='z');
    /// let string = HipPath::from(s);
    /// assert_eq!(string.as_os_str().len(), 26);
    /// assert_eq!(string.capacity(), 42);
    ///
    /// let string2 = string.clone();
    /// assert_eq!(string.capacity(), 42);
    /// ```
    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.0.capacity()
    }

    /// Converts `self` into an [`OsString`] without clone or allocation if possible.
    ///
    /// # Errors
    ///
    /// Returns `Err(self)` if it is impossible to take ownership of the string
    /// backing this `HipPath`.
    #[inline]
    pub fn into_os_string(self) -> Result<OsString, Self> {
        self.0.into_os_string().map_err(Self)
    }

    /// Converts `self` into a [`PathBuf`] without clone or allocation if possible.
    ///
    /// # Errors
    ///
    /// Returns `Err(self)` if it is impossible to take ownership of the string
    /// backing this `HipPath`.
    #[inline]
    pub fn into_path_buf(self) -> Result<PathBuf, Self> {
        self.0.into_os_string().map(PathBuf::from).map_err(Self)
    }

    /// Returns a mutable handle to the underlying [`PathBuf`].
    ///
    /// This operation may reallocate a new buffer if either:
    ///
    /// - the representation is not an allocated buffer (inline array or borrow),
    /// - the underlying buffer is shared.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hipstr::HipPath;
    /// # use std::path::Path;
    /// let mut s = HipPath::borrowed("abc");
    /// {
    ///     let mut r = s.mutate();
    ///     r.push("def");
    ///     assert_eq!(&*r, Path::new("abc/def"));
    /// }
    /// assert_eq!(s, Path::new("abc/def"));
    /// ```
    #[inline]
    #[must_use]
    pub fn mutate(&mut self) -> RefMut<'_, 'borrow, B> {
        let owned = self.take_path_buf();
        RefMut {
            result: self,
            owned,
        }
    }

    fn take_path_buf(&mut self) -> PathBuf {
        PathBuf::from(self.0.take_os_string())
    }

    // /// Appends a given string slice onto the end of this `HipPath`.
    // ///
    // /// # Examples
    // ///
    // /// Basic usage:
    // ///
    // /// ```
    // /// # use hipstr::HipPath;
    // /// let mut s = HipPath::from("cork");
    // /// s.push_str("screw");
    // /// assert_eq!(s, "corkscrew");
    // /// ```
    // #[inline]
    // pub fn push_str(&mut self, addition: impl AsRef<OsStr>) {
    //     self.0.push_slice(addition.as_ref().as_encoded_bytes());
    // }

    // /// Appends the given [`char`] to the end of this `HipPath`.
    // ///
    // /// # Examples
    // ///
    // /// Basic usage:
    // ///
    // /// ```
    // /// # use hipstr::HipPath;
    // /// let mut s = HipPath::from("abc");
    // ///
    // /// s.push('1');
    // /// s.push('2');
    // /// s.push('3');
    // ///
    // /// assert_eq!(s, "abc123");
    // /// ```
    // #[inline]
    // pub fn push(&mut self, ch: char) {
    //     let mut data = [0; 4];
    //     let s = ch.encode_utf8(&mut data);
    //     self.0.push_slice(s.as_bytes());
    // }

    /// Makes the path owned, copying the data if it is actually borrowed.
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// let s: String = ('a'..'z').collect();
    /// let s2 = s.clone();
    /// let h = HipPath::borrowed(&s[..]);
    /// // drop(s); // err, s is borrowed
    /// let h = h.into_owned();
    /// drop(s); // ok
    /// assert_eq!(h.as_os_str(), s2.as_str());
    /// ```
    #[must_use]
    pub fn into_owned(self) -> HipPath<'static, B> {
        HipPath(self.0.into_owned())
    }

    /// Converts the `HipPath` into a [`HipStr`] if it contains valid Unicode data.
    ///
    /// # Errors
    ///
    /// If it contains invalid Unicode data, ownership of the original `HipPath` is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// # use hipstr::{HipStr,HipPath};
    /// let os = HipPath::from("foo");
    /// let s = os.into_str();
    /// assert_eq!(s, Ok(HipStr::from("foo")));
    /// ```
    #[inline]
    pub fn into_str(self) -> Result<HipStr<'borrow, B>, Self> {
        self.0.into_str().map_err(Self)
    }

    /// Shrinks the capacity of the string as much as possible.
    ///
    /// The capacity will remain at least as large as the actual length of the
    /// string.
    ///
    /// No-op if the representation is not allocated.
    ///
    /// # Representation stability
    ///
    /// The allocated representation may change to *inline* if the required
    /// capacity is smaller than the inline capacity.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hipstr::{HipOsStr, HipPath};
    /// let mut s = HipOsStr::with_capacity(100);
    /// s.push("abc");
    /// let mut p = HipPath::from(s);
    /// assert!(p.capacity() >= 100);
    /// p.shrink_to_fit();
    /// assert_eq!(p.capacity(), HipPath::inline_capacity());
    /// ```
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.0.shrink_to_fit();
    }

    /// Shrinks the capacity of the string with a lower bound.
    ///
    /// The capacity will remain at least as large as the given lower bound and
    /// the actual length of the string.
    ///
    /// No-op if the representation is not allocated.
    ///
    /// # Representation stability
    ///
    /// The allocated representation may change to *inline* if the required
    /// capacity is smaller than the inline capacity.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hipstr::{HipOsStr, HipPath};
    /// let s = HipOsStr::with_capacity(100);
    /// let mut p = HipPath::from(s);
    /// p.shrink_to(4);
    /// assert_eq!(p.capacity(), HipPath::inline_capacity());
    /// ```
    #[inline]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.0.shrink_to(min_capacity);
    }
}

impl<B> HipPath<'static, B>
where
    B: Backend,
{
    /// Creates a new `HipPath` from a static string slice without copying the slice.
    ///
    /// # Representation
    ///
    /// The created `HipPath` is _borrowed_.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use hipstr::HipPath;
    /// # use std::path::Path;
    /// let s = HipPath::from_static("hello");
    /// assert_eq!(s, Path::new("hello"));
    /// ```
    #[inline]
    #[must_use]
    pub const fn from_static(value: &'static str) -> Self {
        Self(HipOsStr::from_static(value))
    }
}

// Manual implementation needed to remove trait bound on B.
impl<B> Clone for HipPath<'_, B>
where
    B: Backend,
{
    #[inline]
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

// Manual implementation needed to remove trait bound on B.
impl<B> Default for HipPath<'_, B>
where
    B: Backend,
{
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<B> Deref for HipPath<'_, B>
where
    B: Backend,
{
    type Target = Path;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_path()
    }
}

impl<B> Hash for HipPath<'_, B>
where
    B: Backend,
{
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.as_path().hash(state);
    }
}

// Formatting

impl<B> fmt::Debug for HipPath<'_, B>
where
    B: Backend,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_path(), f)
    }
}

/// A wrapper type for a mutably borrowed [`PathBuf`] out of a [`HipPath`].
pub struct RefMut<'a, 'borrow, B>
where
    B: Backend,
{
    result: &'a mut HipPath<'borrow, B>,
    owned: PathBuf,
}

impl<B> fmt::Debug for RefMut<'_, '_, B>
where
    B: Backend,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.owned.fmt(f)
    }
}

impl<B> Drop for RefMut<'_, '_, B>
where
    B: Backend,
{
    fn drop(&mut self) {
        let owned = core::mem::take(&mut self.owned);
        *self.result = HipPath::from(owned);
    }
}

impl<B> Deref for RefMut<'_, '_, B>
where
    B: Backend,
{
    type Target = PathBuf;
    fn deref(&self) -> &Self::Target {
        &self.owned
    }
}

impl<B> DerefMut for RefMut<'_, '_, B>
where
    B: Backend,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.owned
    }
}