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 <psychon@znc.in>
This commit is contained in:
Uli Schlachter 2023-08-18 10:35:33 +02:00
parent 53914c1180
commit e4224ed85a
1 changed files with 9 additions and 5 deletions

View File

@ -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::<NetworkEndian>(length as u16)?,
LengthFormat::U64 => output.write_u64::<NetworkEndian>(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<CloseFrame>) -> Frame {
let payload = if let Some(CloseFrame { code, reason }) = msg {
let mut p = Vec::with_capacity(reason.as_bytes().len() + 2);
p.write_u16::<NetworkEndian>(code.into()).unwrap(); // can't fail
p.extend(u16::from(code).to_be_bytes());
p.extend_from_slice(reason.as_bytes());
p
} else {