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