Skip to main content

fml_engine/
ids.rs

1//! New ids for `uuid()` and for resources `reference()` gives an id: random by default, or
2//! fixed by the caller so runs can be compared.
3
4use std::sync::atomic::{AtomicU64, Ordering};
5
6/// Makes the UUIDs a transform needs.
7pub trait IdGenerator {
8    /// A new UUID, lowercase.
9    fn uuid(&self) -> String;
10}
11
12/// Random (version 4) UUIDs.
13#[derive(Debug, Default, Clone, Copy)]
14pub struct RandomIds;
15
16impl IdGenerator for RandomIds {
17    fn uuid(&self) -> String {
18        uuid::Uuid::new_v4().to_string()
19    }
20}
21
22/// UUIDs counting up from zero (`00000000-0000-0000-0000-000000000001`, …), for tests and
23/// repeatable runs.
24#[derive(Debug, Default)]
25pub struct SequentialIds {
26    next: AtomicU64,
27}
28
29impl SequentialIds {
30    pub fn new() -> Self {
31        Self::default()
32    }
33}
34
35impl IdGenerator for SequentialIds {
36    fn uuid(&self) -> String {
37        let n = self.next.fetch_add(1, Ordering::Relaxed) + 1;
38        uuid::Uuid::from_u128(u128::from(n)).to_string()
39    }
40}