identifiers: Move session ID validation out of separate validation crate
This commit is contained in:
parent
34ad27bdf5
commit
bf670fb814
@ -2,11 +2,42 @@
|
|||||||
|
|
||||||
use ruma_macros::IdZst;
|
use ruma_macros::IdZst;
|
||||||
|
|
||||||
|
use super::IdParseError;
|
||||||
|
|
||||||
/// A session ID.
|
/// A session ID.
|
||||||
///
|
///
|
||||||
/// Session IDs in Matrix are opaque character sequences of `[0-9a-zA-Z.=_-]`. Their length must
|
/// Session IDs in Matrix are opaque character sequences of `[0-9a-zA-Z.=_-]`. Their length must
|
||||||
/// must not exceed 255 characters.
|
/// must not exceed 255 characters.
|
||||||
#[repr(transparent)]
|
#[repr(transparent)]
|
||||||
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdZst)]
|
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdZst)]
|
||||||
#[ruma_id(validate = ruma_identifiers_validation::session_id::validate)]
|
#[ruma_id(validate = validate_session_id)]
|
||||||
pub struct SessionId(str);
|
pub struct SessionId(str);
|
||||||
|
|
||||||
|
const fn validate_session_id(s: &str) -> Result<(), IdParseError> {
|
||||||
|
if s.len() > 255 {
|
||||||
|
return Err(IdParseError::MaximumLengthExceeded);
|
||||||
|
} else if contains_invalid_byte(s.as_bytes()) {
|
||||||
|
return Err(IdParseError::InvalidCharacters);
|
||||||
|
} else if s.is_empty() {
|
||||||
|
return Err(IdParseError::Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn contains_invalid_byte(mut bytes: &[u8]) -> bool {
|
||||||
|
// non-const form:
|
||||||
|
//
|
||||||
|
// bytes.iter().all(|b| b.is_ascii_alphanumeric() || b".=_-".contains(&b))
|
||||||
|
loop {
|
||||||
|
if let Some((byte, rest)) = bytes.split_first() {
|
||||||
|
if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'=' | b'_' | b'-') {
|
||||||
|
bytes = rest;
|
||||||
|
} else {
|
||||||
|
break true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
break false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -12,7 +12,6 @@ pub mod room_id;
|
|||||||
pub mod room_id_or_alias_id;
|
pub mod room_id_or_alias_id;
|
||||||
pub mod room_version_id;
|
pub mod room_version_id;
|
||||||
pub mod server_name;
|
pub mod server_name;
|
||||||
pub mod session_id;
|
|
||||||
pub mod user_id;
|
pub mod user_id;
|
||||||
pub mod voip_version_id;
|
pub mod voip_version_id;
|
||||||
|
|
||||||
|
@ -1,13 +0,0 @@
|
|||||||
use crate::Error;
|
|
||||||
|
|
||||||
pub fn validate(s: &str) -> Result<(), Error> {
|
|
||||||
if s.len() > 255 {
|
|
||||||
return Err(Error::MaximumLengthExceeded);
|
|
||||||
} else if !s.bytes().all(|b| b.is_ascii_alphanumeric() || b".=_-".contains(&b)) {
|
|
||||||
return Err(Error::InvalidCharacters);
|
|
||||||
} else if s.is_empty() {
|
|
||||||
return Err(Error::Empty);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
Loading…
x
Reference in New Issue
Block a user