use std::num::NonZeroU16;
use ruma_identifiers_validation::{error::MxcUriError, mxc_uri::validate};
use ruma_macros::IdDst;
use super::ServerName;
type Result<T, E = MxcUriError> = std::result::Result<T, E>;
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
#[ruma_id(smallvec_inline_bytes = 60)]
pub struct MxcUri(str);
impl MxcUri {
pub fn media_id(&self) -> Result<&str> {
self.parts().map(|(_, s)| s)
}
pub fn server_name(&self) -> Result<&ServerName> {
self.parts().map(|(s, _)| s)
}
pub fn parts(&self) -> Result<(&ServerName, &str)> {
self.extract_slash_idx().map(|idx| {
(
ServerName::from_borrowed_unchecked(&self.as_str()[6..idx.get() as usize]),
&self.as_str()[idx.get() as usize + 1..],
)
})
}
pub fn validate(&self) -> Result<()> {
self.extract_slash_idx().map(|_| ())
}
#[inline(always)]
pub fn is_valid(&self) -> bool {
self.validate().is_ok()
}
#[inline(always)]
fn extract_slash_idx(&self) -> Result<NonZeroU16> {
validate(self.as_str())
}
}
#[cfg(test)]
mod tests {
use ruma_identifiers_validation::error::MxcUriError;
use super::{MxcUri, OwnedMxcUri};
#[test]
fn parse_mxc_uri() {
let mxc = <&MxcUri>::from("mxc://127.0.0.1/asd32asdfasdsd");
assert!(mxc.is_valid());
assert_eq!(
mxc.parts(),
Ok(("127.0.0.1".try_into().expect("Failed to create ServerName"), "asd32asdfasdsd"))
);
}
#[test]
fn parse_mxc_uri_without_media_id() {
let mxc = <&MxcUri>::from("mxc://127.0.0.1");
assert!(!mxc.is_valid());
assert_eq!(mxc.parts(), Err(MxcUriError::MissingSlash));
}
#[test]
fn parse_mxc_uri_without_protocol() {
assert!(!<&MxcUri>::from("127.0.0.1/asd32asdfasdsd").is_valid());
}
#[test]
fn serialize_mxc_uri() {
assert_eq!(
serde_json::to_string(<&MxcUri>::from("mxc://server/1234id"))
.expect("Failed to convert MxcUri to JSON."),
r#""mxc://server/1234id""#
);
}
#[test]
fn deserialize_mxc_uri() {
let mxc = serde_json::from_str::<OwnedMxcUri>(r#""mxc://server/1234id""#)
.expect("Failed to convert JSON to MxcUri");
assert_eq!(mxc.as_str(), "mxc://server/1234id");
assert!(mxc.is_valid());
assert_eq!(
mxc.parts(),
Ok(("server".try_into().expect("Failed to create ServerName"), "1234id"))
);
}
#[test]
fn parse_mxc_uri_valid_very_long_server_name() {
let server_name = "A".repeat(250);
let uri = format!("mxc://{}/1", server_name);
let mxc = <&MxcUri>::from(uri.as_str());
assert!(mxc.is_valid());
let (mxc_server_name, mxc_media_id) = mxc.parts().unwrap();
assert_eq!(*mxc_server_name, server_name);
assert_eq!(mxc_media_id, "1");
}
#[test]
fn parse_mxc_uri_invalid_too_long_server_name() {
let server_name = "A".repeat(265);
let uri = format!("mxc://{}/1", server_name);
let mxc = <&MxcUri>::from(uri.as_str());
assert!(!mxc.is_valid());
let _ = mxc.parts().unwrap_err();
}
}