Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. use std::io::Read;
  2. use std::num::NonZeroU8;
  3. use std::io::Error;
  4.  
  5. #[derive(Debug)]
  6. struct MyCString
  7. {
  8. inner: Box<[u8]>,
  9. }
  10.  
  11. impl MyCString
  12. {
  13. pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> MyCString {
  14. v.reserve_exact(1);
  15. v.push(0);
  16. MyCString { inner: v.into_boxed_slice() }
  17. }
  18. }
  19.  
  20. // Option 2:
  21. impl From<Vec<NonZeroU8>> for MyCString
  22. {
  23. fn from(vec: Vec<NonZeroU8>) -> Self
  24. {
  25. unsafe {
  26. let vec = std::mem::transmute::<Vec<NonZeroU8>, Vec<u8>>(vec);
  27. MyCString::from_vec_unchecked(vec)
  28. }
  29. }
  30. }
  31.  
  32. fn main() {
  33.  
  34. let test = "Hello this is my world!\0";
  35. let string = my_own_read_function(test.as_bytes());
  36. println!("{:?}", string.unwrap());
  37.  
  38. let test2 = "Hello this \0is my world!\0";
  39. let string2 = my_own_read_function(test2.as_bytes());
  40. println!("{:?}", string2.unwrap());
  41.  
  42. let test3 = "Hello this is my world!";
  43. let result = my_own_read_function(test3.as_bytes());
  44. println!("{:?}", result);
  45. }
  46.  
  47. // By introducing the From<Vec<NonZeroU8>> trait people still have to write this kind of code:
  48. fn my_own_read_function(mut reader: impl Read) -> Result<MyCString, Error>
  49. {
  50. let mut buffer: Vec<NonZeroU8> = Vec::new();
  51. let mut character: u8 = 0;
  52.  
  53. loop {
  54.  
  55. let slice = std::slice::from_mut(&mut character);
  56. reader.read_exact(slice)?;
  57.  
  58. // Check if a null character has been found, if so return the Vec as CString.
  59. if let Some(x) = NonZeroU8::new(character) {
  60. buffer.push(x);
  61. } else
  62. {
  63. return Ok(MyCString::from(buffer));
  64. }
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement