Skip to main content

rig_core/
id.rs

1//! Non-cryptographic random identifiers and process-local run counters. Do
2//! not use generated IDs as secrets.
3//!
4//! ```
5//! let id = rig_core::id::generate();
6//! assert_eq!(id.len(), 21);
7//! ```
8
9use serde::{Deserialize, Serialize};
10use std::{
11    fmt,
12    num::NonZeroU64,
13    sync::atomic::{AtomicU64, Ordering},
14};
15
16/// URL-safe ASCII alphabet for random identifiers.
17const ALPHABET: &[u8; 64] = b"_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
18
19/// Number of characters returned by [`generate`].
20const DEFAULT_LEN: usize = 21;
21
22/// Generate a 21-character URL-safe random identifier. Not cryptographically
23/// secure; collisions are possible.
24pub fn generate() -> String {
25    std::iter::repeat_with(|| {
26        let idx = fastrand::usize(..ALPHABET.len());
27        ALPHABET.get(idx).copied().unwrap_or(b'_') as char
28    })
29    .take(DEFAULT_LEN)
30    .collect()
31}
32
33/// Process-local run identifier shared by that run's hook events, a nonzero
34/// counter serialized as its number. Not secret; add a host or session scope
35/// for cross-process correlation.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
37#[serde(transparent)]
38pub struct RunId(NonZeroU64);
39
40const _: () = assert!(std::mem::size_of::<Option<RunId>>() == std::mem::size_of::<u64>());
41
42impl RunId {
43    /// Mint the next run id. Values increase until wraparound and may then
44    /// repeat or collide with deserialized ids.
45    #[allow(clippy::new_without_default)]
46    pub fn new() -> Self {
47        static NEXT: AtomicU64 = AtomicU64::new(1);
48        // Zero is skipped, also after wraparound.
49        loop {
50            if let Some(raw) = NonZeroU64::new(NEXT.fetch_add(1, Ordering::Relaxed)) {
51                return Self(raw);
52            }
53        }
54    }
55}
56
57impl fmt::Display for RunId {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        fmt::Display::fmt(&self.0, f)
60    }
61}
62
63#[cfg(test)]
64mod tests;