use core::convert::Infallible;
use std::string::ToString;
use zerocopy::{AlignmentError, CastError, ConvertError, KnownLayout, SizeError};
use crate::frame;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("cannot parse {0}-byte packet; valid frames are at least 5 bytes")]
InvalidPacketLength(usize),
#[error("cannot parse frame header from packet: {0}")]
InvalidFrameHeader(String),
#[error("invalid frame type {0:02X}")]
InvalidFrameType(u8),
#[error("frame type {0} has max length of {2} bytes; header length is {1}")]
InvalidFrameLengthForType(frame::FrameType, usize, usize),
#[error("frame type {0} has min length of {2} bytes; body length is {1}")]
InvalidBodyLengthForType(frame::FrameType, usize, usize),
#[error("cannot parse {0} frame body from packet: {1}")]
InvalidFrameBody(frame::FrameType, String),
#[error("frame type {0} cannot have a payload, but {1} bytes remained in packet")]
InvalidFrameStructure(frame::FrameType, usize),
#[error("invalid magic byte sequence in ServerKey frame")]
InvalidMagic,
#[error("invalid peer gone reason: {0}")]
InvalidPeerGoneReason(u8),
#[error("incomplete frame")]
IncompleteFrame,
#[error("could not decrypt frame payload")]
DecryptionFailed(String),
#[error("could not encrypt frame payload")]
EncryptionFailed,
#[error("could not parse public key from string")]
InvalidKey,
}
impl From<CastError<&[u8], frame::RawHeader>> for Error {
fn from(value: CastError<&[u8], frame::RawHeader>) -> Self {
Error::InvalidFrameHeader(value.to_string())
}
}
impl<B: frame::Body + KnownLayout>
From<ConvertError<AlignmentError<&[u8], B>, SizeError<&[u8], B>, Infallible>> for Error
{
fn from(
value: ConvertError<AlignmentError<&[u8], B>, SizeError<&[u8], B>, Infallible>,
) -> Self {
Error::InvalidFrameBody(B::FRAME_TYPE, value.to_string())
}
}