use crate::{utils, R};
use std::fmt;
use std::net::SocketAddr;
const MAX_MESSAGE_SIZE_FOR_SERIALISATION: usize = 1024;
#[derive(Serialize, Deserialize, Debug)]
pub enum WireMsg {
Handshake(Handshake),
EndpointEchoReq,
EndpointEchoResp(SocketAddr),
UserMsg(bytes::Bytes),
}
impl Into<bytes::Bytes> for WireMsg {
fn into(self) -> bytes::Bytes {
if let WireMsg::UserMsg(ref m) = self {
if m.len() > MAX_MESSAGE_SIZE_FOR_SERIALISATION {
return m.clone();
}
}
From::from(unwrap!(bincode::serialize(&self)))
}
}
impl WireMsg {
pub fn from_raw(raw: Vec<u8>) -> R<Self> {
if raw.len() > MAX_MESSAGE_SIZE_FOR_SERIALISATION {
return Ok(WireMsg::UserMsg(From::from(raw)));
}
Ok(bincode::deserialize(&raw)?)
}
}
impl fmt::Display for WireMsg {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
WireMsg::UserMsg(ref m) => {
write!(f, "WireMsg::UserMsg({})", utils::bin_data_format(&*m))
}
ref w => write!(f, "{}", w),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub enum Handshake {
Node { cert_der: Vec<u8> },
Client,
}
impl fmt::Display for Handshake {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Handshake::Node { ref cert_der } => write!(
f,
"Handshake::Node {{ cert_der: {} }}",
utils::bin_data_format(cert_der)
),
Handshake::Client => write!(f, "Handshake::Client"),
}
}
}