usage/
usage.rs

1use std::cmp::Reverse;
2
3use fpq::PriorityQueue;
4
5fn main() {
6    // a score function that returns the length of a string
7    let score_fn = Box::new(|s: &String| s.len());
8    // create a new priority queue with the score function
9    let mut queue = PriorityQueue::new(score_fn);
10
11    // the queue is empty at the beginning
12    assert!(queue.peek().is_none());
13
14    // push some items into the queue
15    // the score function is used to calculate the score of each item
16    queue.push("a".to_string()); // score = 1
17    queue.push("ccc".to_string()); // score = 3
18    queue.push("bb".to_string()); // score = 2
19
20    // you can also push an item with a explicit score
21    queue.push_with_score("b".to_string(), 10); // score = 10
22
23    // peek the item with the highest priority
24    assert_eq!(queue.peek(), Some((10, &"b".to_string())));
25
26    // pop the item with the highest priority
27    assert_eq!(queue.pop(), Some((10, "b".to_string())));
28    assert_eq!(queue.pop(), Some((3, "ccc".to_string())));
29    assert_eq!(queue.pop(), Some((2, "bb".to_string())));
30    assert_eq!(queue.pop(), Some((1, "a".to_string())));
31
32    // the queue is empty again
33    assert!(queue.peek().is_none());
34
35    // you can also use a reverse order
36    let score_fn = Box::new(|s: &String| Reverse(s.len()));
37    let mut queue = PriorityQueue::new(score_fn);
38
39    queue.push("a".to_string()); // score = -1
40    queue.push("ccc".to_string()); // score = -3
41    queue.push("bb".to_string()); // score = -2
42
43    // remember to use Reverse when pushing an item with an explicit score
44    queue.push_with_score("b".to_string(), Reverse(10)); // score = -10
45
46    assert_eq!(queue.peek(), Some((Reverse(1), &"a".to_string())));
47    assert_eq!(queue.pop(), Some((Reverse(1), "a".to_string())));
48    assert_eq!(queue.pop(), Some((Reverse(2), "bb".to_string())));
49    assert_eq!(queue.pop(), Some((Reverse(3), "ccc".to_string())));
50    assert_eq!(queue.pop(), Some((Reverse(10), "b".to_string())));
51
52    assert!(queue.peek().is_none());
53}