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

40 lines
1001 B
Rust
Raw Normal View History

2017-12-16 20:58:18 +00:00
use bytes::{Bytes, Buf};
use errors::*;
use std::io::Cursor;
mod std_impls;
pub trait DnsPacketData: Sized {
fn deserialize(data: &mut Cursor<Bytes>) -> Result<Self>;
}
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-16 20:58:18 +00:00
if c.remaining() != 0 {
2017-12-27 11:41:54 +00:00
bail!("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)
}