1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
use std::{cmp::Ordering, collections::BinaryHeap};

use crate::PriorityQueue;

#[derive(Debug, PartialEq, Eq, Clone)]
struct Node<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> {
    priority: P,
    data: T,
}

impl<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> PartialOrd for Node<P, T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.priority.partial_cmp(&other.priority)
    }
}

impl<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> Ord for Node<P, T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.priority
            .partial_cmp(&other.priority)
            .unwrap_or(Ordering::Less)
    }
}

#[derive(Debug)]
/// A priority queue implementation based on Rust's `BinaryHeap`.
/// Templated with `P` for priority and `T` for data.
///
/// - `P` must be `PartialOrd`, `PartialEq`, and `Eq`.
/// - `T` must be `PartialEq` and `Eq`.
///
/// If Node A and Node B have the same priority, but Node A was added before Node B,
/// then Node A will be prioritized over Node B.
/// See [`PriorityQueue`](trait.PriorityQueue.html) for more information.
///
/// # Examples
///
/// ```rust
/// # use queue_queue::rusty::RustyPriorityQueue;
/// # use queue_queue::PriorityQueue;
///
/// let mut prio = RustyPriorityQueue::<usize, String>::default();
/// prio.enqueue(2, "hello".to_string());
/// prio.enqueue(3, "julia".to_string());
/// prio.enqueue(1, "world".to_string());
/// prio.enqueue(3, "naomi".to_string());
///
/// let mut new_prio: RustyPriorityQueue<usize, String> = prio
///     .into_iter()
///     .map(|(priority, data)| (priority, data.to_owned() + " wow"))
///     .collect();
///
/// assert_eq!(new_prio.dequeue(), Some((3, "julia wow".to_string())));
/// assert_eq!(new_prio.dequeue(), Some((3, "naomi wow".to_string())));
/// assert_eq!(new_prio.dequeue(), Some((2, "hello wow".to_string())));
/// assert_eq!(new_prio.dequeue(), Some((1, "world wow".to_string())));
/// ```
pub struct RustyPriorityQueue<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> {
    queue: BinaryHeap<Node<P, T>>,
}

impl<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> Default for RustyPriorityQueue<P, T> {
    fn default() -> Self {
        Self {
            queue: BinaryHeap::new(),
        }
    }
}

impl<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> PriorityQueue<P, T>
    for RustyPriorityQueue<P, T>
{
    fn with_capacity(capacity: usize) -> Self {
        Self {
            queue: BinaryHeap::with_capacity(capacity),
        }
    }

    fn enqueue(&mut self, priority: P, data: T) {
        let node = Node { priority, data };

        self.queue.push(node);
    }

    fn dequeue(&mut self) -> Option<(P, T)> {
        let node = self.queue.pop();

        node.map(|n| (n.priority, n.data))
    }

    fn peek(&self) -> Option<(&P, &T)> {
        self.queue.peek().map(|node| (&node.priority, &node.data))
    }

    fn len(&self) -> usize {
        self.queue.len()
    }

    fn is_empty(&self) -> bool {
        self.queue.is_empty()
    }

    fn capacity(&self) -> usize {
        self.queue.capacity()
    }

    fn append(&mut self, mut other: Self) {
        self.queue.append(&mut other.queue);
    }

    /// Extend the priority queue with an iterator
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use queue_queue::rusty::RustyPriorityQueue;
    /// # use queue_queue::PriorityQueue;
    ///
    /// let mut prio = RustyPriorityQueue::<usize, String>::default();
    /// prio.extend(vec![(2, "world".to_string()), (3, "hello".to_string())]);
    /// assert_eq!(prio.dequeue(), Some((3, "hello".to_string())));
    /// assert_eq!(prio.dequeue(), Some((2, "world".to_string())));
    /// assert_eq!(prio.dequeue(), None);
    /// ```
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = (P, T)>,
    {
        self.queue.extend(iter.into_iter().map(|(x, y)| Node {
            priority: x,
            data: y,
        }));
    }

    fn reserve(&mut self, additional: usize) {
        self.queue.reserve(additional);
    }

    fn reserve_exact(&mut self, additional: usize) {
        self.queue.reserve_exact(additional);
    }

    fn shrink_to_fit(&mut self) {
        self.queue.shrink_to_fit();
    }

    fn shrink_to(&mut self, capacity: usize) {
        self.queue.shrink_to(capacity);
    }

    fn clear(&mut self) {
        self.queue.clear();
    }

    fn drain(&mut self) -> impl Iterator<Item = (P, T)> + '_ {
        self.queue.drain().map(|n| (n.priority, n.data))
    }

    fn contains(&self, data: &T) -> bool {
        self.queue.iter().any(|node| &node.data == data)
    }

    fn contains_at(&self, priority: &P, data: &T) -> bool {
        self.queue
            .iter()
            .any(|node| &node.data == data && &node.priority == priority)
    }

    fn remove(&mut self, data: &T) -> bool {
        let original_size = self.queue.len();
        self.queue.retain(|node| &node.data != data);
        let new_size = self.queue.len();

        original_size != new_size
    }

    fn remove_at(&mut self, priority: &P, data: &T) -> bool {
        let original_size = self.queue.len();
        self.queue.retain(|node| {
            if &node.priority == priority {
                &node.data != data
            } else {
                true
            }
        });
        let new_size = self.queue.len();

        original_size != new_size
    }

    fn max_node(&self) -> Option<(&P, &T)> {
        self.queue
            .iter()
            .max_by(|a, b| {
                a.priority
                    .partial_cmp(&b.priority)
                    .unwrap_or(Ordering::Equal)
            })
            .map(|node| (&node.priority, &node.data))
    }

    fn min_node(&self) -> Option<(&P, &T)> {
        self.queue
            .iter()
            .min_by(|a, b| {
                a.priority
                    .partial_cmp(&b.priority)
                    .unwrap_or(Ordering::Equal)
            })
            .map(|node| (&node.priority, &node.data))
    }
}

