Skip to content

String is missing as_vec #19080

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
cgaebel opened this issue Nov 18, 2014 · 4 comments
Closed

String is missing as_vec #19080

cgaebel opened this issue Nov 18, 2014 · 4 comments
Labels
A-collections Area: `std::collections`

Comments

@cgaebel
Copy link
Contributor

cgaebel commented Nov 18, 2014

String contains as as_mut_vec method, but is missing a matching as_vec. It was likely forgotten during collections reform.

cc @gankro

@alexcrichton
Copy link
Member

This was originally done because a &Vec<u8> is functionally equivalent to &[u8] (which you can get), and we weren't super fans of as_mut_vec in the first place. Might be good to have for consistency though!

@kmcallister kmcallister added A-libs A-collections Area: `std::collections` labels Jan 28, 2015
@Gankra
Copy link
Contributor

Gankra commented Jan 29, 2015

I think it's fine to have this "hole" in the API, although I guess in the absence of an as_vec method I would have named as_mut_vec that. API's stabilized, though.

@aturon
Copy link
Member

aturon commented Feb 16, 2015

Closing as WONTFIX: you can get this via as_bytes, and I think the as_mut_vec name is good for consistency/clarity.

@aturon aturon closed this as completed Feb 16, 2015
@purplesyringa
Copy link
Contributor

I've just stumbled upon a case where as_bytes doesn't suffice.

Many SIMD libraries, e.g. simdjson, can be implemented more efficiently if the input buffer can be "safely" over-read by a dozen bytes. In Rust, a safe abstraction for such libraries can be implemented by (ab-)using Vec<u8>: if capacity() exceeds len() by the given amount of padding, the buffer is safe to pass to the library. This also gives the user a safe way to guarantee that the over-read is safe -- just reserve the space in the vector.

Anyway, this is why interfaces that take &Vec<u8> instead of &[u8] can be useful. The problem is that, given a String, you can't pass it to the interface, because there isn't a way to convert &String to &Vec<u8>, even though string does, in fact, have the same notion of capacity.

Sure, you could overload the interface for both Vec<u8> and String, or require the users to use unsafe code. But perhaps that's not the design that was expected for the implementers to use, as String is officially just a wrapper.

Should this be an RFC?

lnicola pushed a commit to lnicola/rust that referenced this issue Feb 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-collections Area: `std::collections`
Projects
None yet
Development

No branches or pull requests

6 participants