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

Could rust::Vec::set_len be public API? #990

Open
benesch opened this issue Dec 27, 2021 · 3 comments
Open

Could rust::Vec::set_len be public API? #990

benesch opened this issue Dec 27, 2021 · 3 comments

Comments

@benesch
Copy link
Contributor

benesch commented Dec 27, 2021

I'm writing some code in C++ that reserves space in a rust::Vec, initializes the new chunk of memory, and then wants to call rust::Vec::set_len to indicate that the new elements are now valid. That's obviously "unsafe" from Rust's perspective but doesn't seem particularly more dangerous than any other C++ code. But rust::Vec::set_len is currently private, presumably for a reason! Thoughts on making it public? Perhaps with an unsafe prefix, as in unsafe_set_len?

Note: not blocked on this, since I've got this workaround:

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        unsafe fn vec_u8_set_len(v: &mut Vec<u8>, new_len: usize);
    }
}

unsafe fn vec_u8_set_len(v: &mut Vec<u8>, new_len: usize) {
    v.set_len(new_len)
}
@dtolnay
Copy link
Owner

dtolnay commented Dec 27, 2021

How is this API done in std::vector or other C++ vector libraries?

@benesch
Copy link
Contributor Author

benesch commented Dec 27, 2021

As best as I can tell, the answer for std::vector (and std::string) is that there's no built-in way to do this. Various resources on the matter:

Caveat: It's been a long time since I've seriously written C++. I'm certainly not an expert on this.

@benesch
Copy link
Contributor Author

benesch commented Dec 27, 2021

Here's a StackOverflow that addresses this directly: https://stackoverflow.com/a/61450370.

The tl;dr is the idiom of reserving space in a std::vector, writing to it, and then hackily increasing the size of the vector is technically undefined behavior, but de facto no one cares? What a mess.

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

No branches or pull requests

2 participants