30 lines
991 B
Rust
30 lines
991 B
Rust
use std::io::Read;
|
|
|
|
pub struct String {
|
|
pub content: std::string::String,
|
|
}
|
|
|
|
impl String {
|
|
pub fn serialize(&self) -> Vec<u8> {
|
|
let mut serialized: Vec<u8> = Vec::new();
|
|
let content = self.content.as_bytes();
|
|
serialized.extend(&(content.len() as u32).to_be_bytes());
|
|
serialized.extend(content);
|
|
serialized
|
|
}
|
|
|
|
pub fn deserialize(mut to_serialize: &[u8]) -> String {
|
|
let mut size: [u8; 4] = [0; 4];
|
|
to_serialize.read(&mut size).expect("Could not read string size.");
|
|
let size: u32 = u32::from_be_bytes(size);
|
|
let mut content: Vec<u8> = Vec::new();
|
|
content.resize(size as usize, 0);
|
|
to_serialize.read(&mut content).expect("Could not read string.");
|
|
let content = match std::string::String::from_utf8(content.clone()) {
|
|
Ok(ok) => ok,
|
|
Err(err) => panic!("Error parsing {:#?} as utf-8: {}", content, err),
|
|
};
|
|
String { content: content }
|
|
}
|
|
}
|