1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use rand::Rng;
use crate::*;

impl<T: Message + ?Sized> Message for &T {
    #[inline]
    fn encode<const SIDE: bool>(&self, writer: &mut Vec<u8>) {
        T::encode::<SIDE>(self, writer)
    }
}

impl Message for str {
    #[inline]
    fn encode<const SIDE: bool>(&self, writer: &mut Vec<u8>) {
        encode::<SIDE>(writer, true, 1, self.as_bytes());
    }
}

impl Message for [u8] {
    #[inline]
    fn encode<const SIDE: bool>(&self, writer: &mut Vec<u8>) {
        encode::<SIDE>(writer, true, 2, self);
    }
}

impl<const N: usize> Message for [u8; N] {
    #[inline]
    fn encode<const SIDE: bool>(&self, writer: &mut Vec<u8>) {
        encode::<SIDE>(writer, true, 2, self);
    }
}

impl CloseFrame for () {
    type Frame = Box<[u8]>;
    fn encode<const SIDE: bool>(self) -> Self::Frame {
        if SIDE == SERVER {
            Box::new([136, 0])
        } else {
            Box::new([136, 128, 0, 0, 0, 0])
        }
    }
}

impl CloseFrame for u16 {
    type Frame = Vec<u8>;
    fn encode<const SIDE: bool>(self) -> Self::Frame {
        let mut bytes = Vec::new();
        encode::<SIDE>(&mut bytes, true, 8, &self.to_be_bytes());
        bytes
    }
}

impl CloseFrame for CloseCode {
    type Frame = Vec<u8>;

    fn encode<const SIDE: bool>(self) -> Self::Frame {
        CloseFrame::encode::<SIDE>(u16::from(self))
    }
}

impl<Code, Msg> CloseFrame for (Code, Msg)
where
    Code: Into<u16>,
    Msg: AsRef<[u8]>,
{
    type Frame = Vec<u8>;

    fn encode<const SIDE: bool>(self) -> Self::Frame {
        let (code, reason) = (self.0.into(), self.1.as_ref());
        let mut data = Vec::with_capacity(2 + reason.len());
        data.extend_from_slice(&code.to_be_bytes());
        data.extend_from_slice(reason);

        let mut bytes = Vec::new();
        encode::<SIDE>(&mut bytes, true, 8, &data);
        bytes
    }
}

impl CloseFrame for &str {
    type Frame = Vec<u8>;
    fn encode<const SIDE: bool>(self) -> Self::Frame {
        CloseFrame::encode::<SIDE>((CloseCode::Normal, self))
    }
}

// ------------------------------------------------------------------------------

pub(crate) fn encode<const SIDE: bool>(writer: &mut Vec<u8>, fin: bool, opcode: u8, data: &[u8]) {
    let data_len = data.len();
    writer.reserve(if SERVER == SIDE { 10 } else { 14 } + data_len);
    unsafe {
        let filled = writer.len();
        let start = writer.as_mut_ptr().add(filled);

        let mask_bit = if SERVER == SIDE { 0 } else { 0x80 };

        start.write(((fin as u8) << 7) | opcode);
        let len = if data_len < 126 {
            start.add(1).write(mask_bit | data_len as u8);
            2
        } else if data_len < 65536 {
            let [b2, b3] = (data_len as u16).to_be_bytes();
            start.add(1).write(mask_bit | 126);
            start.add(2).write(b2);
            start.add(3).write(b3);
            4
        } else {
            let [b2, b3, b4, b5, b6, b7, b8, b9] = (data_len as u64).to_be_bytes();
            start.add(1).write(mask_bit | 127);
            start.add(2).write(b2);
            start.add(3).write(b3);
            start.add(4).write(b4);
            start.add(5).write(b5);
            start.add(6).write(b6);
            start.add(7).write(b7);
            start.add(8).write(b8);
            start.add(9).write(b9);
            10
        };

        let header_len = if SERVER == SIDE {
            std::ptr::copy_nonoverlapping(data.as_ptr(), start.add(len), data_len);
            len
        } else {
            let mut rng = rand::thread_rng();
            let mask = rng.gen::<u32>().to_ne_bytes();
            let [a, b, c, d] = mask;
            start.add(len).write(a);
            start.add(len + 1).write(b);
            start.add(len + 2).write(c);
            start.add(len + 3).write(d);

            let dist = start.add(len + 4);
            for (index, byte) in data.iter().enumerate() {
                dist.add(index).write(byte ^ mask.get_unchecked(index % 4));
            }
            len + 4
        };
        writer.set_len(filled + header_len + data_len);
    }
}

#[cfg(test)]
mod encode {
    use super::*;
    const DATA: &[u8] = b"Hello";

    #[test]
    fn unmasked_txt_msg() {
        let mut bytes = vec![];
        encode::<SERVER>(&mut bytes, true, 1, DATA);
        assert_eq!(bytes, [0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]);
    }

    #[test]
    fn fragmented_unmasked_txt_msg() {
        let mut bytes = vec![];
        encode::<SERVER>(&mut bytes, false, 1, b"Hel");
        encode::<SERVER>(&mut bytes, true, 0, b"lo");
        assert_eq!(
            bytes,
            [
                0x01, 0x03, 0x48, 0x65, 0x6c, // fragmented frame
                0x80, 0x02, 0x6c, 0x6f, // final frame
            ]
        );
    }

    #[test]
    fn unmasked_ping_req() {
        let mut bytes = vec![];
        encode::<SERVER>(&mut bytes, true, 9, DATA);
        assert_eq!(bytes, [0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f,]);
    }
}