limited-queue 0.2.0

a limited queue that overrides the oldest data if trying to push a data when the queue is full.
Documentation
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! # LimitedQueue
//!
//! `LimitedQueue<T>` is a limited queue that
//! overrides the oldest data if trying to
//! push a data when the queue is full.
//!
//! All operations are of `O(1)` complexity,
//! except the constructor with `O(Vec::with_capacity)`.

use std::{
    marker::PhantomData,
    mem::{replace, take},
};

/// A circular queue that overrides the oldest data
/// if trying to push data when queue is full.
///
/// All operations are of `O(1)` complexity,
/// except the constructor with `O(Vec::with_capacity)`.
///
/// # Example
///
/// ```
/// let mut q = limited_queue::LimitedQueue::with_capacity(5);
/// // push_ret: [None x 5, 0, 1, ..., 4]
/// let push_ret = [[None; 5], core::array::from_fn(|i| Some(i))].concat();
/// for (i, pr) in (0..10).zip(push_ret) {
///     assert_eq!(q.push(i), pr);
/// }
/// for (n, element) in q.iter().enumerate() {
///     assert_eq!(element.clone(), q[n]); // 5, 6, 7, 8, 9
///     assert_eq!(element.clone(), n + 5); // 5, 6, 7, 8, 9
/// }
/// ```
///
/// # Error
///
/// For indexing, no bound check will occur, so please check
/// the size of the queue with `len` method before subscription.
///
/// If you need boundary check, please use `get` method.
#[derive(Debug)]
pub struct LimitedQueue<T> {
    q: Vec<Option<T>>,
    front: usize,
    rear: usize,
    sz: usize,
}

impl<T> LimitedQueue<T> {
    /// Vec-like constructor
    ///
    /// ```
    /// use limited_queue::LimitedQueue;
    ///
    /// let mut q = LimitedQueue::with_capacity(2);
    ///
    /// assert_eq!(q.push(1), None);
    /// assert_eq!(q.push(2), None);
    ///
    /// // first element popped since the capacity is 2
    /// assert_eq!(q.push(3), Some(1));
    ///
    /// assert_eq!(q.peek(), Some(&2));
    /// assert_eq!(q.pop(), Some(2));
    /// assert_eq!(q.peek(), Some(&3));
    /// assert_eq!(q.pop(), Some(3));
    /// ```
    ///
    /// @param `cap` Capacity (limit size) of the queue
    #[inline]
    pub fn with_capacity(cap: usize) -> LimitedQueue<T> {
        if cap == 0 {
            panic!("Cannot create a LimitedQueue with zero capacity");
        }
        let mut q = Vec::with_capacity(cap);
        q.resize_with(cap, Option::default);

        LimitedQueue {
            q,
            front: 0usize,
            rear: 0usize,
            sz: 0usize,
        }
    }

    /// Get the element at position `idx`,
    /// a.k.a. the position from the start of queue
    ///
    /// ```
    /// use limited_queue::LimitedQueue;
    ///
    /// let mut q = LimitedQueue::with_capacity(2);
    /// q.push(1);
    /// assert_eq!(q.get(100), None);
    /// ```
    #[inline]
    pub fn get(&self, idx: usize) -> Option<&T> {
        if idx >= self.sz {
            None
        } else {
            Some(&self[idx])
        }
    }

    /// Peek the oldest element at the front of the queue
    ///
    /// ```
    /// use limited_queue::LimitedQueue;
    ///
    /// let mut q = LimitedQueue::with_capacity(1);
    ///
    /// q.push(1234);
    /// assert_eq!(q.peek(), Some(&1234));
    /// assert_eq!(q.pop(), Some(1234));
    /// assert_eq!(q.peek(), None);
    /// ```
    #[inline]
    pub fn peek(&self) -> Option<&T> {
        if self.is_empty() {
            None
        } else {
            self.q[self.front].as_ref()
        }
    }

    /// Push a new element into queue,
    /// removing the oldest element if the queue is full
    #[inline]
    pub fn push(&mut self, ele: T) -> Option<T> {
        let mut popped = None;
        if self.is_full() {
            // popped = self.pop();
            // use `replace` so no implicit `Default` will be called
            popped = replace(&mut self.q[self.rear], Some(ele));
            // and move forth the front idx to simulate `pop` operation
            self.front = self.next_idx(self.front);
        } else {
            let _ = std::mem::replace(&mut self.q[self.rear], Some(ele));
            self.sz += 1;
        }
        self.rear = self.next_idx(self.rear);
        popped
    }

