use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub fn rest_username_expiry(username: &str, separator: char) -> Option<SystemTime> {
let timestamp = username.split(separator).next()?;
if timestamp.is_empty() || !timestamp.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let seconds: u64 = timestamp.parse().ok()?;
UNIX_EPOCH.checked_add(Duration::from_secs(seconds))
}
#[cfg(test)]
mod tests {
use super::*;
fn at(s: u64) -> Option<SystemTime> {
Some(UNIX_EPOCH + Duration::from_secs(s))
}
#[test]
fn the_timestamp_before_the_separator_is_the_expiry() {
assert_eq!(
rest_username_expiry("1800000600:host-7", ':'),
at(1_800_000_600)
);
assert_eq!(
rest_username_expiry("1800000600:a:b", ':'),
at(1_800_000_600)
);
assert_eq!(rest_username_expiry("1800000600", ':'), at(1_800_000_600));
assert_eq!(rest_username_expiry("1800000600-x", '-'), at(1_800_000_600));
assert_eq!(rest_username_expiry("0", ':'), at(0));
}
#[test]
fn a_username_without_a_leading_timestamp_has_none() {
for username in [
"",
":1800000600",
"alice",
"alice:1800000600",
"+1800000600",
" 1",
"1.5",
"18446744073709551616",
] {
assert_eq!(rest_username_expiry(username, ':'), None, "{username:?}");
}
assert_eq!(
rest_username_expiry("1800000600:x", '-'),
None,
"another separator"
);
}
}