dns_server/dns_class.rs
1use crate::{read_u16_be, write_u16_be, DnsError};
2use fixed_buffer::FixedBuf;
3
4/// > `CLASS` fields appear in resource records. The following `CLASS` mnemonics and values are
5/// > defined:
6/// >
7/// > - `IN` 1 the Internet
8/// > - `CS` 2 the CSNET class (Obsolete - used only for examples in some obsolete RFCs)
9/// > - `CH` 3 the CHAOS class
10/// > - `HS` 4 Hesiod [Dyer 87]
11/// >
12/// >
13/// > `QCLASS` fields appear in the question section of a query. `QCLASS` values are a superset of
14/// > `CLASS` values; every `CLASS` is a valid `QCLASS`. In addition to `CLASS` values, the following
15/// > `QCLASSes` are defined:
16/// >
17/// > - `*` 255 any class
18///
19/// <https://datatracker.ietf.org/doc/html/rfc1035#section-3.2.4>
20#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
21pub enum DnsClass {
22 Internet,
23 Any,
24 Unknown(u16),
25}
26impl DnsClass {
27 #[must_use]
28 pub fn new(value: u16) -> Self {
29 match value {
30 1 => DnsClass::Internet,
31 255 => DnsClass::Any,
32 other => DnsClass::Unknown(other),
33 }
34 }
35
36 #[must_use]
37 pub fn num(&self) -> u16 {
38 match self {
39 DnsClass::Internet => 1,
40 DnsClass::Any => 255,
41 DnsClass::Unknown(other) => *other,
42 }
43 }
44
45 /// # Errors
46 /// Returns an error when `buf` does not contain two bytes.
47 pub fn read<const N: usize>(buf: &mut FixedBuf<N>) -> Result<Self, DnsError> {
48 Ok(Self::new(read_u16_be(buf)?))
49 }
50
51 /// # Errors
52 /// Returns an error when `buf` is full.
53 pub fn write<const N: usize>(&self, out: &mut FixedBuf<N>) -> Result<(), DnsError> {
54 write_u16_be(out, self.num())
55 }
56}