    /// Inner method: next index of the inner vector
    #[inline]
    fn next_idx(&self, idx: usize) -> usize {
        (idx + 1) % self.q.capacity()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.sz == 0
    }

    #[inline]
    pub fn is_full(&self) -> bool {
        self.sz == self.q.capacity()
    }

    /// Get queue length
    ///
    /// ```
    /// use limited_queue::LimitedQueue;
    ///
    /// let mut q = LimitedQueue::with_capacity(3);
    ///
    /// q.push(1234);
    /// assert_eq!(q.len(), 1);
    /// q.push(1234);
    /// assert_eq!(q.len(), 2);
    /// q.push(1234);
    /// assert_eq!(q.len(), 3);
    /// q.push(1234);
    /// assert_eq!(q.len(), 3);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.sz
    }

    /// To traverse all the elements in
    /// `LimitedQueue`, for example:
    ///
    /// ```
    /// use limited_queue::LimitedQueue;
    ///
    /// let mut q = LimitedQueue::with_capacity(5);
    /// for i in 0..10 {
    ///     q.push(i);
    /// }
    /// for (&n, element) in q.iter().zip(5usize..=9) {
    ///     // will be 5, 6, 7, 8, 9 since 0 ~ 4
    ///     // are popped because the queue is full
    ///     assert_eq!(element.clone(), n);
    /// }
    /// ```
    #[inline]
    pub fn iter(&self) -> LimitedQueueIterator<T> {
        LimitedQueueIterator {
            lq: self,
            front_idx: 0,
            back_idx: self.sz,
        }
    }

    /// Returns a mutable iterator over the queue.
    ///
    /// # Example
    ///
    /// ```
    /// use limited_queue::LimitedQueue;
    ///
    /// let mut q = LimitedQueue::with_capacity(3);
    /// q.push(1);
    /// q.push(2);
    ///
    /// for element in q.iter_mut() {
    ///     *element *= 2;
    /// }
    ///
    /// assert_eq!(q.pop(), Some(2));
    /// assert_eq!(q.pop(), Some(4));
    /// assert_eq!(q.pop(), None);
    /// ```
    #[inline]
    pub fn iter_mut(&mut self) -> LimitedQueueIteratorMut<T> {
        let len = self.sz;
        let cap = self.q.capacity();
        let front = self.front;
        let q_ptr = self.q.as_mut_ptr(); // get raw pointer to Vec's buffer
        LimitedQueueIteratorMut {
            q_ptr,
            front,
            capacity: cap,
            front_idx: 0,
            back_idx: len,
            _marker: PhantomData, // PhantomData for 'a lifetime
        }
    }

    /// `O(1)` method to (lazily) clear all the elements
    ///
    /// ```
    /// use limited_queue::LimitedQueue;
    ///
    /// let mut q = LimitedQueue::with_capacity(5);
    /// for i in 0..10 {
    ///     q.push(i);
    /// }
    /// q.clear();
    /// assert_eq!(q.peek(), None);
    /// assert_eq!(q.is_empty(), true);
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.front = 0;
        self.rear = 0;
        self.sz = 0;
    }

    /// private method of boundary check and indexing
    #[inline]
    fn indexing(&self, idx: usize) -> usize {
        if idx >= self.sz {
            panic!("Invalid subscription index: {}", idx)
        }
        (idx + self.front) % self.q.capacity()
    }

    /// Pop the first element from queue,
    /// will replace the element in queue
    ///
    /// ```
    /// use limited_queue::LimitedQueue;
    ///
    /// let mut q = LimitedQueue::with_capacity(1);
    ///
    /// q.push(1234);
    /// assert_eq!(q.pop(), Some(1234));
    /// assert_eq!(q.pop(), None);
    /// ```
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        if self.is_empty() {
            None
        } else {
            let ret = take(&mut self.q[self.front]);
            self.front = self.next_idx(self.front);
            self.sz -= 1;
            ret
        }
    }
}

impl<T> std::ops::Index<usize> for LimitedQueue<T> {
    type Output = T;

