Skip to main content

hickory_proto/serialize/binary/
mod.rs

1// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! Binary serialization types
9
10mod decoder;
11mod encoder;
12mod restrict;
13
14use alloc::vec::Vec;
15
16pub use self::decoder::{BinDecoder, DecodeError};
17pub use self::encoder::{
18    BinEncoder, EncodedSize, ModalEncoder, NameEncoding, Place, RDataEncoding,
19};
20pub use self::restrict::{Restrict, RestrictedMath, Verified};
21
22#[cfg(test)]
23pub(crate) mod bin_tests;
24
25use crate::error::*;
26
27/// A type which can be encoded into a DNS binary format
28pub trait BinEncodable {
29    /// Write the type to the stream
30    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()>;
31
32    /// Returns the object in binary form
33    fn to_bytes(&self) -> ProtoResult<Vec<u8>> {
34        let mut bytes = Vec::<u8>::new();
35        {
36            let mut encoder = BinEncoder::new(&mut bytes);
37            self.emit(&mut encoder)?;
38        }
39
40        Ok(bytes)
41    }
42}
43
44/// A trait for types which are serializable to and from DNS binary formats
45pub trait BinDecodable<'r>: Sized {
46    /// Read the type from the stream
47    fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError>;
48
49    /// Returns the object in binary form
50    fn from_bytes(bytes: &'r [u8]) -> Result<Self, DecodeError> {
51        let mut decoder = BinDecoder::new(bytes);
52        Self::read(&mut decoder)
53    }
54}
55
56impl BinEncodable for u16 {
57    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
58        encoder.emit_u16(*self)
59    }
60}
61
62impl BinDecodable<'_> for u16 {
63    fn read(decoder: &mut BinDecoder<'_>) -> Result<Self, DecodeError> {
64        decoder.read_u16().map(Restrict::unverified)
65    }
66}
67
68impl BinEncodable for i32 {
69    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
70        encoder.emit_i32(*self)
71    }
72}
73
74impl<'r> BinDecodable<'r> for i32 {
75    fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
76        decoder.read_i32().map(Restrict::unverified)
77    }
78}
79
80impl BinEncodable for u32 {
81    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
82        encoder.emit_u32(*self)
83    }
84}
85
86impl BinDecodable<'_> for u32 {
87    fn read(decoder: &mut BinDecoder<'_>) -> Result<Self, DecodeError> {
88        decoder.read_u32().map(Restrict::unverified)
89    }
90}
91
92impl BinEncodable for Vec<u8> {
93    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
94        encoder.emit_vec(self)
95    }
96}