3Hren / msgpack-rust

MessagePack implementation for Rust / msgpack.org[Rust]
MIT License
1.13k stars 128 forks source link

How to read a string #168

Open fdubois1 opened 6 years ago

fdubois1 commented 6 years ago

I have difficulties to read a string. Here is what I do : let mut buf = [0;64]; rmp::decode::read_str(&mut reader, &mut buf);

This way is good as long as my string is not longer than 64 bytes. But I want to be able to read a string that I don't know the length so I would like to read the length then read the string. let len = rmp::decode::read_str_len(&mut reader); *Here, how can I read the string ? The function read_str_data is not public. If I use read_str, it will read the length again and I don't want that.****

For now, what I am doing is reading a u8 vector with that function : fn msgpack_decode_binary(rd: &mut R, len: usize) -> Result<Vec> { let mut buf: Vec = Vec::new(); let mut i = 0; while i < len { let byte: u8 = rmp::decode::read_data_u8(rd).expect("39"); buf.push(byte); i += 1; }

return Ok(buf);

}

So I can read all u8 character, then build a string with that with String::from_utf8(&buf);

Does it exist a better way to do that ? Thanks

3Hren commented 6 years ago

The easiest way to do this is to use rmp-serde: https://docs.rs/rmp-serde/0.13.7/rmp_serde/decode/fn.from_read.html