Skip to content

Write impl on Vec<u8> is easy to misuse #23768

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

Closed
mahkoh opened this issue Mar 26, 2015 · 3 comments · Fixed by #23934
Closed

Write impl on Vec<u8> is easy to misuse #23768

mahkoh opened this issue Mar 26, 2015 · 3 comments · Fixed by #23934

Comments

@mahkoh
Copy link
Contributor

mahkoh commented Mar 26, 2015

use std::io::{Write};

fn main() {
    let mut vec = b"a".to_vec();
    let _ = write!(&mut vec, "b");
    println!("{:?}", vec);
    // [97, 98]

    let _ = write!(vec, "b");
    println!("{:?}", vec);
    // [98, 98]
}
@sfackler
Copy link
Member

For clarity, the second call to write! ends up using the Write impl on &mut [u8].

cc @erickt I had concerns about this kind of thing when these impls were being introduced but I thought I convinced myself that this kind of thing couldn't happen. Did something change in the way we designed these impls since then?

@sfackler
Copy link
Member

Possible solutions are to either remove the impl for &mut [u8] or update write! to prevent it from invoking DerefMut. Seems to me like the second is the better approach.

bors added a commit that referenced this issue Apr 3, 2015
This means passing in e.g. a `Vec<u8>` or `String` will work as
intended, rather than deref-ing to `&mut [u8]` or `&mut str`.

[breaking-change]

Closes #23768
@lilyball
Copy link
Contributor

lilyball commented Apr 3, 2015

I believe the reason for the &mut *$dst was because it was considered a good thing to require callers to explicitly pass &mut references. I think we've actually gone back and forth on that a few times. Are we committed now to allowing callers to just say write!(someValue, "...")?

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 a pull request may close this issue.

4 participants