dory/src/message/id.rs
Nathan Fisher af49f327ec Add Id type for creating unique message identifiers; Change DateTime
to only deal with instants after the Unix epoch and simplify the math.
2023-06-26 00:16:05 -04:00

62 lines
1.7 KiB
Rust

use {
std::{
error::Error,
fmt,
fs::File,
io::{self, Read},
time::{SystemTime, UNIX_EPOCH},
},
tinyrand::{RandRange, Seeded, StdRand},
};
const ALPHABET: [char; 67] = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '@', '%', '&', '=', '+',
];
#[derive(Clone, Debug)]
pub struct Id {
pub time: u64,
pub id: [char; 8],
}
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.", self.time)?;
self.id.iter().try_for_each(|c| write!(f, "{c}"))
}
}
impl Id {
pub fn new() -> Result<Self, Box<dyn Error>> {
let time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let mut rand = StdRand::seed(random_seed()?);
let mut id = ['0', '0', '0', '0', '0', '0', '0', '0'];
for item in &mut id {
if let Some(c) = ALPHABET.get(rand.next_range(0..68)) {
*item = *c;
}
}
Ok(Self { time, id })
}
}
fn u64_from_bytes(b: [u8; 8]) -> u64 {
u64::from(b[0])
| (u64::from(b[1]) << 8)
| (u64::from(b[2]) << 16)
| (u64::from(b[3]) << 24)
| (u64::from(b[4]) << 32)
| (u64::from(b[5]) << 40)
| (u64::from(b[6]) << 48)
| (u64::from(b[7]) << 56)
}
fn random_seed() -> io::Result<u64> {
let mut buf = [0, 0, 0, 0, 0, 0, 0, 0];
let mut fd = File::open("/dev/urandom")?;
fd.read_exact(&mut buf)?;
Ok(u64_from_bytes(buf))
}