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

Unexpected operation of vec::as_mut_slice() with binary read #96915

Closed
alexpyattaev opened this issue May 10, 2022 · 3 comments
Closed

Unexpected operation of vec::as_mut_slice() with binary read #96915

alexpyattaev opened this issue May 10, 2022 · 3 comments
Labels
C-bug Category: This is a bug.

Comments

@alexpyattaev
Copy link

alexpyattaev commented May 10, 2022

I think there is an issue with implementation of vec::as_mut_slice()
Here in the docs it is suggested that as_mut_slice() can be used to read data into a vec from an IO reader. So, below example should happily read a bunch of bytes from stdin, and print them out to stdout as byte vectors.

    let mut buf:Vec<u8> = Vec::with_capacity(512);
    stdin_lock.read(buf.as_mut_slice());

Now, actually running this will read nothing into buf, and will not produce errors or warnings.
The reason this is happening is subtle - buf has capacity, but once it is converted into a slice, that slice is actually empty. For this reason, nothing gets read.

@alexpyattaev alexpyattaev added the C-bug Category: This is a bug. label May 10, 2022
@sfackler
Copy link
Member

You are creating a vec of zero length but a capacity of 512 in the first example. as_mut_slice returns an empty slice when called on an empty vec.

@alexpyattaev
Copy link
Author

Yes, ended up figuring this out myself as well. Took me way longer than it should though =(

@alexpyattaev
Copy link
Author

alexpyattaev commented May 10, 2022

To avoid people stumbling into this trap, the docs could probably give an example like this to emphasize the possible trap

   let mut buf:Vec<u8> = Vec::with_capacity(size);
    buf.resize(size, 0);
   std::io::stdin().read_exact(buf.as_mutable_slice());

On the same note, should read() even accept empty slices?

@alexpyattaev alexpyattaev changed the title Incorrect operation of vec::as_mut_slice() with binary read Unexpected operation of vec::as_mut_slice() with binary read May 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: This is a bug.
Projects
None yet
Development

No branches or pull requests

2 participants