impl<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> RustyPriorityQueue<P, T> {
    #[must_use]
    /// Get an iterator over the priority queue
    pub const fn iter(&self) -> RustyPriorityQueueIterator<P, T> {
        RustyPriorityQueueIterator {
            internal: &self.queue,
            index: 0,
        }
    }

    #[must_use]
    /// Convert the priority queue into an iterator
    pub fn into_iter(self) -> RustyPriorityQueueIntoIterator<P, T> {
        RustyPriorityQueueIntoIterator { queue: self.queue }
    }

    /// Update the priority of an item in the queue.
    ///
    /// > This is a very slow operation!
    /// > * it uses unsafe `std::mem::transmute_copy` under the hhod to guarantee allocation of priority `P` on every possible scenario.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use queue_queue::rusty::RustyPriorityQueue;
    /// # use queue_queue::PriorityQueue;
    ///
    /// let mut prio = RustyPriorityQueue::<usize, String>::default();
    /// prio.enqueue(5, "julia".to_string());
    /// prio.enqueue(2, "hello".to_string());
    /// prio.enqueue(3, "julia".to_string());
    /// prio.enqueue(1, "world".to_string());
    /// prio.enqueue(3, "naomi".to_string());

    /// let ref_str = "julia".to_string();
    /// let mut new = prio.update(3, 7,&ref_str);

    /// assert_eq!(new.dequeue(), Some((7, "julia".to_string())));
    /// assert_eq!(new.dequeue(), Some((5, "julia".to_string())));
    /// assert_eq!(new.dequeue(), Some((3, "naomi".to_string())));
    /// assert_eq!(new.dequeue(), Some((2, "hello".to_string())));
    /// assert_eq!(new.dequeue(), Some((1, "world".to_string())));
    /// ```
    #[must_use]
    #[allow(clippy::needless_pass_by_value)]
    pub fn update(mut self, old: P, new: P, data: &T) -> Self {
        self.queue
            .drain()
            .map(|n| {
                if n.priority == old && &n.data == data {
                    let copy: P = unsafe { std::mem::transmute_copy(&new) };
                    (copy, n.data)
                } else {
                    (n.priority, n.data)
                }
            })
            .collect()
    }
}

/// An Iterator struct for `RustyPriorityQueue`
pub struct RustyPriorityQueueIterator<'b, P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> {
    internal: &'b BinaryHeap<Node<P, T>>,
    index: usize,
}

impl<'b, P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> Iterator
    for RustyPriorityQueueIterator<'b, P, T>
{
    type Item = (&'b P, &'b T);

    fn next(&mut self) -> Option<Self::Item> {
        let val = self
            .internal
            .iter()
            .nth(self.index)
            .map(|n| (&n.priority, &n.data));
        self.index += 1;
        val
    }
}

impl<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> FromIterator<(P, T)>
    for RustyPriorityQueue<P, T>
{
    fn from_iter<I: IntoIterator<Item = (P, T)>>(iter: I) -> Self {
        let mut collection = Self::default();

        for i in iter {
            collection.enqueue(i.0, i.1);
        }

        collection
    }
}

/// An `IntoIterator` struct for `RustyPriorityQueue`
pub struct RustyPriorityQueueIntoIterator<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> {
    queue: BinaryHeap<Node<P, T>>,
}

impl<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> Iterator
    for RustyPriorityQueueIntoIterator<P, T>
{
    type Item = (P, T);

    fn next(&mut self) -> Option<Self::Item> {
        self.queue.pop().map(|node| (node.priority, node.data))
    }
}

