Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. use std::io::Read;
  2.  
  3. // Since I cannot implement additional methods, for the sake of this example
  4. // I will use MyCString as it represents a CString.
  5. #[derive(Debug)]
  6. struct MyCString
  7. {
  8. inner: Box<[u8]>,
  9. }
  10.  
  11.  
  12. impl MyCString
  13. {
  14. /// Option 1: Add a new method to CString
  15. fn from_reader(mut reader: impl Read) -> Result<MyCString, std::io::Error>
  16. {
  17. let mut buffer = Vec::new();
  18. let mut character: u8 = 0;
  19.  
  20. loop {
  21.  
  22. let slice = std::slice::from_mut(&mut character);
  23. reader.read_exact(slice)?;
  24.  
  25. // Check if a null character has been found, if so return the Vec as CString.
  26. if character == 0 {
  27. return Ok(unsafe { MyCString::from_vec_unchecked(buffer) });
  28. }
  29.  
  30. // Push a new character.
  31. buffer.push(character);
  32. }
  33. }
  34.  
  35. /// This method is already implemented by CString.
  36. pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> MyCString {
  37. v.reserve_exact(1);
  38. v.push(0);
  39. MyCString { inner: v.into_boxed_slice() }
  40. }
  41. }
  42.  
  43. fn main() {
  44.  
  45. let test = "Hello this is my world!\0";
  46. let string = MyCString::from_reader(test.as_bytes());
  47. println!("{:?}", string.unwrap());
  48.  
  49. let test2 = "Hello this \0is my world!\0";
  50. let string2 = MyCString::from_reader(test2.as_bytes());
  51. println!("{:?}", string2.unwrap());
  52.  
  53. let test3 = "Hello this is my world!";
  54. let result = MyCString::from_reader(test3.as_bytes());
  55. println!("{:?}", result);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement