string_newtype/
string.rs

1pub type StringBuf<Marker> = crate::NewtypeBuf<Marker, String>;
2pub type StringRef<Marker> = crate::NewtypeRef<Marker, String>;
3
4impl<Marker> StringBuf<Marker> {
5    /// Creates a new empty buffer.
6    pub fn new() -> Self {
7        Self {
8            s: String::new(),
9            _phantom: std::marker::PhantomData,
10        }
11    }
12
13    /// Creates a new empty buffer with at least the specified capacity.
14    pub fn with_capacity(capacity: usize) -> Self {
15        Self {
16            s: String::with_capacity(capacity),
17            _phantom: std::marker::PhantomData,
18        }
19    }
20
21    /// Returns this buffer as a string slice.
22    pub fn as_str(&self) -> &str {
23        self.s.as_str()
24    }
25
26    //// Converts the buffer into a mutable slice.
27    pub fn as_mut_str(&mut self) -> &mut str {
28        self.s.as_mut_str()
29    }
30
31    /// Returns the length of this buffer.
32    pub fn len(&self) -> usize {
33        self.s.len()
34    }
35
36    /// Returns `true` if this buffer is empty.
37    pub fn is_empty(&self) -> bool {
38        self.s.is_empty()
39    }
40}
41
42impl<Marker> StringRef<Marker> {
43    /// Returns the length of this buffer.
44    pub fn len(&self) -> usize {
45        self.s.len()
46    }
47
48    /// Returns `true` if this buffer is empty.
49    pub fn is_empty(&self) -> bool {
50        self.s.is_empty()
51    }
52}
53
54#[cfg(test)]
55mod test {
56    use super::*;
57
58    #[test]
59    fn string_newtype() {
60        enum S {}
61        type SBuf = StringBuf<S>;
62        type SRef = StringRef<S>;
63
64        let s: SBuf = "Hello".into();
65        let s_ref: &SRef = &s;
66        let hello: &SRef = "Hello".into();
67        assert_eq!(hello, s_ref);
68    }
69
70    #[test]
71    fn asref() {
72        fn f(_: impl AsRef<str>) {}
73
74        let s: StringBuf<()> = "Hello".into();
75        let s_ref: &StringRef<()> = &s;
76
77        f(&s);
78        f(s_ref);
79    }
80
81    #[test]
82    fn tostring() {
83        let s: StringBuf<()> = "Hello".into();
84        let s_ref: &StringRef<()> = &s;
85
86        assert_eq!(s.to_string(), "Hello");
87        assert_eq!(s_ref.to_string(), "Hello");
88    }
89
90    #[test]
91    fn toowned() {
92        let s: StringBuf<()> = "Hello".into();
93        let s_ref: &StringRef<()> = &s;
94
95        let owned: StringBuf<()> = (*s_ref).to_owned();
96
97        assert_eq!(owned, s);
98    }
99}