Skip to main content

rtc_dtls/
compression_methods.rs

1use shared::error::Result;
2
3use byteorder::{ReadBytesExt, WriteBytesExt};
4use std::io::{Read, Write};
5
6#[derive(Copy, Clone, Debug, PartialEq, Eq)]
7/// Compression methods. DTLS in WebRTC always negotiates `Null`.
8pub enum CompressionMethodId {
9    /// `NULL` (`0`).
10    Null = 0,
11    /// A method this crate does not implement.
12    Unsupported,
13}
14
15impl From<u8> for CompressionMethodId {
16    fn from(val: u8) -> Self {
17        match val {
18            0 => CompressionMethodId::Null,
19            _ => CompressionMethodId::Unsupported,
20        }
21    }
22}
23
24#[derive(Clone, Debug, PartialEq, Eq)]
25/// The compression-methods list offered or selected in a hello message.
26pub struct CompressionMethods {
27    /// The methods, in preference order.
28    pub ids: Vec<CompressionMethodId>,
29}
30
31impl CompressionMethods {
32    /// The encoded size of this message in bytes.
33    pub fn size(&self) -> usize {
34        1 + self.ids.len()
35    }
36
37    /// Encodes this message to `writer`.
38    ///
39    /// # Errors
40    ///
41    /// Fails on a write error, or if a field exceeds the length its wire format allows.
42    pub fn marshal<W: Write>(&self, writer: &mut W) -> Result<()> {
43        writer.write_u8(self.ids.len() as u8)?;
44
45        for id in &self.ids {
46            writer.write_u8(*id as u8)?;
47        }
48
49        Ok(writer.flush()?)
50    }
51
52    /// Decodes one of these messages from `reader`.
53    ///
54    /// # Errors
55    ///
56    /// Fails if `reader` is truncated or its contents are not a valid encoding.
57    pub fn unmarshal<R: Read>(reader: &mut R) -> Result<Self> {
58        let compression_methods_count = reader.read_u8()? as usize;
59        let mut ids = vec![];
60        for _ in 0..compression_methods_count {
61            let id = reader.read_u8()?.into();
62            if id != CompressionMethodId::Unsupported {
63                ids.push(id);
64            }
65        }
66
67        Ok(CompressionMethods { ids })
68    }
69}
70
71/// The default list: null compression only.
72pub fn default_compression_methods() -> CompressionMethods {
73    CompressionMethods {
74        ids: vec![CompressionMethodId::Null],
75    }
76}