queue/lib.rs
1//! A simple and easy wrapper around `Vec` to implement a FIFO queue. This is
2//! no fancy, advanced data type but something simple you can use easily until
3//! or unless you need something different.
4//!
5//! # Example
6//!
7//! ```
8//! use queue::Queue;
9//!
10//! let mut q = Queue::new();
11//!
12//! q.queue("hello").unwrap();
13//! q.queue("out").unwrap();
14//! q.queue("there!").unwrap();
15//!
16//! while let Some(item) = q.dequeue() {
17//! println!("{}", item);
18//! }
19//! ```
20//!
21//! Outputs:
22//!
23//! ```text
24//! hello
25//! out
26//! there!
27//! ```
28
29#[cfg(test)]
30mod tests;
31
32/// A first in, first out queue built around `Vec`.
33///
34/// An optional capacity can be set (or changed) to ensure the `Queue` never
35/// grows past a certain size. If the capacity is not specified (ie set to
36/// `None`) then the `Queue` will grow as needed. If you're worried about
37/// memory allocation, set a capacity and the necessary memory will be
38/// allocated at that time. Otherwise memory could be allocated, deallocated
39/// and reallocated as the `Queue` changes size.
40///
41/// The only requirement of the type used is that it implements the `Clone`
42/// trait.
43///
44/// # Example
45///
46/// ```
47/// use queue::Queue;
48///
49/// let mut q = Queue::with_capacity(5);
50///
51/// for i in 0..5 {
52/// q.queue(i).unwrap();
53/// }
54///
55/// for i in 0..5 {
56/// assert_eq!(q.dequeue(), Some(i));
57/// }
58/// ```
59#[derive(Clone, Debug, Default)]
60pub struct Queue<T> {
61 vec: Vec<T>,
62 cap: Option<usize>,
63}
64
65impl<T: Clone> From<Vec<T>> for Queue<T> {
66 /// Constructs a new `Queue<T>` from a `Vec<T>`.
67 ///
68 /// # Example
69 ///
70 /// ```
71 /// # use queue::Queue;
72 /// let q = Queue::from(vec![1, 2, 3]);
73 /// ```
74 fn from(v: Vec<T>) -> Queue<T> {
75 Queue {
76 vec: v,
77 cap: None
78 }
79 }
80}
81
82impl<T: Clone> Queue<T> {
83 /// Constructs a new `Queue<T>`.
84 ///
85 /// # Example
86 ///
87 /// ```
88 /// # use queue::Queue;
89 /// let mut q: Queue<String> = Queue::new();
90 /// ```
91 pub fn new() -> Queue<T> {
92 Queue {
93 vec: Vec::new(),
94 cap: None,
95 }
96 }
97
98 /// Constructs a new `Queue<T>` with a specified capacity.
99 ///
100 /// # Example
101 ///
102 /// ```
103 /// # use queue::Queue;
104 /// let mut q: Queue<String> = Queue::with_capacity(20);
105 /// ```
106 pub fn with_capacity(cap: usize) -> Queue<T> {
107 Queue {
108 vec: Vec::with_capacity(cap),
109 cap: Some(cap),
110 }
111 }
112
113 /// Add an item to the end of the `Queue`. Returns `Ok(usize)` with the new
114 /// length of the `Queue`, or `Err(())` if there is no more room.
115 ///
116 /// # Example
117 ///
118 /// ```
119 /// # use queue::Queue;
120 /// let mut q = Queue::new();
121 /// q.queue("hello").unwrap();
122 /// assert_eq!(q.peek(), Some("hello"));
123 /// ```
124 pub fn queue(&mut self, item: T) -> Result<usize, ()> {
125 if let Some(cap) = self.cap {
126 if self.vec.len() >= cap {
127 Err(())
128 } else {
129 self.vec.push(item);
130 Ok(self.vec.len())
131 }
132 } else {
133 self.vec.push(item);
134 Ok(self.vec.len())
135 }
136 }
137
138 /// Forcefully add an item to the end of the `Queue`. If the `Queue` is at
139 /// capacity, the first item will be removed to make room. Returns `usize`
140 /// with the new length of the `Queue`.
141 ///
142 /// # Example
143 ///
144 /// ```
145 /// # use queue::Queue;
146 /// let mut q = Queue::with_capacity(1);
147 /// q.queue("hello").unwrap();
148 /// let _ = q.force_queue("world");
149 /// assert_eq!(q.peek(), Some("world"));
150 /// ```
151 pub fn force_queue(&mut self, item: T) -> usize {
152 if let Ok(len) = self.queue(item.clone()) {
153 return len;
154 } else {
155 let _ = self.dequeue();
156 return self.queue(item.clone()).unwrap();
157 }
158 }
159
160 /// Remove the next item from the `Queue`. Returns `Option<T>` so it will
161 /// return either `Some(T)` or `None` depending on if there's anything in
162 /// the `Queue` to get.
163 ///
164 /// # Example
165 ///
166 /// ```
167 /// # use queue::Queue;
168 /// let mut q = Queue::new();
169 /// q.queue("hello").unwrap();
170 /// q.queue("world").unwrap();
171 /// assert_eq!(q.dequeue(), Some("hello"));
172 /// ```
173 pub fn dequeue(&mut self) -> Option<T> {
174 if !self.vec.is_empty() {
175 Some(self.vec.remove(0))
176 } else {
177 None
178 }
179 }
180
181 /// Return a `&Vec<T>` for the `Queue<T>`.
182 ///
183 /// # Example
184 ///
185 /// ```
186 /// # use queue::Queue;
187 /// let mut q = Queue::new();
188 /// q.queue(1).unwrap();
189 /// q.queue(2).unwrap();
190 /// q.queue(3).unwrap();
191 /// assert_eq!(&vec![1, 2, 3], q.vec());
192 /// ```
193 pub fn vec(&self) -> &Vec<T> {
194 &self.vec
195 }
196
197 /// Peek at the next item in the `Queue`, if there's something there.
198 ///
199 /// # Example
200 ///
201 /// ```
202 /// # use queue::Queue;
203 /// let mut q = Queue::new();
204 /// q.queue(12).unwrap();
205 /// assert_eq!(q.peek(), Some(12));
206 /// ```
207 pub fn peek(&self) -> Option<T> {
208 if !self.vec.is_empty() {
209 Some(self.vec[0].clone())
210 } else {
211 None
212 }
213 }
214
215 /// The number of items currently in the `Queue`.
216 ///
217 /// # Example
218 ///
219 /// ```
220 /// # use queue::Queue;
221 /// let mut q = Queue::with_capacity(8);
222 /// q.queue(1).unwrap();
223 /// q.queue(2).unwrap();
224 /// assert_eq!(q.len(), 2);
225 /// ```
226 pub fn len(&self) -> usize {
227 self.vec.len()
228 }
229
230 /// Check if the `Queue` is empty.
231 ///
232 /// # Example
233 ///
234 /// ```
235 /// # use queue::Queue;
236 /// let mut q = Queue::new();
237 /// assert_eq!(q.is_empty(), true);
238 /// q.queue(1).unwrap();
239 /// assert_eq!(q.is_empty(), false);
240 /// ```
241 pub fn is_empty(&self) -> bool {
242 self.vec.is_empty()
243 }
244
245 /// Query the capacity for a `Queue`. If there is no capacity set (the
246 /// `Queue` can grow as needed) then `None` will be returned, otherwise
247 /// it will be `Some(usize)`.
248 ///
249 /// # Example
250 ///
251 /// ```
252 /// # use queue::Queue;
253 /// let q: Queue<u8> = Queue::with_capacity(12);
254 /// assert_eq!(q.capacity(), Some(12));
255 /// ```
256 pub fn capacity(&self) -> Option<usize> {
257 self.cap
258 }
259
260 /// Modify the capacity of a `Queue`. If set to `None`, the `Queue` will
261 /// grow automatically, as needed. Otherwise, it will be limited to the
262 /// specified number of items. If there are more items in the `Queue` than
263 /// the requested capacity, `Err(())` will be returned, otherwise the
264 /// operation will succeed and `Ok(())` will be returned. If the capacity
265 /// is shrunk, the underlying `Vec` will be shrunk also, which would free
266 /// up whatever extra memory was allocated for the `Queue`.
267 ///
268 /// # Example
269 ///
270 /// ```
271 /// # use queue::Queue;
272 /// let mut q: Queue<u8> = Queue::new();
273 /// q.set_capacity(12).unwrap();
274 /// q.set_capacity(None).unwrap();
275 /// ```
276 pub fn set_capacity<C: Into<Option<usize>>>(&mut self, cap: C) -> Result<(), ()> {
277 let cap = cap.into();
278
279 if cap == None {
280 self.cap = None;
281 return Ok(());
282 }
283
284 if cap == self.cap {
285 return Ok(());
286 }
287
288 let cap = cap.unwrap();
289
290 if cap < self.vec.len() {
291 return Err(());
292 }
293
294 if let Some(scap) = self.cap {
295 if cap < scap {
296 self.vec.shrink_to_fit();
297 }
298 }
299
300 let r = cap - self.vec.len();
301 self.vec.reserve_exact(r);
302 self.cap = Some(cap);
303
304 Ok(())
305 }
306}