Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 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. let test3 = "Hello this is my world!";
  15. let result = from_reader(test3.as_bytes());
  16. println!("{:?}", result);
  17. }
  18.  
  19. fn from_reader(mut reader: impl Read) -> Result<CString, std::io::Error>
  20. {
  21. let mut buffer = Vec::new();
  22. loop {
  23. // Read a single byte, same way as byteorder::read_u8 does it.
  24. // If the specific implementation of Read::read is buffered and inlined
  25. // I am quite sure this can be optimized well.
  26. let mut character: u8 = 0;
  27. let slice = std::slice::from_mut(&mut character);
  28. reader.read_exact(slice)?;
  29.  
  30. // Check if a null character has been found, if so return the Vec as CString.
  31. if character == 0 {
  32. return Ok(unsafe { CString::from_vec_unchecked(buffer) });
  33. }
  34.  
  35. // Push a new character.
  36. buffer.push(character);
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement