use core::fmt;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use crate::{
error::ProtoResult,
rr::{RData, RecordData, RecordType, domain::Name},
serialize::binary::{BinDecodable, BinDecoder, BinEncodable, BinEncoder},
};
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct SRV {
priority: u16,
weight: u16,
port: u16,
target: Name,
}
impl SRV {
pub fn new(priority: u16, weight: u16, port: u16, target: Name) -> Self {
Self {
priority,
weight,
port,
target,
}
}
pub fn priority(&self) -> u16 {
self.priority
}
pub fn weight(&self) -> u16 {
self.weight
}
pub fn port(&self) -> u16 {
self.port
}
pub fn target(&self) -> &Name {
&self.target
}
}
impl BinEncodable for SRV {
fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
let is_canonical_names = encoder.is_canonical_names();
encoder.emit_u16(self.priority())?;
encoder.emit_u16(self.weight())?;
encoder.emit_u16(self.port())?;
self.target()
.emit_with_lowercase(encoder, is_canonical_names)?;
Ok(())
}
}
impl<'r> BinDecodable<'r> for SRV {
fn read(decoder: &mut BinDecoder<'r>) -> ProtoResult<Self> {
Ok(Self::new(
decoder.read_u16()?.unverified(),
decoder.read_u16()?.unverified(),
decoder.read_u16()?.unverified(),
Name::read(decoder)?,
))
}
}
impl RecordData for SRV {
fn try_from_rdata(data: RData) -> Result<Self, RData> {
match data {
RData::SRV(data) => Ok(data),
_ => Err(data),
}
}
fn try_borrow(data: &RData) -> Option<&Self> {
match data {
RData::SRV(data) => Some(data),
_ => None,
}
}
fn record_type(&self) -> RecordType {
RecordType::SRV
}
fn into_rdata(self) -> RData {
RData::SRV(self)
}
}
impl fmt::Display for SRV {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
f,
"{priority} {weight} {port} {target}",
priority = self.priority,
weight = self.weight,
port = self.port,
target = self.target,
)
}
}
#[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 = SRV::new(1, 2, 3, Name::from_str("_dns._tcp.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 = SRV::read(&mut decoder).expect("Decoding error");
assert_eq!(rdata, read_rdata);
}
}