1
//! UUID string generation - the intended mint for MARKER strings.
2
//!
3
//! Markers (`Dom::with_marker` + `CallbackInfo::get_node_id_by_marker`) are
4
//! app-chosen strings created at `layout()` time; what makes them work is that
5
//! they collide with *nothing* - not another widget, not another window, not a
6
//! hard-coded string in some library. A UUID gives that guarantee without any
7
//! coordination, so the pattern is:
8
//!
9
//! ```rust,ignore
10
//! // once, at layout() time (store it wherever the driving callback looks):
11
//! let marker = Uuid::short();
12
//! let bar = ProgressBar::create(0.0).dom().with_marker(Some(marker.clone()).into());
13
//! ```
14
//!
15
//! [`Uuid::v4`] returns the canonical hyphenated form (36 chars);
16
//! [`Uuid::short`] returns the same 128 bits as a 22-char flickrBase58 string
17
//! (the `short-uuid` encoding) - shorter, no hyphens, URL/log friendly.
18
//!
19
//! # These ids are DETERMINISTIC, not random
20
//!
21
//! Every id is a pure function of a process-local counter, so run the same
22
//! program twice and you get the same sequence of ids. That is all a marker
23
//! needs - it has to be unique among the strings alive in ONE process, and it
24
//! is: the mixing function is a bijection, so 2^63 mints collide zero times,
25
//! exactly rather than probabilistically.
26
//!
27
//! What it is NOT: unpredictable, or unique across processes and machines. Do
28
//! not use these to identify a client to a server, as a security token, or as
29
//! a database key that two processes might mint independently. The crate
30
//! carries no randomness source on purpose - `uuid`'s `v4` needs one, and on
31
//! `wasm32-unknown-unknown` there isn't one without pulling in `getrandom`'s
32
//! JS shim, which broke every wasm consumer of azul-layout 0.0.15.
33

            
34
use core::sync::atomic::{AtomicU64, Ordering};
35

            
36
use azul_css::AzString;
37

            
38
/// flickrBase58 — base58 without the look-alikes `0`, `O`, `I` and `l`.
39
const BASE58: &[u8; 58] = b"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
40

            
41
/// Mint tick. Every id is a pure function of its tick, so the sequence is the
42
/// same on every run — deterministic, not random.
43
static TICK: AtomicU64 = AtomicU64::new(0);
44

            
45
/// The splitmix64 finalizer. Every step (xor-shift-right, multiply by an odd
46
/// constant) is invertible, so the whole function is a BIJECTION on `u64`:
47
/// distinct ticks give distinct outputs, which is what makes the no-collision
48
/// guarantee below exact rather than probabilistic.
49
20256
const fn mix64(mut z: u64) -> u64 {
50
20256
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
51
20256
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
52
20256
    z ^ (z >> 31)
53
20256
}
54

            
55
/// 128 fresh bits: one tick spread over two disjoint `mix64` inputs.
56
///
57
/// `hi` alone is `mix64` of an injective function of the tick, so two mints
58
/// can only repeat once the tick wraps at 2^63.
59
10128
fn next_bits() -> [u8; 16] {
60
10128
    let tick = TICK.fetch_add(1, Ordering::Relaxed);
61
10128
    let hi = mix64(tick.wrapping_mul(2));
62
10128
    let lo = mix64(tick.wrapping_mul(2).wrapping_add(1));
63
10128
    let mut out = [0u8; 16];
64
10128
    out[..8].copy_from_slice(&hi.to_be_bytes());
65
10128
    out[8..].copy_from_slice(&lo.to_be_bytes());
66
    // RFC 4122: version 4 in the high nibble of byte 6, variant 0b10 in the
67
    // top two bits of byte 8. Stamped after the mix so the shape is exact.
68
10128
    out[6] = (out[6] & 0x0F) | 0x40;
69
10128
    out[8] = (out[8] & 0x3F) | 0x80;
70
10128
    out
71
10128
}
72

            
73
/// Static-method namespace for UUID string generation ([`Uuid::v4`],
74
/// [`Uuid::short`]). The struct only exists so the FFI layer can hang static
75
/// methods off it.
76
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
77
#[repr(C)]
78
#[allow(clippy::pub_underscore_fields)] // FFI/api.json static-namespace placeholder field
79
pub struct Uuid {
80
    pub _reserved: u8,
81
}
82

            
83
impl Default for Uuid {
84
1
    fn default() -> Self {
85
1
        Self::new()
86
1
    }
87
}
88

            
89
impl Uuid {
90
    /// Returns a zero-initialised handle. The struct only exists so the FFI
91
    /// layer can hang static methods off it.
92
    #[must_use]
93
3
    pub const fn new() -> Self {
94
3
        Self { _reserved: 0 }
95
3
    }
96

            
97
    /// A fresh version-4-shaped UUID in canonical hyphenated lowercase form,
98
    /// e.g. `"550e8400-e29b-41d4-a716-446655440000"` (36 characters).
99
    ///
100
    /// Deterministic, not random - the value depends only on how many ids this
101
    /// process has already minted. See the module docs before using one as
102
    /// anything but a marker.
103
    #[must_use]
104
5064
    pub fn v4() -> AzString {
105
        const HEX: &[u8; 16] = b"0123456789abcdef";
106
5064
        let b = next_bits();
107
5064
        let mut out = String::with_capacity(36);
108
81024
        for (i, byte) in b.iter().enumerate() {
109
            // 4-2-2-2-6 bytes, so the hyphens fall after bytes 4, 6, 8 and 10.
110
81024
            if matches!(i, 4 | 6 | 8 | 10) {
111
20256
                out.push('-');
112
60768
            }
113
81024
            out.push(HEX[usize::from(byte >> 4)] as char);
114
81024
            out.push(HEX[usize::from(byte & 0x0F)] as char);
115
        }
116
5064
        out.into()
117
5064
    }
118

            
119
    /// A fresh version-4-shaped UUID as a 22-character flickrBase58 string,
120
    /// e.g. `"mhvXdrZT4jP5T8vBxuvm75"` - the same encoding `short-uuid` used to
121
    /// print. The compact spelling for markers, log lines and URLs.
122
    ///
123
    /// Deterministic, not random - see [`Uuid::v4`] and the module docs.
124
    #[must_use]
125
5064
    pub fn short() -> AzString {
126
        // Big-endian base58 of the same 128 bits, left-padded to the fixed 22
127
        // characters `short-uuid` emits (a value with leading zero bytes still
128
        // has to spell 22 characters or the width stops being a contract).
129
5064
        let mut n = u128::from_be_bytes(next_bits());
130
5064
        let mut buf = [BASE58[0]; 22];
131
5064
        let mut i = 22;
132
116297
        while n > 0 && i > 0 {
133
111233
            i -= 1;
134
111233
            buf[i] = BASE58[(n % 58) as usize];
135
111233
            n /= 58;
136
111233
        }
137
5064
        String::from_utf8_lossy(&buf).into_owned().into()
138
5064
    }
139
}
140

            
141
#[cfg(test)]
142
mod uuid_tests {
143
    use std::collections::HashSet;
144

            
145
    use super::*;
146

            
147
    #[test]
148
1
    fn v4_is_canonical_hyphenated_lowercase() {
149
65
        for _ in 0..64 {
150
64
            let s = Uuid::v4();
151
64
            let s = s.as_str();
152
64
            assert_eq!(s.len(), 36, "canonical UUID is 36 chars: {s}");
153
2304
            for (i, c) in s.char_indices() {
154
2304
                if matches!(i, 8 | 13 | 18 | 23) {
155
256
                    assert_eq!(c, '-', "hyphen expected at {i}: {s}");
156
                } else {
157
2048
                    assert!(
158
2048
                        c.is_ascii_hexdigit() && !c.is_ascii_uppercase(),
159
                        "lowercase hex expected at {i}: {s}",
160
                    );
161
                }
162
            }
163
64
            assert_eq!(&s[14..15], "4", "version nibble must say v4: {s}");
164
        }
165
1
    }
166

            
167
    #[test]
168
1
    fn short_is_22_chars_of_flickr_base58() {
169
        // flickrBase58: no 0 / O / I / l - the look-alike characters.
170
65
        for _ in 0..64 {
171
64
            let s = Uuid::short();
172
64
            let s = s.as_str();
173
64
            assert_eq!(s.len(), 22, "short UUID is 22 chars: {s}");
174
1408
            for c in s.chars() {
175
1408
                assert!(c.is_ascii_alphanumeric(), "base58 is alphanumeric: {s}");
176
1408
                assert!(
177
1408
                    !matches!(c, '0' | 'O' | 'I' | 'l'),
178
                    "flickrBase58 excludes look-alikes, got {c:?} in {s}",
179
                );
180
            }
181
        }
182
1
    }
183

            
184
    #[test]
185
1
    fn minted_ids_do_not_collide() {
186
        // The whole point of the module: 10k mints, 10k distinct strings.
187
1
        let mut seen = HashSet::new();
188
5001
        for _ in 0..5_000 {
189
5000
            assert!(seen.insert(Uuid::v4().as_str().to_string()));
190
5000
            assert!(seen.insert(Uuid::short().as_str().to_string()));
191
        }
192
1
    }
193

            
194
    #[test]
195
1
    fn the_namespace_handle_is_inert() {
196
1
        assert_eq!(Uuid::new(), Uuid::default());
197
1
        assert_eq!(Uuid::new()._reserved, 0);
198
1
    }
199
}