diff --git a/quotesdb/Cargo.toml b/quotesdb/Cargo.toml index bf02279..72c404d 100644 --- a/quotesdb/Cargo.toml +++ b/quotesdb/Cargo.toml @@ -15,6 +15,10 @@ path = "src/bin/ui/main.rs" [dependencies] common = { path = "../common" } +uuid = { version = "1", features = ["v4", "serde"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +getrandom = { version = "0.4", features = ["wasm_js"] } [dev-dependencies] diff --git a/quotesdb/src/lib.rs b/quotesdb/src/lib.rs index 778809b..bbed29a 100644 --- a/quotesdb/src/lib.rs +++ b/quotesdb/src/lib.rs @@ -6,3 +6,48 @@ //! //! Use `#[cfg(not(target_arch = "wasm32"))]` for host-only items //! and `#[cfg(target_arch = "wasm32")]` for wasm-only items. + +/// Generates a new UUID v4 string for use as a database primary key. +/// +/// Returns a 36-character hyphenated UUID string. Compatible with both +/// native and `wasm32-unknown-unknown` targets (uses Web Crypto API via +/// `getrandom/wasm_js` on WASM). +/// +/// # Examples +/// +/// ``` +/// let id = quotesdb::generate_id(); +/// assert_eq!(id.len(), 36); +/// assert_eq!(id.chars().filter(|&c| c == '-').count(), 4); +/// ``` +pub fn generate_id() -> String { + uuid::Uuid::new_v4().to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_generate_id_length() { + let id = generate_id(); + assert_eq!(id.len(), 36, "UUID v4 must be 36 characters"); + } + + #[test] + fn test_generate_id_hyphen_count() { + let id = generate_id(); + assert_eq!( + id.chars().filter(|&c| c == '-').count(), + 4, + "UUID v4 must contain exactly 4 hyphens" + ); + } + + #[test] + fn test_generate_id_uniqueness() { + let id1 = generate_id(); + let id2 = generate_id(); + assert_ne!(id1, id2, "Two generated IDs must be different"); + } +}