#priority-queue #binary-heap #priority #queue #heap

keyed_priority_queue

Priority queue that support changing priority or early remove by key

4 releases

0.4.2 Nov 15, 2023
0.4.1 Oct 24, 2021
0.3.2 Feb 21, 2021
0.3.1 Dec 21, 2020
0.1.2 Nov 24, 2019

#111 in Data structures

Download history 28063/week @ 2024-08-13 28257/week @ 2024-08-20 31709/week @ 2024-08-27 33368/week @ 2024-09-03 30100/week @ 2024-09-10 29329/week @ 2024-09-17 28534/week @ 2024-09-24 23533/week @ 2024-10-01 19873/week @ 2024-10-08 29004/week @ 2024-10-15 30785/week @ 2024-10-22 29016/week @ 2024-10-29 26255/week @ 2024-11-05 24467/week @ 2024-11-12 31345/week @ 2024-11-19 25802/week @ 2024-11-26

113,722 downloads per month
Used in 42 crates (10 directly)

MIT license

75KB
1.5K SLoC

Keyed Priority Queue

Crates.io tests MIT licensed Average time to resolve an issue Percentage of issues still open

A Rust library with priority queue that supports changing of priority item in queue or early removal. To change priority you need to use some key.

Minimal supported Rust version enforced by Cargo.toml.

Usage

An example of code:

use keyed_priority_queue::{KeyedPriorityQueue, Entry};

let mut queue = KeyedPriorityQueue::new();

// Currently queue is empty
assert_eq!(queue.peek(), None);

queue.push("Second", 4);
queue.push("Third", 3);
queue.push("First", 5);
queue.push("Fourth", 2);
queue.push("Fifth", 1);

// Peek return references to most important pair.
assert_eq!(queue.peek(), Some((&"First", &5)));

assert_eq!(queue.len(), 5);

// We can clone queue if both key and priority is clonable
let mut queue_clone = queue.clone();

// We can run consuming iterator on queue,
// and it will return items in decreasing order
for (key, priority) in queue_clone{
    println!("Priority of key {} is {}", key, priority);
}

// Popping always will return the biggest element
assert_eq!(queue.pop(), Some(("First", 5)));
// We can change priority of item by key:
queue.set_priority(&"Fourth", 10);
// And get it
assert_eq!(queue.get_priority(&"Fourth"), Some(&10));
// Now biggest element is Fourth
assert_eq!(queue.pop(), Some(("Fourth", 10)));
// We can also decrease priority!
queue.set_priority(&"Second", -1);
assert_eq!(queue.pop(), Some(("Third", 3)));
assert_eq!(queue.pop(), Some(("Fifth", 1)));
assert_eq!(queue.pop(), Some(("Second", -1)));
// Now queue is empty
assert_eq!(queue.pop(), None);

// There are Entry API if you want to avoid double hash lookups
match queue.entry("Entry"){
    Entry::Vacant(entry)=>entry.set_priority(10),
    Entry::Occupied(_)=>unreachable!(),
};

match queue.entry("Entry"){
    Entry::Vacant(_)=>unreachable!(),
    Entry::Occupied(entry)=>{
        assert_eq!(entry.get_key(), &"Entry");
        assert_eq!(entry.get_priority(), &10);
        entry.set_priority(5);
    },
};

// We can clear queue
queue.clear();
assert!(queue.is_empty());

Dependencies

~1MB
~14K SLoC