squeue 0.10.3

SQueue is a sized queue.
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
// Copyright (C) 2024 Christian Mauduit <ufoot@ufoot.org>

use crate::drain::Drain;
use std::collections::vec_deque::IntoIter;
use std::collections::VecDeque;
use std::fmt;

/// FIFO queue with a fixed capacity.
///
/// This is in a LRU package because it has a semantic behavior
/// similar to an LRU, in the sense that when capacity is reached,
/// the oldest element is dropped.
///
/// In practice it in just some syntaxic sugar over a `VecDeque`,
/// and data is dropped when you exceed capacity.
///
/// # Examples
///
/// ```
/// use squeue::Queue;
///
/// let mut queue: Queue<usize> = Queue::new(3);
/// assert_eq!(None, queue.push(1));
/// assert_eq!(None, queue.push(2));
/// assert_eq!(None, queue.push(3));
/// assert_eq!(Some(1), queue.push(4));
/// assert_eq!(3, queue.len());
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub struct Queue<T> {
    capacity: usize,
    data: VecDeque<T>,
}

/// Pretty-print queue content.
///
/// Prints the next element to be popped, and the len/capacity.
///
/// # Examples
///
/// ```
/// use squeue::Queue;
///
/// let mut queue = Queue::new(100);
/// queue.push(123);
/// queue.push(4);
/// queue.push(5);
/// assert_eq!("{ next: 123, len: 3, capacity: 100 }", format!("{}", queue));
/// queue.clear();
/// assert_eq!("{ len: 0, capacity: 100 }", format!("{}", queue));
/// ```
impl<T> fmt::Display for Queue<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.peek() {
            Some(item) => write!(
                f,
                "{{ next: {}, len: {}, capacity: {} }}",
                item,
                self.len(),
                self.capacity()
            ),
            None => write!(
                f,
                "{{ len: {}, capacity: {} }}",
                self.len(),
                self.capacity()
            ),
        }
    }
}

impl<T> Queue<T> {
    /// Create a new queue.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let queue: Queue<String> = Queue::new(10);
    /// assert_eq!(10, queue.capacity());
    /// ```
    pub fn new(capacity: usize) -> Self {
        Queue {
            capacity,
            data: VecDeque::with_capacity(capacity + 1),
        }
    }

    /// Return queue length.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue: Queue<&str> = Queue::new(10);
    /// assert_eq!(0, queue.len());
    /// queue.push("x");
    /// queue.push("y");
    /// assert_eq!(2, queue.len());
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Return queue capacity.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue: Queue<f64> = Queue::new(100);
    /// assert_eq!(100, queue.capacity());
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns true if queue is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue: Queue<String> = Queue::new(100);
    /// assert!(queue.is_empty());
    /// queue.push(String::from("abc"));
    /// assert!(!queue.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Returns true if queue is full.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue: Queue<usize> = Queue::new(10);
    /// assert!(!queue.is_full());
    /// for i in 0..10 {
    ///     queue.push(i);
    /// }
    /// assert!(queue.is_full());
    /// ```
    #[inline]
    pub fn is_full(&self) -> bool {
        self.len() >= self.capacity()
    }

    /// Clear all data.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue: Queue<String> = Queue::new(100);
    /// queue.push(String::from("abc"));
    /// queue.clear();
    /// assert!(queue.is_empty());
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.data.clear()
    }

    /// Resize queue.
    ///
    /// Returns the number of dropped items, if any.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue: Queue<usize> = Queue::new(10);
    /// assert_eq!(10, queue.capacity());
    /// assert_eq!(0, queue.resize(100));
    /// assert_eq!(100, queue.capacity());
    /// for i in 0..1000 {
    ///     queue.push(i);
    /// }
    /// assert_eq!(100, queue.len());
    /// assert_eq!(90, queue.resize(10));
    /// assert_eq!(10, queue.capacity());
    /// assert_eq!(10, queue.len());
    /// assert_eq!(Some(990), queue.pop());
    /// ```
    pub fn resize(&mut self, capacity: usize) -> usize {
        self.capacity = capacity;
        let old_size = self.data.len();
        if old_size > capacity {
            self.data.truncate(capacity);
            old_size - capacity
        } else {
            if capacity > old_size {
                self.data.try_reserve(capacity + 1 - old_size).ok();
            }
            0
        }
    }

    /// Push data into the queue.
    ///
    /// If the queue is full and data needs to be dropped,
    /// that data is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue: Queue<usize> = Queue::new(2);
    /// assert_eq!(None, queue.push(1));
    /// assert_eq!(None, queue.push(10));
    /// assert_eq!(Some(1), queue.push(100));
    /// assert_eq!(Some(10), queue.push(1000));
    /// assert_eq!(2, queue.len());
    /// ```
    pub fn push(&mut self, item: T) -> Option<T> {
        if self.capacity == 0 {
            return None;
        }
        self.data.push_front(item);
        if self.data.len() > self.capacity {
            self.pop()
        } else {
            None
        }
    }

    /// Pop data from the queue.
    ///
    /// The oldest item is returned, this works in FIFO mode.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue: Queue<usize> = Queue::new(5);
    /// assert_eq!(None, queue.pop());
    /// assert_eq!(None, queue.push(1));
    /// assert_eq!(Some(1), queue.pop());
    /// assert_eq!(None, queue.push(2));
    /// assert_eq!(None, queue.push(3));
    /// assert_eq!(Some(2), queue.pop());
    /// assert_eq!(1, queue.len());
    /// ```
    pub fn pop(&mut self) -> Option<T> {
        self.data.pop_back()
    }

    /// Peek data, get it without removing it.
    ///
    /// This gives an insight on what pop() would return.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue: Queue<usize> = Queue::new(5);
    /// assert_eq!(None, queue.peek());
    /// assert_eq!(None, queue.push(1));
    /// assert_eq!(None, queue.push(2));
    /// assert_eq!(Some(&1), queue.peek());
    /// ```
    pub fn peek(&self) -> Option<&T> {
        // May sound a little convoluted, why not use
        // 0 as the "where we pop things" just do
        // queue.get(0). The reason is that if we
        // do this, truncate() does not work as expected
        // and drops recent entries.
        let len = self.data.len();
        if len > 0 {
            self.data.get(len - 1)
        } else {
            None
        }
    }

    /// Creates an iterator which drains the queue.
    ///
    /// Use this when you want to get all the items, at a given point,
    /// and free space in the queue.
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue = Queue::new(10);
    /// queue.push(1);
    /// queue.push(10);
    /// let drain = queue.drain();
    /// assert_eq!(0, queue.len());
    /// assert_eq!(2, drain.count());
    /// ```
    pub fn drain(&mut self) -> Drain<T> {
        Drain::new(self)
    }
}

