use std::{collections::HashMap, convert::TryInto};
use crate::dns::{name::Label, Name, PacketPart};
use super::RR;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct RouteThrough<'a> {
pub preference: u16,
pub intermediate_host: Name<'a>,
}
impl<'a> RR for RouteThrough<'a> {
const TYPE_CODE: u16 = 21;
}
impl<'a> RouteThrough<'a> {
pub fn into_owned<'b>(self) -> RouteThrough<'b> {
RouteThrough {
preference: self.preference,
intermediate_host: self.intermediate_host.into_owned(),
}
}
}
impl<'a> PacketPart<'a> for RouteThrough<'a> {
fn parse(data: &'a [u8], position: usize) -> crate::Result<Self>
where
Self: Sized,
{
let preference = u16::from_be_bytes(data[position..position + 2].try_into()?);
let intermediate_host = Name::parse(data, position + 2)?;
Ok(Self {
preference,
intermediate_host,
})
}
fn write_to<T: std::io::Write>(&self, out: &mut T) -> crate::Result<()> {
out.write_all(&self.preference.to_be_bytes())?;
self.intermediate_host.write_to(out)
}
fn write_compressed_to<T: std::io::Write + std::io::Seek>(
&'a self,
out: &mut T,
name_refs: &mut HashMap<&'a [Label<'a>], usize>,
) -> crate::Result<()> {
out.write_all(&self.preference.to_be_bytes())?;
self.intermediate_host.write_compressed_to(out, name_refs)
}
fn len(&self) -> usize {
self.intermediate_host.len() + 2
}
}
#[cfg(test)]
mod tests {
use crate::{rdata::RData, ResourceRecord};
use super::*;
#[test]
fn parse_and_write_route_through() {
let rt = RouteThrough {
preference: 10,
intermediate_host: Name::new("e.exchange.com").unwrap(),
};
let mut data = Vec::new();
assert!(rt.write_to(&mut data).is_ok());
let rt = RouteThrough::parse(&data, 0);
assert!(rt.is_ok());
let rt = rt.unwrap();
assert_eq!(data.len(), rt.len());
assert_eq!(10, rt.preference);
assert_eq!("e.exchange.com", rt.intermediate_host.to_string());
}
#[test]
fn parse_sample() -> Result<(), Box<dyn std::error::Error>> {
let sample_file = std::fs::read("samples/zonefile/RT.sample")?;
let sample_rdata = match ResourceRecord::parse(&sample_file, 0)?.rdata {
RData::RouteThrough(rdata) => rdata,
_ => unreachable!(),
};
assert_eq!(sample_rdata.preference, 0);
assert_eq!(
sample_rdata.intermediate_host,
"intermediate-host.sample".try_into()?
);
Ok(())
}
}