Files
boxmaker/crates/proto/src/ids.rs
T
2026-09-17 09:29:48 -07:00

187 lines
5.0 KiB
Rust

use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueError {
SessionId,
Hash32,
Timestamp,
}
impl std::fmt::Display for ValueError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ValueError::SessionId => write!(f, "invalid session id"),
ValueError::Hash32 => write!(f, "invalid hash32"),
ValueError::Timestamp => write!(f, "invalid timestamp"),
}
}
}
impl std::error::Error for ValueError {}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct SessionId(String);
impl SessionId {
pub fn new(s: &str) -> Result<Self, ValueError> {
if s.is_empty() || s.len() > 64 {
return Err(ValueError::SessionId);
}
if !s
.bytes()
.all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'-'))
{
return Err(ValueError::SessionId);
}
Ok(SessionId(s.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for SessionId {
type Error = ValueError;
fn try_from(s: String) -> Result<Self, Self::Error> {
SessionId::new(&s)
}
}
impl From<SessionId> for String {
fn from(id: SessionId) -> String {
id.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Epoch(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct CallId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Hash32([u8; 32]);
impl Hash32 {
pub const ZERO: Hash32 = Hash32([0; 32]);
pub fn from_bytes(bytes: [u8; 32]) -> Self {
Hash32(bytes)
}
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
pub fn to_hex(&self) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(64);
for &byte in &self.0 {
out.push(char::from(HEX[usize::from(byte >> 4)]));
out.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
out
}
pub fn from_hex(s: &str) -> Result<Self, ValueError> {
if s.len() != 64 {
return Err(ValueError::Hash32);
}
let mut out = [0u8; 32];
for (i, pair) in s.as_bytes().chunks(2).enumerate() {
let hi = hex_val(pair[0])?;
let lo = hex_val(pair[1])?;
out[i] = (hi << 4) | lo;
}
Ok(Hash32(out))
}
}
impl TryFrom<String> for Hash32 {
type Error = ValueError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Hash32::from_hex(&s)
}
}
impl From<Hash32> for String {
fn from(h: Hash32) -> String {
h.to_hex()
}
}
fn hex_val(c: u8) -> Result<u8, ValueError> {
match c {
b'0'..=b'9' => Ok(c - b'0'),
b'a'..=b'f' => Ok(c - b'a' + 10),
_ => Err(ValueError::Hash32),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Timestamp(u64);
impl Timestamp {
/// 9999-12-31T23:59:59.999Z, the last instant RFC 3339 can spell with a four-digit year.
pub const MAX: Timestamp = Timestamp(253_402_300_799_999);
pub fn from_unix_millis(ms: u64) -> Result<Self, ValueError> {
if ms > Self::MAX.0 {
return Err(ValueError::Timestamp);
}
Ok(Timestamp(ms))
}
pub fn unix_millis(&self) -> u64 {
self.0
}
pub fn now() -> Self {
let dur = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
let ms = u64::try_from(dur.as_millis()).unwrap_or(u64::MAX);
Timestamp::from_unix_millis(ms).unwrap_or(Timestamp::MAX)
}
pub fn to_rfc3339(&self) -> String {
let t = std::time::UNIX_EPOCH
.checked_add(std::time::Duration::from_millis(self.0))
.unwrap_or(std::time::UNIX_EPOCH);
humantime::format_rfc3339_millis(t).to_string()
}
pub fn parse(s: &str) -> Result<Self, ValueError> {
let t = humantime::parse_rfc3339(s).map_err(|_| ValueError::Timestamp)?;
let dur = t
.duration_since(std::time::UNIX_EPOCH)
.map_err(|_| ValueError::Timestamp)?;
let ms = u64::try_from(dur.as_millis()).map_err(|_| ValueError::Timestamp)?;
let parsed = Timestamp::from_unix_millis(ms)?;
if parsed.to_rfc3339() != s {
return Err(ValueError::Timestamp);
}
Ok(parsed)
}
}
impl TryFrom<String> for Timestamp {
type Error = ValueError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Timestamp::parse(&s)
}
}
impl From<Timestamp> for String {
fn from(t: Timestamp) -> String {
t.to_rfc3339()
}
}