stun_rs/
protocols.rs

1//! Assigned Internet Protocol Numbers.
2//! This module contains the protocol numbers specified in
3//! [PROTOCOL-NUMBERS](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml).
4
5use crate::common::check_buffer_boundaries;
6use crate::{Encode, StunError};
7
8const PROTOCOL_NUMBER_SIZE: usize = 1;
9
10/// The protocol number class represents a protocol defined in
11/// [PROTOCOL-NUMBERS](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml).
12#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
13pub struct ProtocolNumber(u8);
14
15impl ProtocolNumber {
16    /// Returns the `ProtocolNumber` as an `u8`
17    pub fn as_u8(&self) -> u8 {
18        self.0
19    }
20}
21
22impl PartialEq<u8> for ProtocolNumber {
23    fn eq(&self, other: &u8) -> bool {
24        self.0 == *other
25    }
26}
27
28impl PartialEq<ProtocolNumber> for u8 {
29    fn eq(&self, other: &ProtocolNumber) -> bool {
30        *self == other.0
31    }
32}
33
34/// `UDP` protocol number
35pub const UDP: ProtocolNumber = ProtocolNumber(17u8);
36
37impl Encode for ProtocolNumber {
38    fn encode(&self, raw_value: &mut [u8]) -> Result<usize, StunError> {
39        check_buffer_boundaries(raw_value, PROTOCOL_NUMBER_SIZE)?;
40        raw_value[0] = self.0;
41        Ok(PROTOCOL_NUMBER_SIZE)
42    }
43}
44
45impl<'a> crate::Decode<'a> for ProtocolNumber {
46    fn decode(raw_value: &'a [u8]) -> Result<(Self, usize), StunError> {
47        check_buffer_boundaries(raw_value, PROTOCOL_NUMBER_SIZE)?;
48        Ok((ProtocolNumber(raw_value[0]), PROTOCOL_NUMBER_SIZE))
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use crate::{Decode, StunErrorType};
56
57    #[test]
58    fn contructor() {
59        let protocol = ProtocolNumber(17u8);
60        assert_eq!(protocol, UDP);
61        assert_eq!(protocol, 17u8);
62        assert_eq!(17u8, protocol);
63    }
64
65    #[test]
66    fn decode_value() {
67        let buffer = [];
68        let error = ProtocolNumber::decode(&buffer).expect_err("Small buffer error expected");
69        assert_eq!(error, StunErrorType::SmallBuffer);
70
71        let buffer = [0x15];
72        let (val, size) = ProtocolNumber::decode(&buffer).expect("Can not decode protocol number");
73        assert_eq!(size, PROTOCOL_NUMBER_SIZE);
74        assert_eq!(val, 0x15);
75    }
76
77    #[test]
78    fn encode_value() {
79        let mut buffer = [];
80        let error = UDP
81            .encode(&mut buffer)
82            .expect_err("Small buffer error expected");
83        assert_eq!(error, StunErrorType::SmallBuffer);
84
85        let mut buffer = [0x00];
86        let size = UDP
87            .encode(&mut buffer)
88            .expect("Can not encode protocol number");
89        assert_eq!(size, PROTOCOL_NUMBER_SIZE);
90        assert_eq!(buffer[0], UDP);
91    }
92}