use 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(stream: &mut R) -> anyhow::Result { 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(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 = 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()); } }