Skip to content

BinaryHeap::from_raw_vec #710

Closed
Closed

Description

@Dan54

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 $O(n\log n)$) or using BinaryHeap::from::<Vec<_>>(), which does a time $O(n)$ rebuild. However, if a 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 $O(n)$ time of 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

  1. scottmcm commented on Dec 10, 2025

    @scottmcm
    Member

    We should not do this as written because I want to be able to trust that BinaryHeap<u32> actually works because I trust u32 -- same as how there's no way to get an invariants-violating HashSet<u32> or BTreeSet<u32> and such APIs have been previously rejected.

    (Said without considering whether an unsafe version should be added. The concern about doing as a safe function doesn't apply if it's changed to unsafe fn instead.)

  2. Dan54 commented on Dec 10, 2025

    @Dan54
    Author

    We should not do this as written because I want to be able to trust that BinaryHeap<u32> actually works because I trust u32 -- same as how there's no way to get an invariants-violating HashSet<u32> or BTreeSet<u32> and such APIs have been previously rejected.

    (Said without considering whether an unsafe version should be added. The concern about doing as a safe function doesn't apply if it's changed to unsafe fn instead.)

    I was mainly thinking about BinaryHeap's API when declaring it safe. I have no objection to making it unsafe if this is a concern.

  3. nia-e commented on Feb 10, 2026

    @nia-e
    Member

    @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 BinaryHeap is a (EDIT: particular layout of) max heap. Whether we want to stably guarantee a particular layout for BinaryHeap will need its own discussion.

  4. kennytm commented on Feb 11, 2026

    @kennytm
    Member

    with the caveat that we don't currently guarantee that BinaryHeap is a max heap.

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

  5. nia-e commented on Feb 11, 2026

    @nia-e
    Member

    I think you mean that we don't guarantee the exact layout how we'll flatten the heap

    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.

  6. scottmcm commented on Feb 13, 2026

    @scottmcm
    Member

    (After looking at the notes) @joshtriplett I think realistically BinaryHeap is 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 BinaryHeap in favour of a new MinMaxHeap that would have push + pop_min() + pop_max() and such, along with a sorted-order .drain() that would be DoubleEndedIterator so that next/next_back give the pop_min/pop_max. (Unlike BinaryHeap::drain which is just a wrapper for the Vec::drain and thus basically useless, and the unstable BinaryHeap::drain_sorted that actually gives them in reverse sorted order.) And that new type wouldn't have iter (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, and into_underlying_vec) explicitly.

  7. okaneco commented on Feb 13, 2026

    @okaneco

    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 Ord on a newtype or wrap your type in a std::cmp::Reverse wrapper.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::Reverse dance to access it. This friction can be a factor in making people bounce off the language.

    Footnotes

    1. https://doc.rust-lang.org/1.93.1/std/collections/struct.BinaryHeap.html#min-heap ↩

  8. joshtriplett commented on Feb 24, 2026

    @joshtriplett
    Member

    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.

  9. added
    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)
    on Mar 10, 2026
  10. joshtriplett commented on Mar 10, 2026

    @joshtriplett
    Member

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)api-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions