Skip to main content

zaun_community_protocol/crypto/voice/
session.rs

1//! The voice session id: 16 random bytes a member draws on every join.
2
3use 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/// One participation in a voice channel. A member draws a fresh one on every join, so KIDs and
12/// epochs never repeat across joins.
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct VoiceSessionId([u8; 16]);
15
16impl VoiceSessionId {
17    /// Length in bytes.
18    pub const LEN: usize = 16;
19
20    /// A fresh, non-zero session id.
21    ///
22    /// # Errors
23    /// [`RngError`] when the CSPRNG fails.
24    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    /// Wraps raw bytes.
35    #[must_use]
36    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
37        Self(bytes)
38    }
39
40    /// The raw bytes.
41    #[must_use]
42    pub const fn as_bytes(&self) -> &[u8; 16] {
43        &self.0
44    }
45
46    /// Unpadded base64url, like every other id.
47    #[must_use]
48    pub fn to_b64(&self) -> String {
49        b64::encode(&self.0)
50    }
51
52    /// Parses unpadded base64url.
53    ///
54    /// # Errors
55    /// [`b64::B64Error`] for bad text or the wrong length.
56    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}