Skip to main content

serenade_lock/
key.rs

1//! Lock resource validation and owner tokens.
2
3use crate::LockError;
4
5/// Resource name plus opaque owner token.
6#[derive(Clone, Debug, Eq, PartialEq)]
7pub struct LockKey {
8    resource: String,
9    token: String,
10}
11
12impl LockKey {
13    /// Builds a key after validating `resource`.
14    ///
15    /// # Errors
16    ///
17    /// Returns [`LockError::InvalidKey`] when `resource` is empty.
18    pub fn new(resource: impl Into<String>, token: impl Into<String>) -> Result<Self, LockError> {
19        let resource = resource.into();
20        validate_resource(&resource)?;
21        Ok(Self {
22            resource,
23            token: token.into(),
24        })
25    }
26
27    /// Lock resource name.
28    #[must_use]
29    pub fn resource(&self) -> &str {
30        &self.resource
31    }
32
33    /// Opaque owner token.
34    #[must_use]
35    pub fn token(&self) -> &str {
36        &self.token
37    }
38}
39
40/// Rejects empty resource names.
41///
42/// # Errors
43///
44/// Returns [`LockError::InvalidKey`] when `resource` is empty.
45pub fn validate_resource(resource: &str) -> Result<(), LockError> {
46    if resource.is_empty() {
47        return Err(LockError::InvalidKey {
48            key: resource.to_owned(),
49            message: "resource must not be empty".to_owned(),
50        });
51    }
52    Ok(())
53}
54
55/// Generates a random hex owner token.
56///
57/// # Errors
58///
59/// Returns [`LockError::Generation`] when the OS RNG fails.
60pub fn generate_lock_token() -> Result<String, LockError> {
61    let mut bytes = [0_u8; 16];
62    getrandom::fill(&mut bytes).map_err(|_| LockError::Generation)?;
63    Ok(bytes
64        .iter()
65        .fold(String::with_capacity(32), |mut out, byte| {
66            use std::fmt::Write as _;
67            let _ = write!(out, "{byte:02x}");
68            out
69        }))
70}