Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std::io::Read::read_to_end - Read Vec<> based on Vec<>.capacity() and not Vec<>.len() #69

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions serial-unix/src/tty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,27 @@ impl io::Read for TTYPort {
Err(io::Error::last_os_error())
}
}

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
try!(super::poll::wait_read_fd(self.fd, self.timeout));

// Saefty: Vec allocate on heap u8*vec.capacity()!
let len = unsafe {
libc::read(self.fd, buf.as_ptr() as *mut c_void, buf.capacity() as size_t)
};

// Safety: We asume libc::read will never return more bytes as given by count!
Copy link
Author

@chkolbe chkolbe Oct 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could increase runtime Safety with this Assert Statement:

assert!(len == buf.capacity(), "libc::read() return more Bytes as given by length!");

unsafe {
buf.set_len(len as usize);
}

if len >= 0 {
Ok(len as usize)
}
else {
Err(io::Error::last_os_error())
}
}
}

impl io::Write for TTYPort {
Expand Down
21 changes: 21 additions & 0 deletions serial-windows/src/com.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,27 @@ impl io::Read for COMPort {
}
}
}

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
let mut len: DWORD = 0;

// Saefty: Vec allocate on heap u8*vec.capacity()!
match unsafe { ReadFile(self.handle, buf.as_mut_ptr() as *mut c_void, buf.capacity() as DWORD, &mut len, ptr::null_mut()) } {
0 => Err(io::Error::last_os_error()),
_ => {
if len != 0 {
// Safety: We asume ReadFile will never return more bytes as given by nNumberOfBytesToRead!
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could increase runtime Safety with this Assert Statement:

assert!(len == buf.capacity(), "ReadFile() return more Bytes as given by length!");

unsafe {
buf.set_len(len as usize);
}
Ok(len as usize)
}
else {
Err(io::Error::new(io::ErrorKind::TimedOut, "Operation timed out"))
}
}
}
}
}

impl io::Write for COMPort {
Expand Down