rust-dnsbox/lib/dnsbox-base/src/ser/packet/mod.rs

50 lines
1.4 KiB
Rust
Raw Normal View History

2017-12-27 14:24:11 +00:00
use bytes::{Bytes, Buf, BufMut};
2017-12-16 20:58:18 +00:00
use errors::*;
use std::io::Cursor;
mod std_impls;
2017-12-27 14:24:11 +00:00
mod write;
pub use self::write::*;
2017-12-16 20:58:18 +00:00
pub trait DnsPacketData: Sized {
fn deserialize(data: &mut Cursor<Bytes>) -> Result<Self>;
2017-12-27 14:24:11 +00:00
fn serialize(&self, context: &mut DnsPacketWriteContext, packet: &mut Vec<u8>) -> Result<()>;
2017-12-16 20:58:18 +00:00
}
2017-12-27 11:41:54 +00:00
pub fn deserialize_with<F, O>(data: Bytes, parser: F) -> Result<O>
2017-12-16 20:58:18 +00:00
where
2017-12-27 11:41:54 +00:00
F: FnOnce(&mut Cursor<Bytes>) -> Result<O>,
2017-12-16 20:58:18 +00:00
{
let mut c = Cursor::new(data);
2017-12-27 11:41:54 +00:00
let result = parser(&mut c)?;
2017-12-27 17:38:02 +00:00
ensure!(!c.has_remaining(), "data remaining: {} bytes", c.remaining());
2017-12-16 20:58:18 +00:00
Ok(result)
}
2017-12-21 12:32:14 +00:00
pub fn remaining_bytes(data: &mut Cursor<Bytes>) -> Bytes {
let pos = data.position() as usize;
let len = data.remaining();
let result = data.get_ref().slice(pos, pos + len);
data.advance(len);
result
}
pub fn short_blob(data: &mut Cursor<Bytes>) -> Result<Bytes> {
check_enough_data!(data, 1, "short blob length");
let blob_len = data.get_u8() as usize;
check_enough_data!(data, blob_len, "short blob content");
let pos = data.position() as usize;
let blob = data.get_ref().slice(pos, pos + blob_len);
data.advance(blob_len);
Ok(blob)
}
2017-12-27 14:24:11 +00:00
pub fn write_short_blob(data: &[u8], packet: &mut Vec<u8>) -> Result<()> {
ensure!(data.len() < 256, "short blob must be at most 255 bytes long");
packet.reserve(data.len() + 1);
packet.put_u8(data.len() as u8);
packet.put_slice(data);
Ok(())
}