Something went wrong. Try again.
A minecraft server software written in Rust
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546use crate::net::codec::data_type::DataType;use crate::net::codec::{varint::Varint, byte::Byte};
pub struct JString;
impl DataType for JString { type Value = String;
async fn read<R: tokio::io::AsyncReadExt + Unpin>(stream: &mut R) -> anyhow::Result<Self::Value> { let length = Varint::read(stream).await? as usize; let mut buf = vec![0u8; length]; stream.read_exact(&mut buf).await?; let string = String::from_utf8(buf)?; Ok(string) }
async fn write<R: tokio::io::AsyncWriteExt + Unpin>(stream: &mut R, value: Self::Value) -> anyhow::Result<()> { let len = value.len() as i32; let bytes = value.bytes(); Varint::write(stream, len).await?;
for byte in bytes { Byte::write(stream, byte).await?; }; Ok(()) }}
#[cfg(test)]mod tests { use super::*;
#[tokio::test] async fn write_string() { let mut data: Vec<u8> = Vec::new(); JString::write(&mut data, "hello!".to_string()).await.unwrap(); assert_eq!(vec![6, 104, 101, 108, 108, 111, 33], data); }
#[tokio::test] async fn read_string() { let mut data: &[u8] = &[6, 104, 101, 108, 108, 111, 33]; assert_eq!("hello!", JString::read(&mut data).await.unwrap()); }}