use std::fmt;
use std::io;
use crate::CrafterError;
pub type Result<T> = std::result::Result<T, PcapError>;
#[derive(Debug)]
pub enum PcapError {
Io(io::Error),
Packet(CrafterError),
Libpcap(::pcap::Error),
InvalidHeader(&'static str),
InvalidRecord(&'static str),
RecordTooLarge {
field: &'static str,
max: u64,
actual: u64,
},
CaptureSourceMissing,
LiveCaptureUnavailable(&'static str),
CaptureThreadPanicked,
}
impl fmt::Display for PcapError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(err) => write!(f, "{err}"),
Self::Packet(err) => write!(f, "{err}"),
Self::Libpcap(err) => write!(f, "{err}"),
Self::InvalidHeader(reason) => write!(f, "invalid pcap header: {reason}"),
Self::InvalidRecord(reason) => write!(f, "invalid pcap record: {reason}"),
Self::RecordTooLarge { field, max, actual } => {
write!(f, "pcap {field} value {actual} exceeds maximum {max}")
}
Self::CaptureSourceMissing => write!(f, "capture source is missing"),
Self::LiveCaptureUnavailable(reason) => {
write!(f, "live capture is unavailable: {reason}")
}
Self::CaptureThreadPanicked => write!(f, "capture thread panicked"),
}
}
}
impl std::error::Error for PcapError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(err) => Some(err),
Self::Packet(err) => Some(err),
Self::Libpcap(err) => Some(err),
_ => None,
}
}
}
impl From<io::Error> for PcapError {
fn from(value: io::Error) -> Self {
Self::Io(value)
}
}
impl From<CrafterError> for PcapError {
fn from(value: CrafterError) -> Self {
Self::Packet(value)
}
}
impl From<::pcap::Error> for PcapError {
fn from(value: ::pcap::Error) -> Self {
Self::Libpcap(value)
}
}