zaun_community_protocol/crypto/voice/
session.rs1use std::fmt;
4
5use serde::de::Error as _;
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8use crate::b64;
9use crate::ids::{RngError, fill_random};
10
11#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct VoiceSessionId([u8; 16]);
15
16impl VoiceSessionId {
17 pub const LEN: usize = 16;
19
20 pub fn random() -> Result<Self, RngError> {
25 loop {
26 let mut bytes = [0u8; 16];
27 fill_random(&mut bytes)?;
28 if bytes != [0u8; 16] {
29 return Ok(Self(bytes));
30 }
31 }
32 }
33
34 #[must_use]
36 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
37 Self(bytes)
38 }
39
40 #[must_use]
42 pub const fn as_bytes(&self) -> &[u8; 16] {
43 &self.0
44 }
45
46 #[must_use]
48 pub fn to_b64(&self) -> String {
49 b64::encode(&self.0)
50 }
51
52 pub fn from_b64(text: &str) -> Result<Self, b64::B64Error> {
57 b64::decode_array(text).map(Self)
58 }
59}
60
61impl fmt::Debug for VoiceSessionId {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "VoiceSessionId({})", self.to_b64())
64 }
65}
66
67impl Serialize for VoiceSessionId {
68 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
69 s.serialize_str(&self.to_b64())
70 }
71}
72
73impl<'de> Deserialize<'de> for VoiceSessionId {
74 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
75 let text = <std::borrow::Cow<'de, str>>::deserialize(d)?;
76 Self::from_b64(&text).map_err(|_| D::Error::custom("invalid VoiceSessionId"))
77 }
78}