rust-dnsbox/lib/dnsbox-base/src/ser/rrdata.rs

98 lines
2.5 KiB
Rust

use bytes::Bytes;
use common_types::{Class, Type, classes};
use errors::*;
use ser::DnsPacketData;
use ser::text::{DnsTextData, DnsTextFormatter, DnsTextContext};
use std::borrow::Cow;
use std::fmt;
use std::io::Cursor;
pub trait RRDataPacket {
fn deserialize_rr_data(ttl: u32, rr_class: Class, rr_type: Type, data: &mut Cursor<Bytes>) -> Result<Self>
where
Self: Sized,
;
fn rr_type(&self) -> Type;
}
impl<T: DnsPacketData + StaticRRData> RRDataPacket for T {
fn deserialize_rr_data(_ttl: u32, rr_class: Class, rr_type: Type, data: &mut Cursor<Bytes>) -> Result<Self> {
ensure!(rr_type == T::TYPE, "type mismatch");
if T::CLASS != classes::ANY {
ensure!(rr_class == T::CLASS, "class mismatch: got {}, need {}", rr_class, T::CLASS);
}
T::deserialize(data)
}
fn rr_type(&self) -> Type {
T::TYPE
}
}
pub trait RRDataText {
fn dns_parse_rr_data(context: &DnsTextContext, data: &mut &str) -> Result<Self>
where
Self: Sized,
;
// format might fail if there is no (known) text representation.
fn dns_format_rr_data(&self, f: &mut DnsTextFormatter) -> fmt::Result;
fn rr_type_txt(&self) -> Cow<'static, str> {
unimplemented!()
}
// (type, rrdata)
fn text(&self) -> Result<(String, String)> {
use std::fmt::Write;
let mut buf = String::new();
match write!(&mut buf, "{}", DnsDisplayRR(self)) {
Ok(()) => {
return Ok((self.rr_type_txt().into(), buf))
},
Err(_) => (),
}
buf.clear();
unimplemented!()
}
}
impl<T: DnsTextData + StaticRRData> RRDataText for T {
fn dns_parse_rr_data(context: &DnsTextContext, data: &mut &str) -> Result<Self>
where
Self: Sized,
{
ensure!(context.record_type() == Some(T::TYPE), "type mismatch");
let rr_class = context.zone_class().expect("require zone CLASS to parse record");
if T::CLASS != classes::ANY {
ensure!(rr_class == T::CLASS, "class mismatch: got {}, need {}", rr_class, T::CLASS);
}
ensure!(context.last_ttl().is_some(), "require TTL to parse record");
T::dns_parse(context, data)
}
fn dns_format_rr_data(&self, f: &mut DnsTextFormatter) -> fmt::Result {
self.dns_format(f)
}
}
#[derive(Debug)]
pub struct DnsDisplayRR<'a, T: RRDataText + ?Sized + 'a>(pub &'a T);
impl<'a, T: RRDataText + ?Sized + 'a> fmt::Display for DnsDisplayRR<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.dns_format_rr_data(&mut DnsTextFormatter::new(f))
}
}
pub trait RRData: RRDataPacket + RRDataText {
}
pub trait StaticRRData: RRData {
const TYPE: Type;
const NAME: &'static str;
// classes::ANY marks class independent types
const CLASS: Class;
}