jid/
parts.rs

1use alloc::borrow::{Cow, ToOwned};
2use alloc::string::{String, ToString};
3use core::borrow::Borrow;
4use core::fmt;
5use core::mem;
6use core::ops::Deref;
7use core::str::FromStr;
8
9#[cfg(feature = "serde")]
10use serde::{Deserialize, Serialize};
11
12use crate::{domain_check, node_check, resource_check};
13use crate::{BareJid, Error, Jid};
14
15macro_rules! def_part_parse_doc {
16    ($name:ident, $other:ident, $more:expr) => {
17        concat!(
18            "Parse a [`",
19            stringify!($name),
20            "`] from a `",
21            stringify!($other),
22            "`, copying its contents.\n",
23            "\n",
24            "If the given `",
25            stringify!($other),
26            "` does not conform to the restrictions imposed by `",
27            stringify!($name),
28            "`, an error is returned.\n",
29            $more,
30        )
31    };
32}
33
34macro_rules! def_part_into_inner_doc {
35    ($name:ident, $other:ident, $more:expr) => {
36        concat!(
37            "Consume the `",
38            stringify!($name),
39            "` and return the inner `",
40            stringify!($other),
41            "`.\n",
42            $more,
43        )
44    };
45}
46
47#[cfg(feature = "serde")]
48#[derive(Deserialize)]
49struct NodeDeserializer<'a>(Cow<'a, str>);
50
51#[cfg(feature = "serde")]
52impl TryFrom<NodeDeserializer<'_>> for NodePart {
53    type Error = Error;
54
55    fn try_from(deserializer: NodeDeserializer) -> Result<NodePart, Self::Error> {
56        Ok(NodePart::new(&deserializer.0)?.into_owned())
57    }
58}
59
60#[cfg(feature = "serde")]
61#[derive(Deserialize)]
62struct DomainDeserializer<'a>(Cow<'a, str>);
63
64#[cfg(feature = "serde")]
65impl TryFrom<DomainDeserializer<'_>> for DomainPart {
66    type Error = Error;
67
68    fn try_from(deserializer: DomainDeserializer) -> Result<DomainPart, Self::Error> {
69        Ok(DomainPart::new(&deserializer.0)?.into_owned())
70    }
71}
72
73#[cfg(feature = "serde")]
74#[derive(Deserialize)]
75struct ResourceDeserializer<'a>(Cow<'a, str>);
76
77#[cfg(feature = "serde")]
78impl TryFrom<ResourceDeserializer<'_>> for ResourcePart {
79    type Error = Error;
80
81    fn try_from(deserializer: ResourceDeserializer) -> Result<ResourcePart, Self::Error> {
82        Ok(ResourcePart::new(&deserializer.0)?.into_owned())
83    }
84}
85
86macro_rules! def_part_types {
87    (
88        $(#[$mainmeta:meta])*
89        pub struct $name:ident(String) use $check_fn:ident();
90
91        $(#[$refmeta:meta])*
92        pub struct ref $borrowed:ident(str);
93    ) => {
94        $(#[$mainmeta])*
95        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
96        #[repr(transparent)]
97        pub struct $name(pub(crate) String);
98
99        impl $name {
100            #[doc = def_part_parse_doc!($name, str, "Depending on whether the contents are changed by normalisation operations, this function either returns a copy or a reference to the original data.")]
101            #[allow(clippy::new_ret_no_self)]
102            pub fn new(s: &str) -> Result<Cow<'_, $borrowed>, Error> {
103                let part = $check_fn(s)?;
104                match part {
105                    Cow::Borrowed(v) => Ok(Cow::Borrowed($borrowed::from_str_unchecked(v))),
106                    Cow::Owned(v) => Ok(Cow::Owned(Self(v))),
107                }
108            }
109
110            #[doc = def_part_into_inner_doc!($name, String, "")]
111            pub fn into_inner(self) -> String {
112                self.0
113            }
114        }
115
116        impl FromStr for $name {
117            type Err = Error;
118
119            fn from_str(s: &str) -> Result<Self, Error> {
120                Ok(Self::new(s)?.into_owned())
121            }
122        }
123
124        impl fmt::Display for $name {
125            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126                <$borrowed as fmt::Display>::fmt(Borrow::<$borrowed>::borrow(self), f)
127            }
128        }
129
130        impl Deref for $name {
131            type Target = $borrowed;
132
133            fn deref(&self) -> &Self::Target {
134                Borrow::<$borrowed>::borrow(self)
135            }
136        }
137
138        impl AsRef<$borrowed> for $name {
139            fn as_ref(&self) -> &$borrowed {
140                Borrow::<$borrowed>::borrow(self)
141            }
142        }
143
144        impl AsRef<String> for $name {
145            fn as_ref(&self) -> &String {
146                &self.0
147            }
148        }
149
150        impl Borrow<$borrowed> for $name {
151            fn borrow(&self) -> &$borrowed {
152                $borrowed::from_str_unchecked(self.0.as_str())
153            }
154        }
155
156        // useful for use in hashmaps
157        impl Borrow<String> for $name {
158            fn borrow(&self) -> &String {
159                &self.0
160            }
161        }
162
163        // useful for use in hashmaps
164        impl Borrow<str> for $name {
165            fn borrow(&self) -> &str {
166                self.0.as_str()
167            }
168        }
169
170        impl<'x> TryFrom<&'x str> for $name {
171            type Error = Error;
172
173            fn try_from(s: &str) -> Result<Self, Error> {
174                Self::from_str(s)
175            }
176        }
177
178        impl From<&$borrowed> for $name {
179            fn from(other: &$borrowed) -> Self {
180                other.to_owned()
181            }
182        }
183
184        impl<'x> From<Cow<'x, $borrowed>> for $name {
185            fn from(other: Cow<'x, $borrowed>) -> Self {
186                other.into_owned()
187            }
188        }
189
190        $(#[$refmeta])*
191        #[repr(transparent)]
192        #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
193        pub struct $borrowed(pub(crate) str);
194
195        impl $borrowed {
196            pub(crate) fn from_str_unchecked(s: &str) -> &Self {
197                // SAFETY: repr(transparent) thing can be transmuted to/from
198                // its inner.
199                unsafe { mem::transmute(s) }
200            }
201
202            /// Access the contents as [`str`] slice.
203            pub fn as_str(&self) -> &str {
204                &self.0
205            }
206        }
207
208        impl Deref for $borrowed {
209            type Target = str;
210
211            fn deref(&self) -> &Self::Target {
212                &self.0
213            }
214        }
215
216        impl ToOwned for $borrowed {
217            type Owned = $name;
218
219            fn to_owned(&self) -> Self::Owned {
220                $name(self.0.to_string())
221            }
222        }
223
224        impl AsRef<str> for $borrowed {
225            fn as_ref(&self) -> &str {
226                &self.0
227            }
228        }
229
230        impl fmt::Display for $borrowed {
231            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232                write!(f, "{}", &self.0)
233            }
234        }
235    }
236}
237
238def_part_types! {
239    /// The [`NodePart`] is the optional part before the (optional) `@` in any
240    /// [`Jid`][crate::Jid], whether [`BareJid`][crate::BareJid] or
241    /// [`FullJid`][crate::FullJid].
242    ///
243    /// The corresponding slice type is [`NodeRef`].
244    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
245    #[cfg_attr(feature = "serde", serde(try_from = "NodeDeserializer"))]
246    pub struct NodePart(String) use node_check();
247
248    /// `str`-like type which conforms to the requirements of [`NodePart`].
249    ///
250    /// See [`NodePart`] for details.
251    #[cfg_attr(feature = "serde", derive(Serialize))]
252    pub struct ref NodeRef(str);
253}
254
255def_part_types! {
256    /// The [`DomainPart`] is the part between the (optional) `@` and the
257    /// (optional) `/` in any [`Jid`][crate::Jid], whether
258    /// [`BareJid`][crate::BareJid] or [`FullJid`][crate::FullJid].
259    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
260    #[cfg_attr(feature = "serde", serde(try_from = "DomainDeserializer"))]
261    pub struct DomainPart(String) use domain_check();
262
263    /// `str`-like type which conforms to the requirements of [`DomainPart`].
264    ///
265    /// See [`DomainPart`] for details.
266    #[cfg_attr(feature = "serde", derive(Serialize))]
267    pub struct ref DomainRef(str);
268}
269
270def_part_types! {
271    /// The [`ResourcePart`] is the optional part after the `/` in a
272    /// [`Jid`][crate::Jid]. It is mandatory in [`FullJid`][crate::FullJid].
273    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
274    #[cfg_attr(feature = "serde", serde(try_from = "ResourceDeserializer"))]
275    pub struct ResourcePart(String) use resource_check();
276
277    /// `str`-like type which conforms to the requirements of
278    /// [`ResourcePart`].
279    ///
280    /// See [`ResourcePart`] for details.
281    #[cfg_attr(feature = "serde", derive(Serialize))]
282    pub struct ref ResourceRef(str);
283}
284
285impl DomainRef {
286    /// Construct a bare JID (a JID without a resource) from this domain and
287    /// the given node (local part).
288    pub fn with_node(&self, node: &NodeRef) -> BareJid {
289        BareJid::from_parts(Some(node), self)
290    }
291}
292
293impl From<DomainPart> for BareJid {
294    fn from(other: DomainPart) -> Self {
295        BareJid {
296            inner: other.into(),
297        }
298    }
299}
300
301impl From<DomainPart> for Jid {
302    fn from(other: DomainPart) -> Self {
303        Jid {
304            normalized: other.0,
305            at: None,
306            slash: None,
307        }
308    }
309}
310
311impl<'x> From<&'x DomainRef> for BareJid {
312    fn from(other: &'x DomainRef) -> Self {
313        Self::from_parts(None, other)
314    }
315}
316
317impl NodeRef {
318    /// Construct a bare JID (a JID without a resource) from this node (the
319    /// local part) and the given domain.
320    pub fn with_domain(&self, domain: &DomainRef) -> BareJid {
321        BareJid::from_parts(Some(self), domain)
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn nodepart_comparison() {
331        let n1 = NodePart::new("foo").unwrap();
332        let n2 = NodePart::new("bar").unwrap();
333        let n3 = NodePart::new("foo").unwrap();
334        assert_eq!(n1, n3);
335        assert_ne!(n1, n2);
336    }
337
338    #[cfg(feature = "serde")]
339    #[test]
340    fn nodepart_serde() {
341        serde_test::assert_de_tokens(
342            &NodePart(String::from("test")),
343            &[
344                serde_test::Token::TupleStruct {
345                    name: "NodePart",
346                    len: 1,
347                },
348                serde_test::Token::BorrowedStr("test"),
349                serde_test::Token::TupleStructEnd,
350            ],
351        );
352
353        serde_test::assert_de_tokens(
354            &NodePart(String::from("test")),
355            &[
356                serde_test::Token::TupleStruct {
357                    name: "NodePart",
358                    len: 1,
359                },
360                serde_test::Token::String("test"),
361                serde_test::Token::TupleStructEnd,
362            ],
363        );
364
365        serde_test::assert_de_tokens_error::<NodePart>(
366            &[
367                serde_test::Token::TupleStruct {
368                    name: "NodePart",
369                    len: 1,
370                },
371                serde_test::Token::BorrowedStr("invalid@domain"),
372                serde_test::Token::TupleStructEnd,
373            ],
374            "localpart doesn’t pass nodeprep validation",
375        );
376    }
377
378    #[cfg(feature = "serde")]
379    #[test]
380    fn domainpart_serde() {
381        serde_test::assert_de_tokens(
382            &DomainPart(String::from("[::1]")),
383            &[
384                serde_test::Token::TupleStruct {
385                    name: "DomainPart",
386                    len: 1,
387                },
388                serde_test::Token::BorrowedStr("[::1]"),
389                serde_test::Token::TupleStructEnd,
390            ],
391        );
392
393        serde_test::assert_de_tokens(
394            &DomainPart(String::from("[::1]")),
395            &[
396                serde_test::Token::TupleStruct {
397                    name: "DomainPart",
398                    len: 1,
399                },
400                serde_test::Token::String("[::1]"),
401                serde_test::Token::TupleStructEnd,
402            ],
403        );
404
405        serde_test::assert_de_tokens(
406            &DomainPart(String::from("domain.example")),
407            &[
408                serde_test::Token::TupleStruct {
409                    name: "DomainPart",
410                    len: 1,
411                },
412                serde_test::Token::BorrowedStr("domain.example"),
413                serde_test::Token::TupleStructEnd,
414            ],
415        );
416
417        serde_test::assert_de_tokens_error::<DomainPart>(
418            &[
419                serde_test::Token::TupleStruct {
420                    name: "DomainPart",
421                    len: 1,
422                },
423                serde_test::Token::BorrowedStr("invalid@domain"),
424                serde_test::Token::TupleStructEnd,
425            ],
426            "domain doesn’t pass idna validation",
427        );
428    }
429
430    #[cfg(feature = "serde")]
431    #[test]
432    fn resourcepart_serde() {
433        serde_test::assert_de_tokens(
434            &ResourcePart(String::from("test")),
435            &[
436                serde_test::Token::TupleStruct {
437                    name: "ResourcePart",
438                    len: 1,
439                },
440                serde_test::Token::BorrowedStr("test"),
441                serde_test::Token::TupleStructEnd,
442            ],
443        );
444
445        serde_test::assert_de_tokens(
446            &ResourcePart(String::from("test")),
447            &[
448                serde_test::Token::TupleStruct {
449                    name: "ResourcePart",
450                    len: 1,
451                },
452                serde_test::Token::String("test"),
453                serde_test::Token::TupleStructEnd,
454            ],
455        );
456
457        serde_test::assert_de_tokens_error::<ResourcePart>(
458            &[
459                serde_test::Token::TupleStruct {
460                    name: "ResourcePart",
461                    len: 1,
462                },
463                serde_test::Token::BorrowedStr("🤖"),
464                serde_test::Token::TupleStructEnd,
465            ],
466            "resource doesn’t pass resourceprep validation",
467        );
468    }
469}