From bba7d624425da2c65a834bbd0e633b7577488cdf Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Fri, 26 Nov 2021 21:03:11 +0100 Subject: [PATCH] identifiers: Add `Rc` / `Arc` parsing constructors --- crates/ruma-identifiers/src/macros.rs | 20 +++++++++++++++ crates/ruma-identifiers/src/user_id.rs | 34 ++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/crates/ruma-identifiers/src/macros.rs b/crates/ruma-identifiers/src/macros.rs index 4953bf54..7396312c 100644 --- a/crates/ruma-identifiers/src/macros.rs +++ b/crates/ruma-identifiers/src/macros.rs @@ -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 + Into>, + ) -> Result, 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 + Into>, + ) -> Result, crate::Error> { + $validate_id(s.as_ref())?; + Ok($id::from_arc(s.into())) + } + } } opaque_identifier_common_impls!($id); diff --git a/crates/ruma-identifiers/src/user_id.rs b/crates/ruma-identifiers/src/user_id.rs index 32005b6a..d6dc7974 100644 --- a/crates/ruma-identifiers/src/user_id.rs +++ b/crates/ruma-identifiers/src/user_id.rs @@ -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`. + /// + /// [`parse_with_server_name`]: Self::parse_with_server_name + pub fn parse_with_server_name_rc( + id: impl AsRef + Into>, + server_name: &ServerName, + ) -> Result, 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`. + /// + /// [`parse_with_server_name`]: Self::parse_with_server_name + pub fn parse_with_server_name_arc( + id: impl AsRef + Into>, + server_name: &ServerName, + ) -> Result, 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]