Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::Read;
- // Since I cannot implement additional methods, for the sake of this example
- // I will use MyCString as it represents a CString.
- #[derive(Debug)]
- struct MyCString
- {
- inner: Box<[u8]>,
- }
- impl MyCString
- {
- /// Option 1: Add a new method to CString
- fn from_reader(mut reader: impl Read) -> Result<MyCString, std::io::Error>
- {
- let mut buffer = Vec::new();
- let mut character: u8 = 0;
- loop {
- let slice = std::slice::from_mut(&mut character);
- reader.read_exact(slice)?;
- // Check if a null character has been found, if so return the Vec as CString.
- if character == 0 {
- return Ok(unsafe { MyCString::from_vec_unchecked(buffer) });
- }
- // Push a new character.
- buffer.push(character);
- }
- }
- /// This method is already implemented by CString.
- pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> MyCString {
- v.reserve_exact(1);
- v.push(0);
- MyCString { inner: v.into_boxed_slice() }
- }
- }
- fn main() {
- let test = "Hello this is my world!\0";
- let string = MyCString::from_reader(test.as_bytes());
- println!("{:?}", string.unwrap());
- let test2 = "Hello this \0is my world!\0";
- let string2 = MyCString::from_reader(test2.as_bytes());
- println!("{:?}", string2.unwrap());
- let test3 = "Hello this is my world!";
- let result = MyCString::from_reader(test3.as_bytes());
- println!("{:?}", result);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement