Repository navigation
Description
Proposal
Problem statement
Currently, a BinaryHeap can be constructed in two main ways: either by adding one item at a time to an empty heap, (time BinaryHeap::from::<Vec<_>>(), which does a time Vec<T> is already structured as a max-heap, then this rebuild is unnecessary, so we could construct the BinaryHeap in constant time.
Motivating examples or use cases
Building a BinaryHeap from data that is already structured as a heap:
let heaped_vec = vec![5,4,3,2,1];
let heap = BinaryHeap::from_raw_vec(heaped_vec);
// or:
let mut data = get_some_data();
fast_heapify(&mut data); // e.g. multithreaded heap build
let heap = BinaryHeap::from_raw_vec(data);It could also reverse a .into_vec():
let inner_vec = heap.into_vec();
// do something with inner_vec
let heap = BinaryHeap::from_raw_vec(inner_vec);Solution sketch
impl BinaryHeap<T, A> {
// Convert a `Vec<T>` to a `BinaryHeap` without rebuilding
// Safety: `vec` must be a max-heap
// It is a logic error for `vec` to not be a max-heap, but will not cause UB
unsafe fn from_raw_vec(vec: Vec<T, A>) -> Self
}The function could be made safe because BinaryHeap does not rely on the underlying Vec being correctly ordered for its safety (it cannot because Ord is safe), but this could break code that relies on the correctness of BinaryHeap for trusted types like u32.
Alternatives
The alternatives are to either accept the From<Vec<T>> or to create your own implementation of BinaryHeap.
Links and related work
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.
Activity
scottmcm commentedon Dec 10, 2025
We should not do this as written because I want to be able to trust that
BinaryHeap<u32>actually works because I trustu32-- same as how there's no way to get an invariants-violatingHashSet<u32>orBTreeSet<u32>and such APIs have been previously rejected.(Said without considering whether an
unsafeversion should be added. The concern about doing as a safe function doesn't apply if it's changed tounsafe fninstead.)Dan54 commentedon Dec 10, 2025
I was mainly thinking about
BinaryHeap's API when declaring it safe. I have no objection to making itunsafeif this is a concern.nia-e commentedon Feb 10, 2026
@Dan54 We discussed this in the @rust-lang/libs-api meeting and gave the go-ahead to add this as an unstable method, with the caveat that we don't currently guarantee that
BinaryHeapis a (EDIT: particular layout of) max heap. Whether we want to stably guarantee a particular layout forBinaryHeapwill need its own discussion.kennytm commentedon Feb 11, 2026
😕 https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html the 2nd paragraph literally said "This will be a max-heap.".
I think you mean that we don't guarantee the exact layout how we'll flatten the heap (which is a binary tree) into a Vec? Basically document that
BinaryHeap::from_raw_vec(heap.into_vec())works, but no guarantee about a hand-crafted vector.nia-e commentedon Feb 11, 2026
Gah sorry, yes that's what I meant. But still that means we can't put a stable safety condition on
from_raw_heap, so it should be unstable for now.scottmcm commentedon Feb 13, 2026
(After looking at the notes) @joshtriplett I think realistically
BinaryHeapis stuck as what it is today, because we'd want a bunch of different APIs if this did become a min-map heap. (Well, I guess it could become a d-ary heap https://internals.rust-lang.org/t/why-not-use-d-ary-heap-inside-rather-than-binary-heap/18765?u=scottmcm but the name does say "binary" heap pretty specifically.)The conversation makes me think of rust-lang/rust#76234 (comment) and that it'd be nice to soft-deprecate
BinaryHeapin favour of a newMinMaxHeapthat would havepush+pop_min()+pop_max()and such, along with a sorted-order.drain()that would beDoubleEndedIteratorso thatnext/next_backgive thepop_min/pop_max. (UnlikeBinaryHeap::drainwhich is just a wrapper for theVec::drainand thus basically useless, and the unstableBinaryHeap::drain_sortedthat actually gives them in reverse sorted order.) And that new type wouldn't haveiter(nor&MinMaxHeap: IntoIterator) because obviously it shouldn't be exposing the underlying order without calling something (maybe.as_underlying_slice() -> &[T], with no mut version, andinto_underlying_vec) explicitly.okaneco commentedon Feb 13, 2026
I would second a min-max heap for std (or something with that capability).
Most times I reach for a heap, it's for a priority queue where I need a min-heap. To get that, you're forced to implement
Ordon a newtype or wrap your type in astd::cmp::Reversewrapper.1 This has the annoying knock-on effect that when you retrieve values out of the heap, their comparisons are inverted. So either you unwrap your value or use inverted logic in all of the following code. It quickly gets confusing remembering the context that your min is "greater than" a larger key.The other motivation is telling people new to Rust that we have a min-heap, but you have to do the
std::cmp::Reversedance to access it. This friction can be a factor in making people bounce off the language.Footnotes
https://doc.rust-lang.org/1.93.1/std/collections/struct.BinaryHeap.html#min-heap ↩
joshtriplett commentedon Feb 24, 2026
We could consider adding a min-max heap to std, but that'd need to be a separate type, since BinaryHeap already guarantees it's a max-heap.
joshtriplett commentedon Mar 10, 2026
Marking this as accepted. Please go ahead and add it; close this ACP when the tracking issue is opened. We don't expect to change the heap layout, and we should document the exact layout it has.