    #[inline]
    fn index(&self, idx: usize) -> &Self::Output {
        let real_idx = self.indexing(idx);
        self.q[real_idx].as_ref().unwrap()
    }
}

impl<T> std::ops::IndexMut<usize> for LimitedQueue<T> {
    #[inline]
    fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
        let real_idx = self.indexing(idx);
        self.q[real_idx].as_mut().unwrap()
    }
}

pub struct LimitedQueueIterator<'a, T> {
    lq: &'a LimitedQueue<T>,
    front_idx: usize,
    back_idx: usize,
}

#[cfg(not(tarpaulin_include))]
impl<'a, T> Iterator for LimitedQueueIterator<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.front_idx == self.back_idx {
            None // the end of iteration
        } else {
            let cur_idx = self.front_idx;
            self.front_idx += 1;
            Some(&self.lq[cur_idx])
        }
    }
}

impl<'a, T> DoubleEndedIterator for LimitedQueueIterator<'a, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.front_idx == self.back_idx {
            None // the end of iteration
        } else {
            self.back_idx -= 1;
            let cur_idx = self.back_idx;
            Some(&self.lq[cur_idx])
        }
    }
}

/// A mutable, double-ended iterator over a `LimitedQueue`.
pub struct LimitedQueueIteratorMut<'a, T> {
    q_ptr: *mut Option<T>, // raw pointer to the Vec's data
    front: usize,          // internal Vec's front index
    capacity: usize,
    front_idx: usize,                // logical queue index (0..sz)
    back_idx: usize,                 // logical queue index (0..sz)
    _marker: PhantomData<&'a mut T>, // marker for 'a lifetime
}

impl<'a, T> Iterator for LimitedQueueIteratorMut<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.front_idx == self.back_idx {
            None
        } else {
            let cur_idx = self.front_idx;
            self.front_idx += 1;
            let real_idx = (cur_idx + self.front) % self.capacity;

            unsafe {
                // get pointer to the real_idx-th element in Vec
                let elem_ptr = self.q_ptr.add(real_idx);

                // convert raw pointer back to an 'a lifetime mutable reference
                // this is safe because:
                // 1. _marker ensures 'a is the lifetime of LimitedQueueMutIterator
                // 2. we ensure real_idx is within self.q.capacity()
                // 3. cur_idx < self.sz, so this position must be Some(T)
                let opt_ref = &mut *elem_ptr;

                // .unwrap() is safe because
                // logical index (cur_idx) < self.sz,
                // which means self.q[real_idx] must be Some(T)
                Some(opt_ref.as_mut().unwrap())
            }
        }
    }
}

