use crate::LockError;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LockKey {
resource: String,
token: String,
}
impl LockKey {
pub fn new(resource: impl Into<String>, token: impl Into<String>) -> Result<Self, LockError> {
let resource = resource.into();
validate_resource(&resource)?;
Ok(Self {
resource,
token: token.into(),
})
}
#[must_use]
pub fn resource(&self) -> &str {
&self.resource
}
#[must_use]
pub fn token(&self) -> &str {
&self.token
}
}
pub fn validate_resource(resource: &str) -> Result<(), LockError> {
if resource.is_empty() {
return Err(LockError::InvalidKey {
key: resource.to_owned(),
message: "resource must not be empty".to_owned(),
});
}
Ok(())
}
pub fn generate_lock_token() -> Result<String, LockError> {
let mut bytes = [0_u8; 16];
getrandom::fill(&mut bytes).map_err(|_| LockError::Generation)?;
Ok(bytes
.iter()
.fold(String::with_capacity(32), |mut out, byte| {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
out
}))
}