iri_string/template/string/
owned.rs

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
//! Owned `UriTemplateString`.

use core::fmt;

use alloc::borrow::Cow;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::borrow::ToOwned;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::boxed::Box;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::string::String;

use crate::template::error::{CreationError, Error, ErrorKind};
use crate::template::parser::validate_template_str;
use crate::template::string::UriTemplateStr;

/// An owned slice of a URI template.
///
/// URI Template is defined by [RFC 6570].
///
/// Note that "URI Template" can also be used for IRI.
///
/// [RFC 6570]: https://www.rfc-editor.org/rfc/rfc6570.html
///
/// # Valid values
///
/// This type can have a URI template string.
// Note that `From<$ty> for {Arc,Rc}<$slice>` is currently not implemented since
// this won't reuse allocated memory and hides internal memory reallocation. See
// <https://github.com/lo48576/iri-string/issues/20#issuecomment-1105207849>.
// However, this is not decided with firm belief or opinion, so there would be
// a chance that they are implemented in future.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UriTemplateString {
    /// Inner data.
    inner: String,
}

impl UriTemplateString {
    /// Creates a new string without validation.
    ///
    /// This does not validate the given string, so it is caller's
    /// responsibility to ensure the given string is valid.
    ///
    /// # Safety
    ///
    /// The given string must be syntactically valid as `Self` type.
    /// If not, any use of the returned value or the call of this
    /// function itself may result in undefined behavior.
    #[inline]
    #[must_use]
    pub unsafe fn new_unchecked(s: alloc::string::String) -> Self {
        // The construction itself can be written in safe Rust, but
        // every other place including unsafe functions expects
        // `self.inner` to be syntactically valid as `Self`. In order to
        // make them safe, the construction should validate the value
        // or at least should require users to validate the value by
        // making the function `unsafe`.
        Self { inner: s }
    }

    /// Shrinks the capacity of the inner buffer to match its length.
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.inner.shrink_to_fit()
    }

    /// Returns the internal buffer capacity in bytes.
    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.inner.capacity()
    }

    /// Returns the borrowed IRI string slice.
    ///
    /// This is equivalent to `&*self`.
    #[inline]
    #[must_use]
    pub fn as_slice(&self) -> &UriTemplateStr {
        self.as_ref()
    }

    /// Appends the template string.
    #[inline]
    pub fn append(&mut self, other: &UriTemplateStr) {
        self.inner.push_str(other.as_str());
        debug_assert!(validate_template_str(self.as_str()).is_ok());
    }
}

impl AsRef<str> for UriTemplateString {
    #[inline]
    fn as_ref(&self) -> &str {
        &self.inner
    }
}

impl AsRef<UriTemplateStr> for UriTemplateString {
    #[inline]
    fn as_ref(&self) -> &UriTemplateStr {
        // SAFETY: `UriTemplateString and `UriTemplateStr` requires same validation,
        // so the content of `self: &UriTemplateString` must be valid as `UriTemplateStr`.
        unsafe { UriTemplateStr::new_always_unchecked(AsRef::<str>::as_ref(self)) }
    }
}

impl core::borrow::Borrow<str> for UriTemplateString {
    #[inline]
    fn borrow(&self) -> &str {
        self.as_ref()
    }
}

impl core::borrow::Borrow<UriTemplateStr> for UriTemplateString {
    #[inline]
    fn borrow(&self) -> &UriTemplateStr {
        self.as_ref()
    }
}

impl ToOwned for UriTemplateStr {
    type Owned = UriTemplateString;

    #[inline]
    fn to_owned(&self) -> Self::Owned {
        self.into()
    }
}

impl From<&'_ UriTemplateStr> for UriTemplateString {
    #[inline]
    fn from(s: &UriTemplateStr) -> Self {
        // This is safe because `s` must be valid.
        Self {
            inner: alloc::string::String::from(s.as_str()),
        }
    }
}

