| 19 | pub fn new(app: impl Into<String>, protocol: impl Into<String>, version: u16) -> Self { |
| 20 | Self { |
| 21 | app: app.into(), |
| 22 | protocol: protocol.into(), |
| 23 | version, |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | pub fn encode(&self) -> NetResult<Vec<u8>> { |
| 28 | let app = self.app.as_bytes(); |
| 29 | let protocol = self.protocol.as_bytes(); |
| 30 | if app.len() > u16::MAX as usize || protocol.len() > u16::MAX as usize { |
| 31 | return Err(NetError::new( |
| 32 | NetErrorKind::Handshake, |
| 33 | "handshake text too large", |
| 34 | )); |
| 35 | } |
| 36 | |
| 37 | let mut out = Vec::with_capacity(Self::MAGIC.len() + 6 + app.len() + protocol.len()); |
| 38 | out.extend_from_slice(Self::MAGIC); |
| 39 | out.extend_from_slice(&self.version.to_be_bytes()); |
| 40 | out.extend_from_slice(&(app.len() as u16).to_be_bytes()); |
| 41 | out.extend_from_slice(&(protocol.len() as u16).to_be_bytes()); |
| 42 | out.extend_from_slice(app); |