identifiers: Add Rc / Arc parsing constructors

This commit is contained in:
Jonas Platte 2021-11-26 21:03:11 +01:00
parent 6324034f03
commit bba7d62442
No known key found for this signature in database
GPG Key ID: CC154DE0E30B7C67
2 changed files with 54 additions and 0 deletions

View File

@ -217,6 +217,26 @@ macro_rules! opaque_identifier_validated {
Ok($id::from_owned(s.into()))
}
}
doc_concat! {
#[doc = concat!("Try parsing a `&str` into an `Rc<", stringify!($id), ">`.")]
pub fn parse_rc(
s: impl AsRef<str> + Into<std::rc::Rc<str>>,
) -> Result<std::rc::Rc<Self>, crate::Error> {
$validate_id(s.as_ref())?;
Ok($id::from_rc(s.into()))
}
}
doc_concat! {
#[doc = concat!("Try parsing a `&str` into an `Arc<", stringify!($id), ">`.")]
pub fn parse_arc(
s: impl AsRef<str> + Into<std::sync::Arc<str>>,
) -> Result<std::sync::Arc<Self>, crate::Error> {
$validate_id(s.as_ref())?;
Ok($id::from_arc(s.into()))
}
}
}
opaque_identifier_common_impls!($id);

View File

@ -1,5 +1,7 @@
//! Matrix user identifiers.
use std::{rc::Rc, sync::Arc};
use crate::{MatrixToRef, ServerName};
/// A Matrix user ID.
@ -51,6 +53,38 @@ impl UserId {
}
}
/// Variation of [`parse_with_server_name`] that returns `Rc<Self>`.
///
/// [`parse_with_server_name`]: Self::parse_with_server_name
pub fn parse_with_server_name_rc(
id: impl AsRef<str> + Into<Rc<str>>,
server_name: &ServerName,
) -> Result<Rc<Self>, crate::Error> {
let id_str = id.as_ref();
if id_str.starts_with('@') {
Self::parse_rc(id)
} else {
Ok(Self::from_rc(format!("@{}:{}", id_str, server_name).into()))
}
}
/// Variation of [`parse_with_server_name`] that returns `Arc<Self>`.
///
/// [`parse_with_server_name`]: Self::parse_with_server_name
pub fn parse_with_server_name_arc(
id: impl AsRef<str> + Into<Arc<str>>,
server_name: &ServerName,
) -> Result<Arc<Self>, crate::Error> {
let id_str = id.as_ref();
if id_str.starts_with('@') {
Self::parse_arc(id)
} else {
Ok(Self::from_arc(format!("@{}:{}", id_str, server_name).into()))
}
}
/// Returns the user's localpart.
pub fn localpart(&self) -> &str {
&self.as_str()[1..self.colon_idx() as usize]