Skip to content

Commit

Permalink
fix(string) Fix Rust string encoding did not account for byte length.
Browse files Browse the repository at this point in the history
  • Loading branch information
x4exr committed Oct 1, 2024
1 parent cb66ac5 commit 5bdb599
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
14 changes: 10 additions & 4 deletions rust-examples/examples/hello_world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,21 @@ use xbinser_macros::{EnumDecoded, EnumEncoded, StructDecoded, StructEncoded};

#[derive(Debug, StructEncoded, StructDecoded, PartialEq)]
struct TextContainer {
text: String
text: String,
also: String
}

fn main() {
let mut cursor = Cursor::new(vec![]);
TextContainer { text: String::from("Hello World") }.encode(&mut cursor).unwrap();
TextContainer { text: String::from("hi"), also: String::from("bye") }.encode(&mut cursor).unwrap();

assert_eq!(&vec![0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64], cursor.get_ref());
assert_eq!(&vec![
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x68, 0x69, // hi
0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x62, 0x79, 0x65 // bye
], cursor.get_ref());

cursor.set_position(0);
assert_eq!(TextContainer { text: String::from("Hello World") }, TextContainer::decode(&mut cursor).unwrap());
assert_eq!(TextContainer { text: String::from("hi"), also: String::from("bye") }, TextContainer::decode(&mut cursor).unwrap());
}
12 changes: 4 additions & 8 deletions rust/src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ impl<T: Decoded + SlowType> Decoded for Vec<T> {

impl Encoded for &str {
fn encode(&self, output: &mut impl io::Write) -> io::Result<()> {
output.write_all(self.as_bytes())
self.as_bytes().encode(output)
}
}
impl Encoded for String {
Expand All @@ -166,12 +166,8 @@ impl Encoded for String {

impl Decoded for String {
fn decode(input: &mut impl io::Read) -> io::Result<Self> {
let mut bytes = Vec::new();
input.read_to_end(&mut bytes)?;

let decoded_string = String::from_utf8(bytes)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

Ok(decoded_string)
let bytes = Vec::<u8>::decode(input)?;
String::from_utf8(bytes)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
}

0 comments on commit 5bdb599

Please sign in to comment.