impl<P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> IntoIterator for RustyPriorityQueue<P, T> {
    type Item = (P, T);
    type IntoIter = RustyPriorityQueueIntoIterator<P, T>;

    fn into_iter(self) -> Self::IntoIter {
        RustyPriorityQueueIntoIterator { queue: self.queue }
    }
}

impl<'b, P: PartialOrd + PartialEq + Eq, T: PartialEq + Eq> IntoIterator
    for &'b RustyPriorityQueue<P, T>
{
    type IntoIter = RustyPriorityQueueIterator<'b, P, T>;
    type Item = (&'b P, &'b T);
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_is_empty() {
        let prio = RustyPriorityQueue::<usize, String>::default();

        assert_eq!(prio.len(), 0);
        assert!(prio.is_empty());
    }

    #[test]
    fn enqueue_once_has_size_1() {
        let mut prio = RustyPriorityQueue::<usize, String>::default();

        prio.enqueue(3, String::from("hello world"));
        assert_eq!(prio.len(), 1);
        assert_eq!(prio.peek(), Some((&3, &String::from("hello world"))));
    }

    #[test]
    fn dequeues_in_order() {
        let mut prio = RustyPriorityQueue::<usize, &str>::default();
        prio.enqueue(2, "hello");
        prio.enqueue(3, "julia");
        prio.enqueue(1, "world");
        prio.enqueue(3, "naomi");

        assert_eq!(prio.len(), 4);

        assert_eq!(prio.dequeue(), Some((3, "julia")));
        assert_eq!(prio.dequeue(), Some((3, "naomi")));
        assert_eq!(prio.dequeue(), Some((2, "hello")));
        assert_eq!(prio.dequeue(), Some((1, "world")));
    }

    #[test]
    fn iterate_over_queue() {
        let mut prio = RustyPriorityQueue::<usize, String>::default();
        prio.enqueue(2, "hello".to_string());
        prio.enqueue(3, "julia".to_string());
        prio.enqueue(1, "world".to_string());
        prio.enqueue(3, "naomi".to_string());

        let mut new_prio: RustyPriorityQueue<usize, String> = prio
            .iter()
            .map(|(priority, data)| (*priority, data.clone() + " wow"))
            .collect();

        assert_eq!(new_prio.dequeue(), Some((3, "julia wow".to_string())));
        assert_eq!(new_prio.dequeue(), Some((3, "naomi wow".to_string())));
        assert_eq!(new_prio.dequeue(), Some((2, "hello wow".to_string())));
        assert_eq!(new_prio.dequeue(), Some((1, "world wow".to_string())));
    }

    #[test]
    fn into_iterate_over_queue() {
        let mut prio = RustyPriorityQueue::<usize, String>::default();
        prio.enqueue(2, "hello".to_string());
        prio.enqueue(3, "julia".to_string());
        prio.enqueue(1, "world".to_string());
        prio.enqueue(3, "naomi".to_string());

        let ref_str = "julia".to_string();
        assert!(prio.contains(&ref_str));
        assert!(prio.contains_at(&3, &ref_str));
        assert!(!prio.contains_at(&2, &ref_str));

        let mut new_prio: RustyPriorityQueue<usize, String> = prio
            .into_iter()
            .map(|(priority, data)| (priority, data.to_owned() + " wow"))
            .collect();

        let new_ref_str = "julia wow".to_string();
        assert!(!new_prio.contains(&ref_str));
        assert!(!new_prio.contains_at(&3, &ref_str));
        assert!(!new_prio.contains_at(&2, &ref_str));
        assert!(new_prio.contains(&new_ref_str));
        assert!(new_prio.contains_at(&3, &new_ref_str));
        assert!(!new_prio.contains_at(&2, &new_ref_str));

        assert_eq!(new_prio.dequeue(), Some((3, "julia wow".to_string())));
        assert_eq!(new_prio.dequeue(), Some((3, "naomi wow".to_string())));
        assert_eq!(new_prio.dequeue(), Some((2, "hello wow".to_string())));
        assert_eq!(new_prio.dequeue(), Some((1, "world wow".to_string())));
    }

    #[test]
    fn node_order() {
        let node1 = Node {
            priority: 3,
            data: "hello".to_string(),
        };
        let node2 = Node {
            priority: 2,
            data: "julia".to_string(),
        };

        assert!(node1 > node2);
    }

    #[test]
    fn queue_with_capacity() {
        let prio = RustyPriorityQueue::<usize, String>::with_capacity(10);
        assert_eq!(prio.len(), 0);
        assert!(prio.is_empty());
        assert_eq!(prio.capacity(), 10);

        let default_prio = RustyPriorityQueue::<usize, String>::default();
        assert_eq!(default_prio.len(), 0);
        assert!(default_prio.is_empty());
        assert_eq!(default_prio.capacity(), 0);
    }

    #[test]
    fn appends_into_queue() {
        let mut prio = RustyPriorityQueue::<usize, &str>::default();
        assert_eq!(prio.len(), 0);
        prio.extend([(2, "hello"), (3, "julia"), (1, "world"), (3, "naomi")]);
        assert_eq!(prio.len(), 4);

        let mut append_prio = RustyPriorityQueue::<usize, &str>::default();
        assert_eq!(append_prio.len(), 0);
        append_prio.append(prio);
        assert_eq!(append_prio.len(), 4);

        assert_eq!(append_prio.dequeue(), Some((3, "julia")));
    }

    #[test]
    fn capacity_management() {
        let mut prio = RustyPriorityQueue::<usize, &str>::default();
        assert_eq!(prio.capacity(), 0);
        prio.reserve(3);
        assert_eq!(prio.capacity(), 4);
        prio.shrink_to_fit();
        assert_eq!(prio.capacity(), 0);
        prio.reserve_exact(3);
        assert_eq!(prio.capacity(), 3);
        prio.shrink_to(2);
        assert_eq!(prio.capacity(), 2);
    }

    #[test]
    fn clears_queue() {
        let mut prio = RustyPriorityQueue::<usize, String>::default();
        prio.enqueue(2, "hello".to_string());
        prio.enqueue(3, "julia".to_string());
        prio.enqueue(1, "world".to_string());
        prio.enqueue(3, "naomi".to_string());

        assert_eq!(prio.len(), 4);
        prio.clear();
        assert_eq!(prio.len(), 0);
    }

    #[test]
    fn drain_queue() {
        let mut prio = RustyPriorityQueue::<usize, String>::default();
        prio.enqueue(2, "hello".to_string());

        assert!(!prio.is_empty());

        for x in prio.drain() {
            assert_eq!(x, (2, "hello".to_string()));
        }

        assert!(prio.is_empty());
    }

    #[test]
    fn remove_node() {
        let mut prio = RustyPriorityQueue::<usize, String>::default();
        prio.enqueue(5, "julia".to_string());
        prio.enqueue(2, "hello".to_string());
        prio.enqueue(3, "julia".to_string());
        prio.enqueue(1, "world".to_string());
        prio.enqueue(3, "naomi".to_string());

        let ref_str = "julia".to_string();
        assert!(prio.remove(&ref_str));

        // assert_eq!(prio.dequeue(), Some((3, "julia".to_string())));
        assert_eq!(prio.dequeue(), Some((3, "naomi".to_string())));
        assert_eq!(prio.dequeue(), Some((2, "hello".to_string())));
        assert_eq!(prio.dequeue(), Some((1, "world".to_string())));
    }

    #[test]
    fn remove_node_at_prio() {
        let mut prio = RustyPriorityQueue::<usize, String>::default();
        prio.enqueue(5, "julia".to_string());
        prio.enqueue(2, "hello".to_string());
        prio.enqueue(3, "julia".to_string());
        prio.enqueue(1, "world".to_string());
        prio.enqueue(3, "naomi".to_string());

        let ref_str = "julia".to_string();
        assert!(prio.remove_at(&3, &ref_str));

        assert_eq!(prio.dequeue(), Some((5, "julia".to_string())));
        assert_eq!(prio.dequeue(), Some((3, "naomi".to_string())));
        assert_eq!(prio.dequeue(), Some((2, "hello".to_string())));
        assert_eq!(prio.dequeue(), Some((1, "world".to_string())));
    }

    #[test]
    fn update() {
        let mut prio = RustyPriorityQueue::<usize, String>::default();
        prio.enqueue(5, "julia".to_string());
        prio.enqueue(2, "hello".to_string());
        prio.enqueue(3, "julia".to_string());
        prio.enqueue(1, "world".to_string());
        prio.enqueue(3, "naomi".to_string());

        let ref_str = "julia".to_string();
        let mut new = prio.update(3, 7, &ref_str);

        assert_eq!(new.dequeue(), Some((7, "julia".to_string())));
        assert_eq!(new.dequeue(), Some((5, "julia".to_string())));
        assert_eq!(new.dequeue(), Some((3, "naomi".to_string())));
        assert_eq!(new.dequeue(), Some((2, "hello".to_string())));
        assert_eq!(new.dequeue(), Some((1, "world".to_string())));
    }

    #[test]
    fn min_max() {
        let mut prio = RustyPriorityQueue::<usize, String>::default();
        prio.enqueue(5, "julia".to_string());
        prio.enqueue(2, "hello".to_string());
        prio.enqueue(3, "julia".to_string());
        prio.enqueue(1, "world".to_string());
        prio.enqueue(3, "naomi".to_string());

        assert_eq!(prio.max_node(), Some((&5, &"julia".to_string())));
        assert_eq!(prio.min_node(), Some((&1, &"world".to_string())));
    }
}