Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. use std::io::Read;
  2. use std::ffi::CString;
  3.  
  4. fn main() {
  5.  
  6. let test = "Hello this is my world!\0";
  7. let string = from_reader(test.as_bytes());
  8. println!("{:?}", string.unwrap());
  9.  
  10. let test2 = "Hello this \0is my world!\0";
  11. let string2 = from_reader(test2.as_bytes());
  12. println!("{:?}", string2.unwrap());
  13. }
  14.  
  15. fn from_reader(mut reader: impl Read) -> Result<CString, std::io::Error>
  16. {
  17. let mut buffer = Vec::new();
  18. loop {
  19. // Read a single byte, same way as byteorder::read_u8 does it.
  20. // If the specific implementation of Read::read is buffered and inlined
  21. // I am quite sure this can be optimized well.
  22. let mut character: u8 = 0;
  23. let slice = std::slice::from_mut(&mut character);
  24. reader.read_exact(slice)?;
  25.  
  26. // Push a new character.
  27. buffer.push(character);
  28.  
  29. // Check if a null character has been found, if so return the Vec as CString.
  30. if character == 0 {
  31. return Ok(CString { inner: buffer.into_boxed_slice() });
  32. }
  33. }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement