rtc_stun/
uattrs.rs

1#[cfg(test)]
2mod uattrs_test;
3
4use crate::attributes::*;
5use crate::message::*;
6use shared::error::*;
7
8use std::fmt;
9
10// UnknownAttributes represents UNKNOWN-ATTRIBUTES attribute.
11//
12// RFC 5389 Section 15.9
13pub struct UnknownAttributes(pub Vec<AttrType>);
14
15impl fmt::Display for UnknownAttributes {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        if self.0.is_empty() {
18            write!(f, "<nil>")
19        } else {
20            let mut s = vec![];
21            for t in &self.0 {
22                s.push(t.to_string());
23            }
24            write!(f, "{}", s.join(", "))
25        }
26    }
27}
28
29// type size is 16 bit.
30const ATTR_TYPE_SIZE: usize = 2;
31
32impl Setter for UnknownAttributes {
33    // add_to adds UNKNOWN-ATTRIBUTES attribute to message.
34    fn add_to(&self, m: &mut Message) -> Result<()> {
35        let mut v = Vec::with_capacity(ATTR_TYPE_SIZE * 20); // 20 should be enough
36                                                             // If len(a.Types) > 20, there will be allocations.
37        for t in &self.0 {
38            v.extend_from_slice(&t.value().to_be_bytes());
39        }
40        m.add(ATTR_UNKNOWN_ATTRIBUTES, &v);
41        Ok(())
42    }
43}
44
45impl Getter for UnknownAttributes {
46    // GetFrom parses UNKNOWN-ATTRIBUTES from message.
47    fn get_from(&mut self, m: &Message) -> Result<()> {
48        let v = m.get(ATTR_UNKNOWN_ATTRIBUTES)?;
49        if v.len() % ATTR_TYPE_SIZE != 0 {
50            return Err(Error::ErrBadUnknownAttrsSize);
51        }
52        self.0.clear();
53        let mut first = 0usize;
54        while first < v.len() {
55            let last = first + ATTR_TYPE_SIZE;
56            self.0
57                .push(AttrType(u16::from_be_bytes([v[first], v[first + 1]])));
58            first = last;
59        }
60        Ok(())
61    }
62}