use serde::{Deserialize, Serialize};
pub const MAX_PEER_ID_LENGTH: usize = 512;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SignalEnvelope {
#[serde(deserialize_with = "deserialize_bounded_peer_id")]
pub peer_id: String,
pub signal: SignalPayload,
}
fn deserialize_bounded_peer_id<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{Error, Visitor};
use std::fmt;
struct PeerIdVisitor;
impl<'de> Visitor<'de> for PeerIdVisitor {
type Value = String;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "a string of at most {MAX_PEER_ID_LENGTH} bytes")
}
fn visit_borrowed_str<E: Error>(self, v: &'de str) -> Result<String, E> {
if v.len() > MAX_PEER_ID_LENGTH {
return Err(E::custom(format!(
"peer_id exceeds {MAX_PEER_ID_LENGTH} bytes (got {})",
v.len()
)));
}
Ok(v.to_owned())
}
fn visit_str<E: Error>(self, v: &str) -> Result<String, E> {
if v.len() > MAX_PEER_ID_LENGTH {
return Err(E::custom(format!(
"peer_id exceeds {MAX_PEER_ID_LENGTH} bytes (got {})",
v.len()
)));
}
Ok(v.to_owned())
}
fn visit_string<E: Error>(self, v: String) -> Result<String, E> {
if v.len() > MAX_PEER_ID_LENGTH {
return Err(E::custom(format!(
"peer_id exceeds {MAX_PEER_ID_LENGTH} bytes (got {})",
v.len()
)));
}
Ok(v)
}
}
deserializer.deserialize_string(PeerIdVisitor)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum SignalPayload {
Offer(String),
Answer(String),
IceCandidate(String),
PeerJoined(String),
PeerLeft(String),
}