(bytes: &[u8])
| 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); |
| 43 | out.extend_from_slice(protocol); |
| 44 | Ok(out) |
| 45 | } |
| 46 | |
| 47 | pub fn decode(bytes: &[u8]) -> NetResult<Self> { |
| 48 | let min_len = Self::MAGIC.len() + 6; |
| 49 | if bytes.len() < min_len || !bytes.starts_with(Self::MAGIC) { |
| 50 | return Err(NetError::new( |
| 51 | NetErrorKind::Handshake, |
| 52 | "invalid handshake header", |
| 53 | )); |
| 54 | } |
| 55 | |
| 56 | let mut i = Self::MAGIC.len(); |
| 57 | let version = u16::from_be_bytes([bytes[i], bytes[i + 1]]); |
| 58 | i += 2; |
| 59 | let app_len = u16::from_be_bytes([bytes[i], bytes[i + 1]]) as usize; |
| 60 | i += 2; |
| 61 | let protocol_len = u16::from_be_bytes([bytes[i], bytes[i + 1]]) as usize; |
| 62 | i += 2; |
| 63 | |
| 64 | if bytes.len() != i + app_len + protocol_len { |
| 65 | return Err(NetError::new( |
| 66 | NetErrorKind::Handshake, |
| 67 | "invalid handshake length", |
| 68 | )); |
| 69 | } |
| 70 | |
| 71 | let app = utf8(bytes[i..i + app_len].to_vec())?; |
| 72 | i += app_len; |
| 73 | let protocol = utf8(bytes[i..i + protocol_len].to_vec())?; |
| 74 | |
| 75 | Ok(Self { |
| 76 | app, |
| 77 | protocol, |
no test coverage detected