1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use crate::identifier::{Scru128Id, MAX_COUNTER, MAX_PER_SEC_RANDOM};

use std::time::{SystemTime, UNIX_EPOCH};

use rand::{rngs::StdRng, RngCore, SeedableRng};

/// Unix time in milliseconds at 2020-01-01 00:00:00+00:00.
pub const TIMESTAMP_BIAS: u64 = 1577836800000;

/// Represents a SCRU128 ID generator that encapsulates the monotonic counter and other internal
/// states.
///
/// # Examples
///
/// ```rust
/// use scru128::Scru128Generator;
///
/// let mut g = Scru128Generator::new();
/// println!("{}", g.generate());
/// println!("{}", g.generate().as_u128());
/// ```
///
/// Each generator instance generates monotonically ordered IDs, but multiple generators called
/// concurrently may produce unordered results unless explicitly synchronized. Use Rust's
/// synchronization mechanisms to control the scope of guaranteed monotonicity:
///
/// ```rust
/// use scru128::Scru128Generator;
/// use std::sync::{Arc, Mutex};
///
/// let g_shared = Arc::new(Mutex::new(Scru128Generator::new()));
///
/// let mut hs = Vec::new();
/// for i in 0..4 {
///     let g_shared = Arc::clone(&g_shared);
///     hs.push(std::thread::spawn(move || {
///         let mut g_local = Scru128Generator::new();
///         for _ in 0..4 {
///             println!("Shared generator: {}", g_shared.lock().unwrap().generate());
///             println!("Thread-local generator {}: {}", i, g_local.generate());
///         }
///     }));
/// }
///
/// for h in hs {
///     let _ = h.join();
/// }
/// ```
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Scru128Generator<R = StdRng> {
    ts_last_gen: u64,
    counter: u32,
    ts_last_sec: u64,
    per_sec_random: u32,
    n_clock_check_max: usize,
    rng: R,
}

impl Default for Scru128Generator {
    fn default() -> Self {
        Self::with_rng(StdRng::from_entropy())
    }
}

impl Scru128Generator {
    /// Creates a generator object with the default random number generator.
    pub fn new() -> Self {
        Self::with_rng(StdRng::from_entropy())
    }
}

impl<R: RngCore> Scru128Generator<R> {
    /// Creates a generator object with a specified random number generator. The specified random
    /// number generator should be cryptographically strong and securely seeded.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use scru128::Scru128Generator;
    ///
    /// let mut g = Scru128Generator::with_rng(rand::thread_rng());
    /// println!("{}", g.generate());
    /// ```
    pub fn with_rng(rng: R) -> Self {
        Self {
            /// Timestamp at last generation.
            ts_last_gen: 0,

            /// Counter at last generation.
            counter: 0,

            /// Timestamp at last renewal of per_sec_random.
            ts_last_sec: 0,

            /// Per-second random value at last generation.
            per_sec_random: 0,

            /// Maximum number of checking the system clock until it goes forward.
            n_clock_check_max: 1_000_000,

            rng,
        }
    }

    /// Generates a new SCRU128 ID object.
    pub fn generate(&mut self) -> Scru128Id {
        // update timestamp and counter
        let mut ts_now = get_msec_unixts();
        if ts_now > self.ts_last_gen {
            self.ts_last_gen = ts_now;
            self.counter = self.rng.next_u32() & MAX_COUNTER;
        } else {
            self.counter += 1;
            if self.counter > MAX_COUNTER {
                #[cfg(feature = "log")]
                log::info!("counter limit reached; will wait until clock goes forward");
                let mut n_clock_check = 0;
                while ts_now <= self.ts_last_gen {
                    ts_now = get_msec_unixts();
                    n_clock_check += 1;
                    if n_clock_check > self.n_clock_check_max {
                        #[cfg(feature = "log")]
                        log::warn!("reset state as clock did not go forward");
                        self.ts_last_sec = 0;
                        break;
                    }
                }
                self.ts_last_gen = ts_now;
                self.counter = self.rng.next_u32() & MAX_COUNTER;
            }
        }

        // update per_sec_random
        if self.ts_last_gen - self.ts_last_sec > 1000 {
            self.ts_last_sec = self.ts_last_gen;
            self.per_sec_random = self.rng.next_u32() & MAX_PER_SEC_RANDOM;
        }

        Scru128Id::from_fields(
            self.ts_last_gen - TIMESTAMP_BIAS,
            self.counter,
            self.per_sec_random,
            self.rng.next_u32(),
        )
    }
}

/// Returns the current unix time in milliseconds.
fn get_msec_unixts() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("clock may have gone backwards")
        .as_millis() as u64
}