packet: add bytes crate support to packet
@@ -4,7 +4,6 @@ use std::io::{Read, Write};
use crate::error::Error;
use crate::header::*;
-#[cfg(test)]
mod packet_test;
// Packet represents an RTP Packet
@@ -13,6 +12,7 @@ mod packet_test;
pub struct Packet {
pub header: Header,
pub payload: Vec<u8>,
+ pub raw: BytesMut,
}
impl fmt::Display for Packet {
@@ -32,26 +32,50 @@ impl fmt::Display for Packet {
}
impl Packet {
- // MarshalSize returns the size of the packet once marshaled.
- pub fn size(&self) -> usize {
- self.header.size() + self.payload.len()
+ pub fn new() -> Self {
+ Packet::default()
}
- // Unmarshal parses the passed byte slice and stores the result in the Header this method is called upon
- pub fn unmarshal<R: Read>(reader: &mut R) -> Result<Self, Error> {
- let header = Header::unmarshal(reader)?;
+ /// Unmarshal parses the passed byte slice and stores the result in the Header this method is called upon
+ pub fn unmarshal(&mut self, raw_packet: &mut BytesMut) -> Result<(), RTPError> {
+ self.header.unmarshal(raw_packet)?;
- let mut payload = vec![];
- reader.read_to_end(&mut payload)?;
+ self.payload = raw_packet[self.header.payload_offset..].to_vec();
+ self.raw = raw_packet.clone();
- Ok(Packet { header, payload })
+ Ok(())
}
- // Marshal serializes the header and writes to the buffer.
- pub fn marshal<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
- self.header.marshal(writer)?;
- writer.write_all(&self.payload)?;
+ /// MarshalSize returns the size of the packet once marshaled.
+ pub fn marshal_size(&mut self) -> usize {
+ self.header.marshal_size() + self.payload.len()
+ }
+
+ pub fn marshal_to(&mut self, buf: &mut BytesMut) -> Result<usize, RTPError> {
+ let size = self.header.marshal_to(buf)?;
+
+ // Make sure the buffer is large enough to hold the packet.
+ if size + self.payload.len() > buf.len() {
+ return Err(RTPError::ShortBuffer);
+ }
+
+ buf[size..size + self.payload.len()].copy_from_slice(&self.payload);
+
+ self.raw = buf.clone();
+ self.raw.truncate(size + self.payload.len());
+
+ Ok(size + self.payload.len())
+ }
+
+ /// MarshalTo serializes the packet and writes to the buffer.
+ pub fn marshal(&mut self) -> Result<BytesMut, RTPError> {
+ let mut buf = BytesMut::new();
+ buf.resize(self.marshal_size(), 0u8);
+
+ let size = self.marshal_to(&mut buf)?;
+
+ buf.truncate(size);
- Ok(writer.flush()?)
+ Ok(buf)
}
}
