Skip to main content

str0m_proto/
id.rs

1use std::fmt;
2use std::str::from_utf8;
3
4use crate::NonCryptographicRng;
5
6// deliberate subset of ice-char, etc that are "safe"
7const CHARS: &[u8] = b"abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789";
8
9pub struct Id<const L: usize>([u8; L]);
10
11impl<const L: usize> Id<L> {
12    pub fn random() -> Id<L> {
13        let mut x = [0; L];
14        for val in x.iter_mut().take(L) {
15            let y: f32 = NonCryptographicRng::f32();
16            let idx = (CHARS.len() as f32 * y).floor() as usize;
17            *val = CHARS[idx];
18        }
19        Id(x)
20    }
21
22    pub fn into_array(self) -> [u8; L] {
23        self.0
24    }
25}
26
27impl<const L: usize> Default for Id<L> {
28    fn default() -> Self {
29        Id::random()
30    }
31}
32
33impl<const L: usize> fmt::Display for Id<L> {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        let s = from_utf8(&self.0).expect("ascii characters");
36        write!(f, "{s}")
37    }
38}