Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::Read;
- use std::ffi::CString;
- fn main() {
- let test = "Hello this is my world!\0";
- let string = from_reader(test.as_bytes());
- println!("{:?}", string.unwrap());
- let test2 = "Hello this \0is my world!\0";
- let string2 = from_reader(test2.as_bytes());
- println!("{:?}", string2.unwrap());
- }
- fn from_reader(mut reader: impl Read) -> Result<CString, std::io::Error>
- {
- let mut buffer = Vec::new();
- loop {
- // Read a single byte, same way as byteorder::read_u8 does it.
- // If the specific implementation of Read::read is buffered and inlined
- // I am quite sure this can be optimized well.
- let mut character: u8 = 0;
- let slice = std::slice::from_mut(&mut character);
- reader.read_exact(slice)?;
- // Push a new character.
- buffer.push(character);
- // Check if a null character has been found, if so return the Vec as CString.
- if character == 0 {
- return Ok(unsafe { CString::from_vec_unchecked(buffer) });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement