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

Conversation

chkolbe
Copy link

@chkolbe chkolbe commented Sep 25, 2022

Lib read Implementation receives Bytes based on the Length and not on Capacity.
Receiving Bytes must be smaller or equal to Bytes send.

Added read_to_end, to use same Buffer for Writing and Receiving based on Capacity.

Implementation testes on Mac OS. Windows Implementation is untested.

let port = SerialPort::new();
let mut buf: Vec<u8> = Vec::with_capacity(255);
let bytes_count_to_receive: usize = 100;

// We prepare to send one Byte
buf.push(0xff);
port.write_all(buf.as_mut_slice()).unwrap();

// We clear the Vec so Len = 0 and Capacity = 255
buf.clear();

// We expect to receive more as 0 Byte.
if port.read_to_end(&mut buf).unwrap() != bytes_count_to_receive {
    panic!("Can not read all Bytes!");
}

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!");

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!");

@chkolbe chkolbe marked this pull request as ready for review October 18, 2022 14:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant