#queue #bounded #numbers #maximum #elements #optional #constraint

limq

Queue with optional maximum number of elements constraint

1 unstable release

0.1.0 Apr 9, 2024

#1562 in Data structures

Download history 160/week @ 2024-04-09

160 downloads per month
Used in bndpresbufq

0BSD license

9KB
96 lines

Limited Queue

LimQ is a queue that can be configured to hold a maximum number of elements.


lib.rs:

LimQ is a queue (implemented as a wrapper around VecDeque) that supports an optional maximum number of elements constraint.

Rather than supplying the traditional push() method to add elements to the queue, LimQ implements [LimQ::try_push()] and [LimQ::force_push()]. If no queue limit has been enabled, both of these act exactly like a traditional push() would. When a limit has been set, and reached, try_push() will fail, returning the input element. force_push() will forcibly add the new element while dropping the next element in line to be pulled off the queue.

use limq::LimQ;

// Construct a queue with a maximum 2 element length limit
let mut q: LimQ<u32> = LimQ::new(Some(2));

// Add elements to fill up to queue
q.try_push(1).unwrap();
q.force_push(2);

// Fail to add a new node
assert_eq!(q.try_push(3), Err(3));

// Forcibly add node; expelling the oldest node
q.force_push(4);

// Remaining nodes should be 2 and 4
assert_eq!(q.pop(), Some(2));
assert_eq!(q.pop(), Some(4));
assert_eq!(q.pop(), None);

No runtime deps