From e4224ed85acb67a62638503f454bfca728bd4f7b Mon Sep 17 00:00:00 2001 From: Uli Schlachter Date: Fri, 18 Aug 2023 10:35:33 +0200 Subject: [PATCH] Reduce use of byteorder crate The byteorder dependency is only used in protocol::frame::frame. I thought this dependency could easily be removed and set out to replace the use of byteorder with equivalent std methods. NetworkEndian is an alias for BigEndian. Converting a number like u32 to bytes can be done via the std lib via .to_be_bytes(). The opposite direction is from_by_bytes(). These simple things thus to not need byteorder. There is one place in the code where byteorder actually helps, thus this dependency is not actually fully removed. ByteOrder::read_uint() allows to read 1 to 8 bytes of data and returns the result as u64. Doing this with the standard library basically requires re-implementing byteorder. Thus, I did not do that. Signed-off-by: Uli Schlachter --- src/protocol/frame/frame.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/protocol/frame/frame.rs b/src/protocol/frame/frame.rs index 08def34..d88d9ac 100644 --- a/src/protocol/frame/frame.rs +++ b/src/protocol/frame/frame.rs @@ -1,4 +1,4 @@ -use byteorder::{ByteOrder, NetworkEndian, ReadBytesExt, WriteBytesExt}; +use byteorder::{NetworkEndian, ReadBytesExt}; use log::*; use std::{ borrow::Cow, @@ -108,8 +108,12 @@ impl FrameHeader { output.write_all(&[one, two])?; match lenfmt { LengthFormat::U8(_) => (), - LengthFormat::U16 => output.write_u16::(length as u16)?, - LengthFormat::U64 => output.write_u64::(length)?, + LengthFormat::U16 => { + output.write(&(length as u16).to_be_bytes())?; + } + LengthFormat::U64 => { + output.write(&length.to_be_bytes())?; + } } if let Some(ref mask) = self.mask { @@ -295,7 +299,7 @@ impl Frame { 1 => Err(Error::Protocol(ProtocolError::InvalidCloseSequence)), _ => { let mut data = self.payload; - let code = NetworkEndian::read_u16(&data[0..2]).into(); + let code = u16::from_be_bytes([data[0], data[1]]).into(); data.drain(0..2); let text = String::from_utf8(data)?; Ok(Some(CloseFrame { code, reason: text.into() })) @@ -340,7 +344,7 @@ impl Frame { pub fn close(msg: Option) -> Frame { let payload = if let Some(CloseFrame { code, reason }) = msg { let mut p = Vec::with_capacity(reason.as_bytes().len() + 2); - p.write_u16::(code.into()).unwrap(); // can't fail + p.extend(u16::from(code).to_be_bytes()); p.extend_from_slice(reason.as_bytes()); p } else {