summaryrefslogtreecommitdiffstats
path: root/vendor/kstring/src/backend.rs
blob: 3827082f1da9e392f9a22d43d29b24fd0dd1b0d5 (plain)
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
#[cfg(feature = "arc")]
pub(crate) type DefaultStr = crate::backend::ArcStr;
#[cfg(not(feature = "arc"))]
pub(crate) type DefaultStr = crate::backend::BoxedStr;

/// Fast allocations, O(n) clones
pub type BoxedStr = Box<str>;
static_assertions::assert_eq_size!(DefaultStr, BoxedStr);

/// Cross-thread, O(1) clones
pub type ArcStr = std::sync::Arc<str>;
static_assertions::assert_eq_size!(DefaultStr, ArcStr);

/// O(1) clones
pub type RcStr = std::rc::Rc<str>;
static_assertions::assert_eq_size!(DefaultStr, RcStr);

/// Abstract over different type of heap-allocated strings
pub trait HeapStr: std::fmt::Debug + Clone + private::Sealed {
    fn from_str(other: &str) -> Self;
    fn from_string(other: String) -> Self;
    fn from_boxed_str(other: BoxedStr) -> Self;
    fn as_str(&self) -> &str;
}

impl HeapStr for BoxedStr {
    #[inline]
    fn from_str(other: &str) -> Self {
        other.into()
    }

    #[inline]
    fn from_string(other: String) -> Self {
        other.into_boxed_str()
    }

    #[inline]
    fn from_boxed_str(other: BoxedStr) -> Self {
        other
    }

    #[inline]
    fn as_str(&self) -> &str {
        self
    }
}

impl HeapStr for ArcStr {
    #[inline]
    fn from_str(other: &str) -> Self {
        other.into()
    }

    #[inline]
    fn from_string(other: String) -> Self {
        other.into_boxed_str().into()
    }

    #[inline]
    fn from_boxed_str(other: BoxedStr) -> Self {
        other.into()
    }

    #[inline]
    fn as_str(&self) -> &str {
        self
    }
}

impl HeapStr for RcStr {
    #[inline]
    fn from_str(other: &str) -> Self {
        other.into()
    }

    #[inline]
    fn from_string(other: String) -> Self {
        other.into_boxed_str().into()
    }

    #[inline]
    fn from_boxed_str(other: BoxedStr) -> Self {
        other.into()
    }

    #[inline]
    fn as_str(&self) -> &str {
        self
    }
}

pub(crate) mod private {
    pub trait Sealed {}
    impl Sealed for super::BoxedStr {}
    impl Sealed for super::ArcStr {}
    impl Sealed for super::RcStr {}
}