Skip to main content

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