Skip to main content

grip_control/
frames.rs

1/// Returns a WebSocket-over-HTTP formatted control message
2pub fn ws_control(kind: &str) -> Vec<u8> {
3    format!("{kind}\r\n").into_bytes()
4}
5
6pub fn ws_text(msg: &str) -> Vec<u8> {
7    format!("TEXT {:x}\r\n{}\r\n", msg.len(), msg).into_bytes()
8}
9
10/// Returns a TEXT-wrapped GRIP subscription command for the given channel
11pub fn ws_sub(ch: &str) -> Vec<u8> {
12    let control_msg = format!("c:{{\"type\":\"subscribe\",\"channel\":\"{}\"}}", ch);
13    ws_text(&control_msg)
14}
15
16/// Returns a TEXT-wrapped GRIP unsubscribe command for the given channel
17pub fn ws_unsub(ch: &str) -> Vec<u8> {
18    let control_msg = format!("c:{{\"type\":\"unsubscribe\",\"channel\":\"{}\"}}", ch);
19    ws_text(&control_msg)
20}
21
22#[cfg(test)]
23mod test {
24    use super::*;
25
26    #[test]
27    fn test_ws_control() {
28        let frame = ws_control("OPEN");
29        assert_eq!(frame, b"OPEN\r\n");
30
31        let frame = ws_control("PING");
32        assert_eq!(frame, b"PING\r\n");
33
34        let frame = ws_control("DISCONNECT");
35        assert_eq!(frame, b"DISCONNECT\r\n");
36    }
37
38    #[test]
39    fn test_ws_text() {
40        let frame = ws_text("hello");
41        assert_eq!(frame, b"TEXT 5\r\nhello\r\n");
42
43        let frame = ws_text("hello world");
44        assert_eq!(frame, b"TEXT b\r\nhello world\r\n");
45
46        let frame = ws_text("");
47        assert_eq!(frame, b"TEXT 0\r\n\r\n");
48    }
49
50    #[test]
51    fn test_ws_sub() {
52        let frame = ws_sub("test-channel");
53        let expected = b"TEXT 2f\r\nc:{\"type\":\"subscribe\",\"channel\":\"test-channel\"}\r\n";
54        assert_eq!(frame, expected);
55
56        let frame = ws_sub("my-room");
57        let expected = b"TEXT 2a\r\nc:{\"type\":\"subscribe\",\"channel\":\"my-room\"}\r\n";
58        assert_eq!(frame, expected);
59    }
60
61    #[test]
62    fn test_ws_unsub() {
63        let frame = ws_unsub("test-channel");
64        let expected = b"TEXT 31\r\nc:{\"type\":\"unsubscribe\",\"channel\":\"test-channel\"}\r\n";
65        assert_eq!(frame, expected);
66
67        let frame = ws_unsub("my-room");
68        let expected = b"TEXT 2c\r\nc:{\"type\":\"unsubscribe\",\"channel\":\"my-room\"}\r\n";
69        assert_eq!(frame, expected);
70    }
71}