Should I add as_slice method to BinaryHeap?

There is BinaryHeap::into_vec, but it consumes the value. I wonder if there is API design limitation that should be taken into account. Implementation-wise, the inner buffer is just a Vec, so it is trivial to expose as_slice from it.


I think the only consideration is that even if you only pass out a &[T] it is possible to safety mess with the data (when using UnsafeCell) you would have to validate after the lifetime of the slice that all the invariants still held.

Nope, even if you shuffle the slice, that wouldn't change the safety of BinaryHeap. This is analogous to misusing the RawEntry api for HashMap. It's perfectly safe, but may give strange (but well defined) results. Note that you can give a nonsense Ord impl to BinaryHeap, and that should not be unsafe, even if it's buggy.

1 Like

I guess that is what I meant by "safety mess with the data" .

I didn't think my post implied I meant memory unsafety.

Update: The implementation has been merged into Rust nightly. Here is the tracking issue: Tracking Issue for `alloc::collections::BinaryHeap::as_slice` · Issue #83659 · rust-lang/rust · GitHub

1 Like