-
Notifications
You must be signed in to change notification settings - Fork 131
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
Add ArrayVec::leak #235
base: master
Are you sure you want to change the base?
Add ArrayVec::leak #235
Conversation
Why do you want to leak the values? |
My use case is a reusable buffer. The bytes are pushed into the buffer, and when the content is finalized it can be handed out as a &[u8]. The borrow checker makes sure that the buffer isn't re-used as long as a reference to the contents are live, and the old content will never be seen after the &[u8] ref is dropped. "leak()" isn't the best of names for the operation, as the memory isn't actually leaked, but it aligns with std :: Vec. The values will not be dropped however, so in that sense "leak()" is correct. |
Names along the lines of take are also interesting then, but they don't convey the leaking (when it applies). You mentioned that Vec has Vec::leak, and that should be in the first PR description - that's usually a good enough argument for any new arrayvec method. Then it's easy for us to just adapt the same idea. |
pub fn leak(&mut self) -> &mut [T] { | ||
unsafe { | ||
let s = slice::from_raw_parts_mut(self.as_mut_ptr(), self.len()); | ||
self.set_len(0); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would be more comfortable to swap the order of these two lines actually!
A. We create a borrow of the whole vec as a &mut [T]
B. We modify self (set_len)
This is better in the order of B, then A, so that it's clear we don't invalidate the borrow. Miri apparently didn't react on this though?
no github actions run, don't immediately see why |
I have swapped the order of creating the slice and setting the length to 0 now, as per your suggestion. An alternative name to leak might be "forget", but I would expect a return value from that method. "into_slice_and_forget" is a bit of a mouth-full. The old saying about cache invalidation and naming things still applies.. |
You can enable action runs for first-time contributors in the settings. |
ok, changed to a more permissive setting |
Hello,
This pull request adds leak() to ArrayVec, which can be useful if you want to hand out a reference to the contained data, and at the same time want to be sure that the vec is empty when the reference is dropped. Especially useful for !Drop types.