impl<T> std::iter::IntoIterator for Queue<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    /// Creates an iterator over the queue.
    ///
    /// Takes ownership.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue = Queue::new(10);
    /// queue.push(4);
    /// queue.push(5);
    /// queue.push(6);
    ///
    /// let sum=queue.into_iter().sum();
    /// assert_eq!(15, sum);
    /// ```
    fn into_iter(self) -> IntoIter<T> {
        self.data.into_iter()
    }
}

impl<T> FromIterator<T> for Queue<T> {
    /// Creates a new queue from an iterator.
    ///
    /// With this, you can use collect() to build a queue.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let src: Vec<usize> = vec![4, 5, 6];
    ///
    /// let mut queue = src.into_iter().collect::<Queue<usize>>();
    /// assert_eq!(Some(4), queue.pop());
    /// assert_eq!(Some(5), queue.pop());
    /// assert_eq!(Some(6), queue.pop());
    /// assert_eq!(None, queue.pop());
    /// assert_eq!(3, queue.capacity());
    /// ```
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut queue = Queue::new(0);

        for i in iter {
            queue.resize(queue.len() + 1);
            queue.push(i);
        }

        queue
    }
}

impl<T> PartialEq<Queue<T>> for Queue<T>
where
    T: PartialEq,
{
    /// Compares two queues. Capacity, content and order must match.
    ///
    /// # Examples
    ///
    /// ```
    /// use squeue::Queue;
    ///
    /// let mut queue1 = Queue::new(10);
    /// queue1.push("Alice");
    /// queue1.push("Bob");
    /// let mut queue2 = Queue::new(10);
    /// queue2.push("Oscar");
    /// queue2.push("Alice");
    /// queue2.push("Bob");
    /// assert_ne!(&queue1, &queue2);
    /// queue2.pop();
    /// assert_eq!(&queue1, &queue2);
    /// ```
    fn eq(&self, other: &Self) -> bool {
        if self.capacity != other.capacity {
            return false;
        }
        if self.len() != other.len() {
            return false;
        }
        let mut iter_other = other.data.iter();
        for self_v in self.data.iter() {
            match iter_other.next() {
                Some(other_v) => {
                    if self_v != other_v {
                        return false;
                    }
                }
                None => return false,
            }
        }
        true
    }
}

impl<T> Eq for Queue<T> where T: Eq {}

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

    #[test]
    fn test_queue_0() {
        let mut queue: Queue<usize> = Queue::new(0);
        assert_eq!(None, queue.push(42));
        assert_eq!(None, queue.pop());
        assert_eq!(0, queue.capacity());
        assert_eq!(true, queue.is_full());
        assert_eq!(true, queue.is_empty());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_json() {
        use serde_json::json;

        let mut queue1 = Queue::<usize>::new(10);

        queue1.push(1);
        queue1.push(2);

        let export = json!(&queue1).to_string();

        assert_eq!("{\"capacity\":10,\"data\":[2,1]}", export);

        let queue2: Queue<usize> = serde_json::from_str(&export).unwrap();

        assert_eq!(&queue1, &queue2);
        queue1.clear();
        assert_eq!(0, queue1.len());
        assert_eq!(2, queue2.len());
    }
}