impl From<UriTemplateString> for alloc::string::String {
    #[inline]
    fn from(s: UriTemplateString) -> Self {
        s.inner
    }
}

impl<'a> From<UriTemplateString> for Cow<'a, UriTemplateStr> {
    #[inline]
    fn from(s: UriTemplateString) -> Cow<'a, UriTemplateStr> {
        Cow::Owned(s)
    }
}

impl From<UriTemplateString> for Box<UriTemplateStr> {
    #[inline]
    fn from(s: UriTemplateString) -> Box<UriTemplateStr> {
        let inner: String = s.into();
        let buf = Box::<str>::from(inner);
        // SAFETY: `UriTemplateStr` has `repr(transparent)` attribute, so
        // the memory layouts of `Box<str>` and `Box<UriTemplateStr>` are
        // compatible. Additionally, `UriTemplateString` and `UriTemplateStr`
        // require the same syntax.
        unsafe {
            let raw: *mut str = Box::into_raw(buf);
            Box::<UriTemplateStr>::from_raw(raw as *mut UriTemplateStr)
        }
    }
}

impl TryFrom<&'_ str> for UriTemplateString {
    type Error = Error;

    #[inline]
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        <&UriTemplateStr>::try_from(s).map(Into::into)
    }
}

impl TryFrom<&'_ [u8]> for UriTemplateString {
    type Error = Error;

    #[inline]
    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        let s = core::str::from_utf8(bytes)
            .map_err(|e| Error::new(ErrorKind::InvalidUtf8, e.valid_up_to()))?;
        <&UriTemplateStr>::try_from(s).map(Into::into)
    }
}

impl core::convert::TryFrom<alloc::string::String> for UriTemplateString {
    type Error = CreationError<String>;

    #[inline]
    fn try_from(s: alloc::string::String) -> Result<Self, Self::Error> {
        match <&UriTemplateStr>::try_from(s.as_str()) {
            Ok(_) => {
                // This is safe because `<&UriTemplateStr>::try_from(s)?` ensures
                // that the string `s` is valid.
                Ok(Self { inner: s })
            }
            Err(e) => Err(CreationError::new(e, s)),
        }
    }
}

impl alloc::str::FromStr for UriTemplateString {
    type Err = Error;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        TryFrom::try_from(s)
    }
}

impl core::ops::Deref for UriTemplateString {
    type Target = UriTemplateStr;

    #[inline]
    fn deref(&self) -> &UriTemplateStr {
        self.as_ref()
    }
}

impl_cmp!(str, UriTemplateStr, Cow<'_, str>);
impl_cmp!(str, &UriTemplateStr, Cow<'_, str>);

impl_cmp!(str, str, UriTemplateString);
impl_cmp!(str, &str, UriTemplateString);
impl_cmp!(str, Cow<'_, str>, UriTemplateString);
impl_cmp!(str, String, UriTemplateString);

impl fmt::Display for UriTemplateString {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Serde deserializer implementation.
#[cfg(feature = "serde")]
mod __serde_owned {
    use super::UriTemplateString;

    use core::fmt;

    #[cfg(all(feature = "alloc", feature = "serde", not(feature = "std")))]
    use alloc::string::String;

    use serde::{
        de::{self, Visitor},
        Deserialize, Deserializer,
    };

    /// Custom owned string visitor.
    #[derive(Debug, Clone, Copy)]
    struct CustomStringVisitor;

    impl<'de> Visitor<'de> for CustomStringVisitor {
        type Value = UriTemplateString;

        #[inline]
        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("URI template string")
        }

        #[inline]
        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            <UriTemplateString as TryFrom<&str>>::try_from(v).map_err(E::custom)
        }

        #[cfg(feature = "serde")]
        #[inline]
        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            <UriTemplateString as TryFrom<String>>::try_from(v).map_err(E::custom)
        }
    }

    impl<'de> Deserialize<'de> for UriTemplateString {
        #[inline]
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_str(CustomStringVisitor)
        }
    }
}