refactors

This commit is contained in:
2023-06-11 02:39:01 +02:00
parent ccb0ce87e1
commit 50fa67409c
9 changed files with 76 additions and 208 deletions

View File

@@ -1,4 +1,4 @@
use std::{ffi::CStr, fmt::Debug};
use std::fmt::Debug;
use bytemuck::{Pod, Zeroable};
use eyre::eyre;
@@ -82,19 +82,40 @@ pub struct Packet {
pub data: Vec<u8>,
}
impl Packet {
#[must_use]
pub fn data(&self) -> &[u8] {
&self.data[..self.header.length as usize]
}
#[must_use]
pub fn as_string(&self) -> Option<&str> {
let data = self.data();
let nul = data.iter().enumerate().find(|(_i, c)| **c == 0);
let data = if let Some((i, _)) = nul {
&data[..i]
} else {
data
};
std::str::from_utf8(data).ok()
}
}
impl Debug for Packet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let data = &self.data;
let mut debugger = f.debug_struct("Packet");
debugger.field("kind", &PacketKind::from_u8(self.header.kind));
let c_str = CStr::from_bytes_until_nul(data).ok();
if let Some(str_data) = c_str.as_ref().and_then(|x| x.to_str().ok()) {
debugger.field("data", &str_data);
} else {
debugger.field("data", &data);
match self.as_string() {
Some(string) if string.chars().all(|c| !c.is_control()) => {
debugger.field("data", &string);
}
_ => {
debugger.field("data", &self.data());
}
}
debugger.finish()
@@ -132,7 +153,7 @@ impl Packet {
pub async fn recv_into_cancelation_safe(
&mut self,
stream: &mut ReadHalf<'_>,
) -> std::io::Result<()> {
) -> eyre::Result<()> {
// Makes sure all data is available before reading
let header_bytes = bytemuck::bytes_of_mut(&mut self.header);
stream.peek(header_bytes).await?;
@@ -144,7 +165,7 @@ impl Packet {
}
#[allow(clippy::missing_errors_doc)]
pub async fn recv_into(&mut self, stream: &mut ReadHalf<'_>) -> std::io::Result<()> {
pub async fn recv_into(&mut self, stream: &mut ReadHalf<'_>) -> eyre::Result<()> {
let header_bytes = bytemuck::bytes_of_mut(&mut self.header);
stream.read_exact(header_bytes).await?;
@@ -153,13 +174,20 @@ impl Packet {
stream.read_exact(&mut self.data).await?;
if self.header.kind == PacketKind::Error.raw() {
return Err(eyre!(
"client reported error: {:?}",
self.as_string().unwrap_or("unknown dyn auth error")
));
}
Ok(())
}
#[allow(clippy::missing_errors_doc)]
pub async fn send(&self, stream: &mut WriteHalf<'_>) -> std::io::Result<()> {
stream.write_all(bytemuck::bytes_of(&self.header)).await?;
stream.write_all(&self.data).await?;
stream.write_all(self.data()).await?;
Ok(())
}