arrayvec icon indicating copy to clipboard operation
arrayvec copied to clipboard

Add ArrayVec::leak

Open luksan opened this issue 2 years ago • 7 comments

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.

luksan avatar Apr 04 '23 14:04 luksan

Why do you want to leak the values?

bluss avatar May 05 '23 19:05 bluss

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.

luksan avatar May 08 '23 14:05 luksan

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.

bluss avatar May 08 '23 16:05 bluss

no github actions run, don't immediately see why

bluss avatar May 08 '23 16:05 bluss

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..

luksan avatar May 10 '23 15:05 luksan