use bytes::{Buf, BufMut};
use n0_error::{e, stack_error};
use noq_proto::{
VarInt,
coding::{Decodable, Encodable, UnexpectedEnd},
};
#[repr(u32)]
#[derive(
Copy, Clone, PartialEq, Eq, Debug, num_enum::IntoPrimitive, num_enum::TryFromPrimitive,
)]
#[non_exhaustive]
pub enum FrameType {
ServerChallenge = 0,
ClientAuth = 1,
ServerConfirmsAuth = 2,
ServerDeniesAuth = 3,
ClientToRelayDatagram = 4,
ClientToRelayDatagramBatch = 5,
RelayToClientDatagram = 6,
RelayToClientDatagramBatch = 7,
EndpointGone = 8,
Ping = 9,
Pong = 10,
Health = 11,
Restarting = 12,
Status = 13,
}
#[stack_error(derive, add_meta)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum FrameTypeError {
#[error("not enough bytes to parse frame type")]
UnexpectedEnd {
#[error(std_err)]
source: UnexpectedEnd,
},
#[error("frame type unknown")]
UnknownFrameType { tag: VarInt },
}
impl FrameType {
pub(crate) fn write_to<O: BufMut>(&self, mut dst: O) -> O {
VarInt::from(*self).encode(&mut dst);
dst
}
pub(crate) fn encoded_len(&self) -> usize {
let x: u32 = (*self).into();
if x < 2u32.pow(6) {
1 } else if x < 2u32.pow(14) {
2
} else if x < 2u32.pow(30) {
4
} else {
unreachable!("Impossible FrameType primitive representation")
}
}
pub(crate) fn from_bytes(buf: &mut impl Buf) -> Result<Self, FrameTypeError> {
let tag = VarInt::decode(buf).map_err(|err| e!(FrameTypeError::UnexpectedEnd, err))?;
let tag_u32 = u32::try_from(u64::from(tag))
.map_err(|_| e!(FrameTypeError::UnknownFrameType { tag }))?;
let frame_type = FrameType::try_from(tag_u32)
.map_err(|_| e!(FrameTypeError::UnknownFrameType { tag }))?;
Ok(frame_type)
}
}
impl From<FrameType> for VarInt {
fn from(value: FrameType) -> Self {
(value as u32).into()
}
}