Skip to main content

rtc_datachannel/message/
message_type.rs

1use super::*;
2use shared::error::{Error, Result};
3
4// The first byte in a `Message` that specifies its type:
5pub(crate) const MESSAGE_TYPE_THRESHOLD: u8 = 0x00; // reuse 0x00 for internal usage
6pub(crate) const MESSAGE_TYPE_CLOSE: u8 = 0x01; // reuse 0x01 for internal usage
7pub(crate) const MESSAGE_TYPE_ACK: u8 = 0x02;
8pub(crate) const MESSAGE_TYPE_OPEN: u8 = 0x03;
9pub(crate) const MESSAGE_TYPE_LEN: usize = 1;
10
11/// The one-byte type that prefixes a DCEP message.
12#[derive(Eq, PartialEq, Copy, Clone, Debug)]
13pub enum MessageType {
14    /// A buffered-amount threshold crossing. Internal to this crate.
15    DataChannelThreshold, // internal usage only
16    /// A channel close notification. Internal to this crate.
17    DataChannelClose, // internal usage only
18    /// `DATA_CHANNEL_ACK` (`0x02`).
19    DataChannelAck,
20    /// `DATA_CHANNEL_OPEN` (`0x03`).
21    DataChannelOpen,
22}
23
24impl MarshalSize for MessageType {
25    fn marshal_size(&self) -> usize {
26        MESSAGE_TYPE_LEN
27    }
28}
29
30impl Marshal for MessageType {
31    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
32        let b = match self {
33            MessageType::DataChannelThreshold => MESSAGE_TYPE_THRESHOLD, // internal usage only
34            MessageType::DataChannelClose => MESSAGE_TYPE_CLOSE,         // internal usage only
35            MessageType::DataChannelAck => MESSAGE_TYPE_ACK,
36            MessageType::DataChannelOpen => MESSAGE_TYPE_OPEN,
37        };
38
39        buf.put_u8(b);
40
41        Ok(1)
42    }
43}
44
45impl Unmarshal for MessageType {
46    fn unmarshal<B>(buf: &mut B) -> Result<Self>
47    where
48        B: Buf,
49    {
50        let required_len = MESSAGE_TYPE_LEN;
51        if buf.remaining() < required_len {
52            return Err(Error::UnexpectedEndOfBuffer {
53                expected: required_len,
54                actual: buf.remaining(),
55            });
56        }
57
58        let b = buf.get_u8();
59
60        match b {
61            MESSAGE_TYPE_THRESHOLD => Ok(MessageType::DataChannelThreshold), // internal usage only
62            MESSAGE_TYPE_CLOSE => Ok(MessageType::DataChannelClose),         // internal usage only
63            MESSAGE_TYPE_ACK => Ok(Self::DataChannelAck),
64            MESSAGE_TYPE_OPEN => Ok(Self::DataChannelOpen),
65            _ => Err(Error::InvalidMessageType(b)),
66        }
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use bytes::{Bytes, BytesMut};
73
74    use super::*;
75
76    #[test]
77    fn test_message_type_unmarshal_open_success() -> Result<()> {
78        let mut bytes = Bytes::from_static(&[0x03]);
79        let msg_type = MessageType::unmarshal(&mut bytes)?;
80
81        assert_eq!(msg_type, MessageType::DataChannelOpen);
82
83        Ok(())
84    }
85
86    #[test]
87    fn test_message_type_unmarshal_ack_success() -> Result<()> {
88        let mut bytes = Bytes::from_static(&[0x02]);
89        let msg_type = MessageType::unmarshal(&mut bytes)?;
90
91        assert_eq!(msg_type, MessageType::DataChannelAck);
92        Ok(())
93    }
94
95    #[test]
96    fn test_message_type_unmarshal_invalid() -> Result<()> {
97        let mut bytes = Bytes::from_static(&[0x04]);
98        match MessageType::unmarshal(&mut bytes) {
99            Ok(_) => panic!("expected Error, but got Ok"),
100            Err(err) => {
101                if Error::InvalidMessageType(0x04) == err {
102                    return Ok(());
103                }
104                panic!(
105                    "unexpected err {:?}, want {:?}",
106                    err,
107                    Error::InvalidMessageType(0x04)
108                );
109            }
110        }
111    }
112
113    #[test]
114    fn test_message_type_marshal_size() -> Result<()> {
115        let ack = MessageType::DataChannelAck;
116        let marshal_size = ack.marshal_size();
117
118        assert_eq!(marshal_size, MESSAGE_TYPE_LEN);
119        Ok(())
120    }
121
122    #[test]
123    fn test_message_type_marshal() -> Result<()> {
124        let mut buf = BytesMut::with_capacity(MESSAGE_TYPE_LEN);
125        buf.resize(MESSAGE_TYPE_LEN, 0u8);
126        let msg_type = MessageType::DataChannelAck;
127        let n = msg_type.marshal_to(&mut buf)?;
128        let bytes = buf.freeze();
129
130        assert_eq!(n, MESSAGE_TYPE_LEN);
131        assert_eq!(&bytes[..], &[0x02]);
132        Ok(())
133    }
134}