use super::checksum::internet_checksum;
use core::fmt;
pub const ICMPV4_HEADER_LENGTH: usize = 8;
pub const ICMPV4_MAX_VALID_CODE: u8 = 15;
pub struct Icmpv4Writer<'a> {
pub bytes: &'a mut [u8],
}
impl<'a> Icmpv4Writer<'a> {
#[inline]
pub fn new(bytes: &'a mut [u8]) -> Result<Self, &'static str> {
if bytes.len() < ICMPV4_HEADER_LENGTH {
return Err("Slice is too short to contain an ICMP header.");
}
Ok(Self { bytes })
}
#[inline]
pub fn header_len(&self) -> usize {
ICMPV4_HEADER_LENGTH
}
#[inline]
pub fn packet_len(&self) -> usize {
self.bytes.len()
}
#[inline]
pub fn set_icmp_type(&mut self, icmp_type: u8) {
self.bytes[0] = icmp_type;
}
#[inline]
pub fn set_icmp_code(&mut self, code: u8) {
self.bytes[1] = code;
}
#[inline]
pub fn set_payload(&mut self, payload: &[u8]) -> Result<(), &'static str> {
let start = self.header_len();
let payload_len = payload.len();
if self.packet_len() - start < payload_len {
return Err("Payload is too large to fit in the ICMPv4 packet.");
}
let end = start + payload_len;
self.bytes[start..end].copy_from_slice(payload);
Ok(())
}
#[inline]
pub fn set_checksum(&mut self) {
self.bytes[2] = 0;
self.bytes[3] = 0;
let checksum = internet_checksum(self.bytes, 0);
self.bytes[2] = (checksum >> 8) as u8;
self.bytes[3] = (checksum & 0xff) as u8;
}
}
#[derive(PartialEq)]
pub struct Icmpv4Reader<'a> {
pub bytes: &'a [u8],
}
impl<'a> Icmpv4Reader<'a> {
#[inline]
pub fn new(bytes: &'a [u8]) -> Result<Self, &'static str> {
if bytes.len() < ICMPV4_HEADER_LENGTH {
return Err("Slice is too short to contain an ICMP header.");
}
Ok(Self { bytes })
}
#[inline]
pub fn icmp_type(&self) -> u8 {
self.bytes[0]
}
#[inline]
pub fn icmp_code(&self) -> u8 {
self.bytes[1]
}
#[inline]
pub fn checksum(&self) -> u16 {
((self.bytes[2] as u16) << 8) | (self.bytes[3] as u16)
}
#[inline]
pub fn header_len(&self) -> usize {
ICMPV4_HEADER_LENGTH
}
#[inline]
pub fn header(&self) -> &'a [u8] {
&self.bytes[..ICMPV4_HEADER_LENGTH]
}
#[inline]
pub fn payload(&self) -> &'a [u8] {
&self.bytes[ICMPV4_HEADER_LENGTH..]
}
}
impl fmt::Debug for Icmpv4Reader<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Icmpv4Packet")
.field("type", &self.icmp_type())
.field("code", &self.icmp_code())
.field("checksum", &self.checksum())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn getters_and_setters() {
let mut bytes = [0u8; ICMPV4_HEADER_LENGTH];
let icmp_type = 8;
let code = 0;
let mut writer = Icmpv4Writer::new(&mut bytes).unwrap();
writer.set_icmp_type(icmp_type);
writer.set_icmp_code(code);
writer.set_checksum();
let reader = Icmpv4Reader::new(&bytes).unwrap();
assert_eq!(reader.icmp_type(), icmp_type);
assert_eq!(reader.icmp_code(), code);
}
}