1use crate::LockError;
4
5#[derive(Clone, Debug, Eq, PartialEq)]
7pub struct LockKey {
8 resource: String,
9 token: String,
10}
11
12impl LockKey {
13 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 #[must_use]
29 pub fn resource(&self) -> &str {
30 &self.resource
31 }
32
33 #[must_use]
35 pub fn token(&self) -> &str {
36 &self.token
37 }
38}
39
40pub 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
55pub 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}