Skip to main content

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