rtc_turn/proto/
channum.rs

1#[cfg(test)]
2mod channnum_test;
3
4use std::fmt;
5
6use stun::attributes::*;
7use stun::checks::*;
8use stun::message::*;
9
10use shared::error::Result;
11
12// 16 bits of uint + 16 bits of RFFU = 0.
13const CHANNEL_NUMBER_SIZE: usize = 4;
14
15// See https://tools.ietf.org/html/rfc5766#section-11:
16//
17// 0x4000 through 0x7FFF: These values are the allowed channel
18// numbers (16,383 possible values).
19pub const MIN_CHANNEL_NUMBER: u16 = 0x4000;
20pub const MAX_CHANNEL_NUMBER: u16 = 0x7FFF;
21
22/// `ChannelNumber` represents `CHANNEL-NUMBER` attribute. Encoded as `u16`.
23///
24/// The `CHANNEL-NUMBER` attribute contains the number of the channel.
25///
26/// [RFC 5766 Section 14.1](https://www.rfc-editor.org/rfc/rfc5766#section-14.1).
27#[derive(Default, Eq, PartialEq, Debug, Copy, Clone, Hash)]
28pub struct ChannelNumber(pub u16);
29
30impl fmt::Display for ChannelNumber {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(f, "{}", self.0)
33    }
34}
35
36impl Setter for ChannelNumber {
37    /// Adds `CHANNEL-NUMBER` to message.
38    fn add_to(&self, m: &mut Message) -> Result<()> {
39        let mut v = vec![0; CHANNEL_NUMBER_SIZE];
40        v[..2].copy_from_slice(&self.0.to_be_bytes());
41        // v[2:4] are zeroes (RFFU = 0)
42        m.add(ATTR_CHANNEL_NUMBER, &v);
43        Ok(())
44    }
45}
46
47impl Getter for ChannelNumber {
48    /// Decodes `CHANNEL-NUMBER` from message.
49    fn get_from(&mut self, m: &Message) -> Result<()> {
50        let v = m.get(ATTR_CHANNEL_NUMBER)?;
51
52        check_size(ATTR_CHANNEL_NUMBER, v.len(), CHANNEL_NUMBER_SIZE)?;
53
54        //_ = v[CHANNEL_NUMBER_SIZE-1] // asserting length
55        self.0 = u16::from_be_bytes([v[0], v[1]]);
56        // v[2:4] is RFFU and equals to 0.
57        Ok(())
58    }
59}
60
61impl ChannelNumber {
62    /// Returns true if c in `[0x4000, 0x7FFF]`.
63    fn is_channel_number_valid(&self) -> bool {
64        self.0 >= MIN_CHANNEL_NUMBER && self.0 <= MAX_CHANNEL_NUMBER
65    }
66
67    /// returns `true` if channel number has correct value that complies
68    /// [RFC 5766 Section 11](https://www.rfc-editor.org/rfc/rfc5766#section-11) range.
69    pub fn valid(&self) -> bool {
70        self.is_channel_number_valid()
71    }
72}