impl<'a, T> DoubleEndedIterator for LimitedQueueIteratorMut<'a, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.front_idx == self.back_idx {
            None
        } else {
            // move index back
            self.back_idx -= 1;
            let cur_idx = self.back_idx;
            let real_idx = (cur_idx + self.front) % self.capacity;

            unsafe {
                let elem_ptr = self.q_ptr.add(real_idx);
                let opt_ref = &mut *elem_ptr;

                // .unwrap() is also safe here
                Some(opt_ref.as_mut().unwrap())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::panic;

    use rand::Rng;

    use crate::LimitedQueue;

    // Helper struct that doesn't implement Default
    #[derive(Debug, PartialEq, Eq, Clone)]
    struct NoDefault(i32);

    #[test]
    fn test_pop_no_default() {
        let mut q = LimitedQueue::with_capacity(2);
        q.push(NoDefault(1));
        q.push(NoDefault(2));
        assert_eq!(q.push(NoDefault(3)), Some(NoDefault(1)));
        assert_eq!(q.peek(), Some(&NoDefault(2)));
        assert_eq!(q.pop(), Some(NoDefault(2)));
        assert_eq!(q.pop(), Some(NoDefault(3)));
        assert_eq!(q.pop(), None);
    }

    #[test]
    fn test_iter() {
        let mut q = crate::LimitedQueue::with_capacity(5);
        // push_ret: [None x 5, 0, 1, ..., 4]
        let push_ret = [[None; 5], core::array::from_fn(|i| Some(i))].concat();
        for (i, pr) in (0..10).zip(push_ret) {
            assert_eq!(q.push(i), pr);
        }
        assert_eq!(q.len(), 5);
        for (n, element) in q.iter().enumerate() {
            assert_eq!(element.clone(), q[n]); // 5, 6, 7, 8, 9
            assert_eq!(element.clone(), n + 5); // 5, 6, 7, 8, 9
        }

        // test DoubleEndedIterator
        for (n, element) in q.iter().rev().enumerate() {
            assert_eq!(element.clone(), q[4 - n]); // 5, 6, 7, 8, 9
            assert_eq!(element.clone(), 9 - n); // 5, 6, 7, 8, 9
        }
    }

    #[test]
    fn test_iter_mut() {
        let mut q = LimitedQueue::with_capacity(5);
        for i in 0..5 {
            q.push(i); // 0, 1, 2, 3, 4
        }

        for element in q.iter_mut() {
            *element += 10;
        }

        // Queue should now contain 10, 11, 12, 13, 14
        for (n, element) in q.iter().enumerate() {
            assert_eq!(*element, n + 10);
        }

        // Test push overflow with modified data
        assert_eq!(q.push(99), Some(10)); // pops 10
        assert_eq!(q.peek(), Some(&11));
    }

    #[test]
    fn test_double_ended_iter_mut() {
        let mut q = LimitedQueue::with_capacity(5);
        for i in 0..5 {
            q.push(i); // 0, 1, 2, 3, 4
        }

        // Modify from both ends
        let mut iter_mut = q.iter_mut();
        *iter_mut.next().unwrap() = 100; // 0 -> 100
        *iter_mut.next_back().unwrap() = 400; // 4 -> 400
        *iter_mut.next().unwrap() = 200; // 1 -> 200
        *iter_mut.next_back().unwrap() = 300; // 3 -> 300
                                              // 2 is untouched

        // Check final state
        let mut iter = q.iter();
        assert_eq!(iter.next(), Some(&100));
        assert_eq!(iter.next(), Some(&200));
        assert_eq!(iter.next(), Some(&2));
        assert_eq!(iter.next(), Some(&300));
        assert_eq!(iter.next(), Some(&400));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn test_change_size() {
        const MAX_SZ: usize = 25;
        let mut q: LimitedQueue<i32> = crate::LimitedQueue::with_capacity(MAX_SZ);
        let mut sz = 0;
        let mut rng = rand::thread_rng();

        for _ in 0..1000 {
            let op = rng.gen_range(0..=2);
            match op {
                0 => {
                    if q.push(rng.gen()).is_none() {
                        sz += 1
                    };
                }
                1 => {
                    if q.pop().is_some() {
                        sz -= 1
                    };
                }
                _ => {
                    assert!(match sz {
                        0 => q.is_empty() && q.pop().is_none() && q.peek().is_none(),
                        MAX_SZ => q.is_full(),
                        _ => sz == q.len() && sz < MAX_SZ,
                    });
                }
            };
        }
    }

    #[test]
    #[should_panic]
    fn test_zero_len_invalid_indexing() {
        LimitedQueue::<i32>::with_capacity(0)[0];
    }

    #[test]
    fn test_invalid_indexing() {
        // shadow out panic message for unwind in the loop
        let old_hook = panic::take_hook();
        panic::set_hook(Box::new(|_info| {}));

        let mut q = LimitedQueue::with_capacity(5);
        q.push(1);
        for i in 5..100 {
            let invalid_access = || q[i];
            let should_be_false = panic::catch_unwind(invalid_access).is_err();
            if !should_be_false {
                // reset panic hook to show error message
                panic::set_hook(old_hook);
                // panic with reason
                panic!("Indexing with idx: {} cannot trigger panic.", i);
            }
        }

        panic::set_hook(old_hook);
    }

    #[test]
    fn test_clear() {
        let mut q = LimitedQueue::with_capacity(10);

        // Test clear on empty
        q.clear();
        assert_eq!(q.len(), 0);
        assert!(q.is_empty());

        // Test clear on partially full
        for _ in 0..3 {
            q.push(1);
        }
        assert_eq!(q.len(), 3);
        q.clear();
        assert_eq!(q.len(), 0);
        assert_eq!(q.peek(), None);
        assert!(q.is_empty());

        // Test clear on full
        for i in 0..10 {
            q.push(i);
        }
        assert!(q.is_full());
        q.clear();
        assert!(q.is_empty());
        assert_eq!(q.len(), 0);
        assert_eq!(q.peek(), None);

        // Test functionality after clear
        assert_eq!(q.push(100), None);
        assert_eq!(q.len(), 1);
        assert_eq!(q.peek(), Some(&100));
        assert_eq!(q.pop(), Some(100));
        assert_eq!(q.len(), 0);
        assert!(q.is_empty());
    }

    #[test]
    fn test_capacity_one() {
        let mut q = LimitedQueue::with_capacity(1);
        assert!(q.is_empty());
        assert_eq!(q.push(1), None);
        assert!(q.is_full());
        assert_eq!(q.peek(), Some(&1));
        assert_eq!(q.push(2), Some(1)); // Overwrite
        assert!(q.is_full());
        assert_eq!(q.peek(), Some(&2));
        assert_eq!(q.pop(), Some(2));
        assert!(q.is_empty());
        assert_eq!(q.peek(), None);
        assert_eq!(q.pop(), None);
        assert_eq!(q.push(3), None);
        assert_eq!(q.len(), 1);
        assert_eq!(q.peek(), Some(&3));
    }

    #[test]
    #[should_panic]
    fn test_capacity_zero_push_panic() {
        let mut q = LimitedQueue::<i32>::with_capacity(0);
        q.push(1); // This should panic
    }

    #[test]
    fn test_get_method() {
        let mut q = LimitedQueue::with_capacity(3);
        assert_eq!(q.get(0), None); // Empty
        assert_eq!(q.get(1), None);

        q.push(10); // 10
        q.push(20); // 10, 20
        assert_eq!(q.get(0), Some(&10));
        assert_eq!(q.get(1), Some(&20));
        assert_eq!(q.get(2), None); // Out of bounds (len)

        q.push(30); // 10, 20, 30 (full)
        assert_eq!(q.get(2), Some(&30));
        assert_eq!(q.get(3), None);

        q.push(40); // 20, 30, 40 (wrapped)
        assert_eq!(q.get(0), Some(&20));
        assert_eq!(q.get(1), Some(&30));
        assert_eq!(q.get(2), Some(&40));
        assert_eq!(q.get(3), None); // Out of bounds (len)
    }

    #[test]
    fn test_iter_empty() {
        let mut q = LimitedQueue::<i32>::with_capacity(5);
        assert_eq!(q.iter().next(), None);
        assert_eq!(q.iter().next_back(), None);
        assert_eq!(q.iter_mut().next(), None);
        assert_eq!(q.iter_mut().next_back(), None);
    }

    #[test]
    fn test_iter_mixed() {
        let mut q = LimitedQueue::with_capacity(5);
        for i in 0..5 {
            q.push(i); // 0, 1, 2, 3, 4
        }

        let mut iter = q.iter();
        assert_eq!(iter.next(), Some(&0));
        assert_eq!(iter.next_back(), Some(&4));
        assert_eq!(iter.next(), Some(&1));
        assert_eq!(iter.next_back(), Some(&3));
        assert_eq!(iter.next(), Some(&2));
        assert_eq!(iter.next(), None);
        assert_eq!(iter.next_back(), None);
    }

    #[test]
    fn test_index_mut() {
        let mut q = LimitedQueue::with_capacity(3);
        q.push(1);
        q.push(2); // q = [1, 2]

        q[0] = 100; // Test IndexMut
        q[1] = 200;

        assert_eq!(q.get(0), Some(&100));
        assert_eq!(q.get(1), Some(&200));
    }

    #[test]
    fn test_debug_format() {
        let mut q = LimitedQueue::with_capacity(3);
        q.push(1);
        q.push(2);

        // Test whether debug works as expected
        let formatted = format!("{:?}", q);
        assert!(formatted.contains("LimitedQueue"));
        assert!(formatted.contains("Some(1)"));
        assert!(formatted.contains("Some(2)"));
    }

    #[test]
    #[should_panic(expected = "Invalid subscription index: 1")]
    fn test_indexing_panic_simple() {
        let mut q = LimitedQueue::with_capacity(3);
        q.push(1); // sz = 1
        let _ = q[1]; // Accessing q[1] when sz=1 should panic
    }
}