oml_storage/storage_id/
random_id.rs

1use crate::StorageId;
2use color_eyre::eyre::Result;
3use serde::{Deserialize, Serialize};
4use std::fmt;
5/// A nanoid-based random identifier
6///
7/// This ID type generates random, unique strings using the nanoid library.
8/// It's suitable for distributed systems where coordination is difficult.
9#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize, Hash)]
10pub struct RandomId(String);
11
12impl RandomId {
13    /// Create a new random ID
14    pub fn new() -> Self {
15        Self(nanoid::nanoid!())
16    }
17
18    /// Create from an existing string
19    pub fn from_str(s: &str) -> Self {
20        Self(s.to_string())
21    }
22
23    /// Get the inner string value
24    pub fn value(&self) -> &str {
25        &self.0
26    }
27}
28
29impl StorageId for RandomId {
30    fn from_string(s: &str) -> Result<Self> {
31        Ok(Self(s.to_string()))
32    }
33
34    fn generate_new(_previous: Option<&Self>) -> Self {
35        Self::new()
36    }
37
38    fn is_valid_format(_s: &str) -> bool {
39        // nanoid can be any string, so we don't need specific validation
40        // Could add length checks or character set validation if needed
41        true
42    }
43}
44
45impl fmt::Display for RandomId {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "{}", self.0)
48    }
49}