utopia_database/id.rs
1//! Document identifiers: [`unique`] generates one, [`custom`] takes one given.
2//!
3//! PHP: `Utopia\Database\Id`.
4
5use crate::error::{Error, Result};
6
7/// The random hex characters [`unique`] appends to the time-based part.
8pub const PADDING: i64 = 7;
9
10/// A new unique ID: 13 hex characters of the current time (`uniqid()`),
11/// then [`PADDING`] random hex characters (20 characters in all).
12///
13/// ```
14/// use utopia_database::id;
15///
16/// let id = id::unique().unwrap();
17/// assert_eq!(id.len(), 20);
18/// assert!(id.bytes().all(|c| c.is_ascii_hexdigit()));
19/// ```
20///
21/// PHP: `ID::unique()`.
22pub fn unique() -> Result<String> {
23 unique_padded(PADDING)
24}
25
26/// A new unique ID with `padding` random hex characters after the 13 of
27/// `uniqid()` (none when `padding` is 0 or less).
28///
29/// Fails like PHP when the system cannot provide random bytes.
30///
31/// PHP: `ID::unique($padding)`.
32pub fn unique_padded(padding: i64) -> Result<String> {
33 let mut id = php_std::system::uniqid("", false);
34 if padding > 0 {
35 // One random byte is two hex characters: max(1, ceil(padding / 2)) bytes.
36 let len = usize::try_from(padding / 2 + padding % 2)
37 .map_err(|_| Error::database("Could not gather sufficient random data"))?;
38 let mut bytes = vec![0u8; len.max(1)];
39 getrandom::fill(&mut bytes).map_err(|_| Error::database("Could not gather sufficient random data"))?;
40 let hex = hex::encode(bytes);
41 id.push_str(&hex[..hex.len().min(padding as usize)]);
42 }
43 Ok(id)
44}
45
46/// An ID given by the caller, as it is.
47///
48/// PHP: `ID::custom($id)`.
49pub fn custom(id: impl Into<String>) -> String {
50 id.into()
51}