hickory_proto/serialize/binary/
mod.rs1mod decoder;
11mod encoder;
12mod restrict;
13
14pub use self::decoder::{BinDecoder, DecodeError};
15pub use self::encoder::BinEncoder;
16pub use self::encoder::EncodeMode;
17pub use self::restrict::{Restrict, RestrictedMath, Verified};
18
19#[cfg(test)]
20pub(crate) mod bin_tests;
21
22use crate::error::*;
23
24pub trait BinEncodable {
26 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()>;
28
29 fn to_bytes(&self) -> ProtoResult<Vec<u8>> {
31 let mut bytes = Vec::<u8>::new();
32 {
33 let mut encoder = BinEncoder::new(&mut bytes);
34 self.emit(&mut encoder)?;
35 }
36
37 Ok(bytes)
38 }
39}
40
41pub trait BinDecodable<'r>: Sized {
43 fn read(decoder: &mut BinDecoder<'r>) -> ProtoResult<Self>;
45
46 fn from_bytes(bytes: &'r [u8]) -> ProtoResult<Self> {
48 let mut decoder = BinDecoder::new(bytes);
49 Self::read(&mut decoder)
50 }
51}
52
53impl BinEncodable for u16 {
54 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
55 encoder.emit_u16(*self)
56 }
57}
58
59impl BinDecodable<'_> for u16 {
60 fn read(decoder: &mut BinDecoder<'_>) -> ProtoResult<Self> {
61 decoder
62 .read_u16()
63 .map(Restrict::unverified)
64 .map_err(Into::into)
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>) -> ProtoResult<Self> {
76 decoder
77 .read_i32()
78 .map(Restrict::unverified)
79 .map_err(Into::into)
80 }
81}
82
83impl BinEncodable for u32 {
84 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
85 encoder.emit_u32(*self)
86 }
87}
88
89impl BinDecodable<'_> for u32 {
90 fn read(decoder: &mut BinDecoder<'_>) -> ProtoResult<Self> {
91 decoder
92 .read_u32()
93 .map(Restrict::unverified)
94 .map_err(Into::into)
95 }
96}
97
98impl BinEncodable for Vec<u8> {
99 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
100 encoder.emit_vec(self)
101 }
102}