use alloc::string::ToString;
use core::fmt;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use crate::{
error::ProtoResult,
rr::{RData, RecordData, RecordType, domain::Name},
serialize::{binary::*, txt::ParseError},
};
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[non_exhaustive]
pub struct MX {
pub preference: u16,
pub exchange: Name,
}
impl MX {
pub fn new(preference: u16, exchange: Name) -> Self {
Self {
preference,
exchange,
}
}
pub(crate) fn from_tokens<'i, I: Iterator<Item = &'i str>>(
mut tokens: I,
origin: Option<&Name>,
) -> Result<Self, ParseError> {
let preference: u16 = tokens
.next()
.ok_or_else(|| ParseError::MissingToken("preference".to_string()))
.and_then(|s| s.parse().map_err(Into::into))?;
let exchange: Name = tokens
.next()
.ok_or_else(|| ParseError::MissingToken("exchange".to_string()))
.and_then(|s| Name::parse(s, origin).map_err(ParseError::from))?;
Ok(Self::new(preference, exchange))
}
}
impl BinEncodable for MX {
fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
let mut encoder = encoder.with_rdata_behavior(RDataEncoding::StandardRecord);
encoder.emit_u16(self.preference)?;
self.exchange.emit(&mut encoder)?;
Ok(())
}
}
impl<'r> BinDecodable<'r> for MX {
fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
Ok(Self::new(
decoder.read_u16()?.unverified(),
Name::read(decoder)?,
))
}
}
impl RecordData for MX {
fn try_borrow(data: &RData) -> Option<&Self> {
match data {
RData::MX(csync) => Some(csync),
_ => None,
}
}
fn record_type(&self) -> RecordType {
RecordType::MX
}
fn into_rdata(self) -> RData {
RData::MX(self)
}
}
impl fmt::Display for MX {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
f,
"{pref} {ex}",
pref = &self.preference,
ex = self.exchange
)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::dbg_macro, clippy::print_stdout)]
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::println;
use super::*;
#[test]
fn test() {
use core::str::FromStr;
let rdata = MX::new(16, Name::from_str("mail.example.com.").unwrap());
let mut bytes = Vec::new();
let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
assert!(rdata.emit(&mut encoder).is_ok());
let bytes = encoder.into_bytes();
#[cfg(feature = "std")]
println!("bytes: {bytes:?}");
let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
let read_rdata = MX::read(&mut decoder).expect("Decoding error");
assert_eq!(rdata, read_rdata);
}
}