Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::Read;
- use std::num::NonZeroU8;
- use std::io::Error;
- #[derive(Debug)]
- struct MyCString
- {
- inner: Box<[u8]>,
- }
- impl MyCString
- {
- pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> MyCString {
- v.reserve_exact(1);
- v.push(0);
- MyCString { inner: v.into_boxed_slice() }
- }
- }
- // Option 2:
- impl From<Vec<NonZeroU8>> for MyCString
- {
- fn from(vec: Vec<NonZeroU8>) -> Self
- {
- unsafe {
- let vec = std::mem::transmute::<Vec<NonZeroU8>, Vec<u8>>(vec);
- MyCString::from_vec_unchecked(vec)
- }
- }
- }
- fn main() {
- let test = "Hello this is my world!\0";
- let string = my_own_read_function(test.as_bytes());
- println!("{:?}", string.unwrap());
- let test2 = "Hello this \0is my world!\0";
- let string2 = my_own_read_function(test2.as_bytes());
- println!("{:?}", string2.unwrap());
- let test3 = "Hello this is my world!";
- let result = my_own_read_function(test3.as_bytes());
- println!("{:?}", result);
- }
- // By introducing the From<Vec<NonZeroU8>> trait people still have to write this kind of code:
- fn my_own_read_function(mut reader: impl Read) -> Result<MyCString, Error>
- {
- let mut buffer: Vec<NonZeroU8> = 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 let Some(x) = NonZeroU8::new(character) {
- buffer.push(x);
- } else
- {
- return Ok(MyCString::from(buffer));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement