bento-kit 0.1.1

A bento box of common Rust utilities: id generation, timing, masking
Documentation
//! UUID v4 / v7 helpers.

use uuid::Uuid;

/// Generate a random UUID v4 as a hyphenated string (36 chars).
///
/// ```
/// let id = bento_kit::id::uuid_v4();
/// assert_eq!(id.len(), 36);
/// ```
pub fn uuid_v4() -> String {
    Uuid::new_v4().to_string()
}

/// Generate a random UUID v4 without hyphens (32 hex chars).
///
/// Useful when you need a compact identifier (e.g. database keys, URL slugs).
pub fn uuid_v4_simple() -> String {
    Uuid::new_v4().simple().to_string()
}

/// Generate a UUID v7 (time-ordered, monotonic per millisecond) as a hyphenated string.
///
/// Prefer this over v4 for database primary keys: rows insert in roughly
/// chronological order, which keeps B-tree indexes hot at the right edge.
pub fn uuid_v7() -> String {
    Uuid::now_v7().to_string()
}

/// Generate a UUID v7 without hyphens.
pub fn uuid_v7_simple() -> String {
    Uuid::now_v7().simple().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn v4_has_correct_shape() {
        let id = uuid_v4();
        assert_eq!(id.len(), 36);
        assert_eq!(id.matches('-').count(), 4);
        // Version nibble for v4 sits at index 14.
        assert_eq!(id.chars().nth(14), Some('4'));
    }

    #[test]
    fn v4_simple_is_32_hex_chars() {
        let id = uuid_v4_simple();
        assert_eq!(id.len(), 32);
        assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn v4_values_are_unique() {
        let a = uuid_v4();
        let b = uuid_v4();
        assert_ne!(a, b);
    }

    #[test]
    fn v7_has_correct_shape() {
        let id = uuid_v7();
        assert_eq!(id.len(), 36);
        assert_eq!(id.chars().nth(14), Some('7'));
    }

    #[test]
    fn v7_is_time_ordered() {
        // Generate a batch and confirm they sort the same way they were generated.
        let ids: Vec<String> = (0..32).map(|_| uuid_v7()).collect();
        let mut sorted = ids.clone();
        sorted.sort();
        assert_eq!(
            ids, sorted,
            "v7 ids should be monotonic when generated back-to-back"
        );
    }
}