1#![allow(deprecated)]
2
3use std::fmt;
4
5use crate::{
6 context::{DeserializeContext, SerializeContext},
7 Class, Name, NameParseError, PacketParseError, Type,
8};
9
10#[derive(Clone, Debug)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct Question {
13 pub name: Name,
14 #[serde(rename = "type")]
15 pub type_: Type,
16 #[serde(default)]
17 pub class: Class,
18}
19
20impl fmt::Display for Question {
21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 write!(f, "{} {}", self.type_, self.name)
23 }
24}
25
26impl Question {
27 pub fn new(type_: Type, name: impl AsRef<str>) -> Result<Self, NameParseError> {
28 Ok(Self {
29 name: name.as_ref().parse()?,
30 type_,
31 class: Default::default(),
32 })
33 }
34
35 pub(crate) fn parse(context: &mut DeserializeContext<'_>) -> Result<Self, PacketParseError> {
36 Ok(Self {
37 name: context.read_name()?,
38 type_: context.read(u16::from_be_bytes)?.into(),
39 class: context.read(u16::from_be_bytes)?.into(),
40 })
41 }
42
43 pub(crate) fn serialize(&self, context: &mut SerializeContext) {
44 context.write_name(&self.name);
45 context.write_blob(<Type as Into<u16>>::into(self.type_).to_be_bytes());
46 context.write_blob(<Class as Into<u16>>::into(self.class).to_be_bytes());
47 }
48}