silkrust/net/io/
reader_extensions.rs

1use std::string::FromUtf8Error;
2use bytes::{Buf, Bytes};
3use crate::net::io::fragment::Fragment;
4
5pub trait BytesExtension {
6    fn get_collection<T: Fragment>(&mut self) -> Vec<T>;
7    fn get_string(&mut self) -> Result<String, FromUtf8Error>;
8}
9
10impl BytesExtension for Bytes {
11    fn get_collection<T: Fragment>(&mut self) -> Vec<T> {
12        let mut entities = vec![];
13        while self.get_u8() == 1 {
14            entities.push(<T as Fragment>::get(self));
15        }
16
17        entities
18    }
19
20    fn get_string(&mut self) -> Result<String, FromUtf8Error> {
21        let mut buf = vec![0u8; self.get_u16_le() as usize];
22        self.copy_to_slice(&mut buf);
23
24        String::from_utf8(buf)
25    }
26}