sample/ring_buffer.rs
1//! Items related to the implementation of ring buffers.
2//!
3//! The primary items of interest in this module include:
4//!
5//! - The [Slice](./trait.Slice.html) and [SliceMut](./trait.SliceMut.html) traits - implemented
6//! for types that may be used as the underlying buffer in `Fixed` and `Bounded` ring buffers.
7//! - The [Fixed](./struct.Fixed.html) ring buffer type.
8//! - The [Bounded](./struct.Bounded.html) ring buffer type.
9
10use Box;
11use core::mem;
12use core::iter::{Chain, Cycle, FromIterator, Skip, Take};
13use core::ptr;
14use core::ops::{Index, IndexMut};
15use core::slice;
16use Vec;
17
18////////////////////////
19///// SLICE TRAITS /////
20////////////////////////
21
22/// Types that may be used as a data slice for `Fixed` and `Bounded` ring buffers.
23pub trait Slice {
24 /// The type contained within the slice.
25 type Element;
26 /// Borrow the data slice.
27 fn slice(&self) -> &[Self::Element];
28}
29
30/// Types that may be used as a data slice for mutable `Fixed` and `Bounded` ring buffers.
31pub trait SliceMut: Slice {
32 /// Mutably borrow the data slice.
33 fn slice_mut(&mut self) -> &mut [Self::Element];
34}
35
36/// Types that may be used as a constant-length buffer underlying a `Bounded` ring buffer.
37pub trait FixedSizeArray {
38 /// The constant length.
39 const LEN: usize;
40}
41
42impl<'a, T> Slice for &'a [T] {
43 type Element = T;
44 #[inline]
45 fn slice(&self) -> &[Self::Element] {
46 self
47 }
48}
49
50impl<'a, T> Slice for &'a mut [T] {
51 type Element = T;
52 #[inline]
53 fn slice(&self) -> &[Self::Element] {
54 self
55 }
56}
57
58impl<'a, T> SliceMut for &'a mut [T] {
59 #[inline]
60 fn slice_mut(&mut self) -> &mut [Self::Element] {
61 self
62 }
63}
64
65impl<T> Slice for Box<[T]> {
66 type Element = T;
67 #[inline]
68 fn slice(&self) -> &[Self::Element] {
69 &self[..]
70 }
71}
72
73impl<T> SliceMut for Box<[T]> {
74 #[inline]
75 fn slice_mut(&mut self) -> &mut [Self::Element] {
76 &mut self[..]
77 }
78}
79
80impl<T> Slice for Vec<T> {
81 type Element = T;
82 #[inline]
83 fn slice(&self) -> &[Self::Element] {
84 &self[..]
85 }
86}
87
88impl<T> SliceMut for Vec<T> {
89 #[inline]
90 fn slice_mut(&mut self) -> &mut [Self::Element] {
91 &mut self[..]
92 }
93}
94
95macro_rules! impl_slice_for_arrays {
96 ($($N:expr)*) => {
97 $(
98 impl<T> Slice for [T; $N] {
99 type Element = T;
100 #[inline]
101 fn slice(&self) -> &[Self::Element] {
102 &self[..]
103 }
104 }
105 impl<T> SliceMut for [T; $N] {
106 #[inline]
107 fn slice_mut(&mut self) -> &mut [Self::Element] {
108 &mut self[..]
109 }
110 }
111 impl<T> FixedSizeArray for [T; $N] {
112 const LEN: usize = $N;
113 }
114 )*
115 };
116}
117
118impl_slice_for_arrays! {
119 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
120 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
121 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
122 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
123 121 122 123 124 125 126 127 128 256 512 1024 2048 4096 8192
124}
125
126/////////////////////////////
127///// FIXED RING BUFFER /////
128/////////////////////////////
129
130/// A ring buffer with a fixed length.
131///
132/// *AKA Circular buffer, cyclic buffer, FIFO queue.*
133///
134/// Elements are pushed and popped from the buffer simultaneously in order to retain a consistent
135/// length.
136///
137/// A `Fixed` ring buffer can be created around any type with a slice to write to.
138///
139/// ```
140/// extern crate sample;
141///
142/// fn main() {
143/// // From a fixed size array.
144/// sample::ring_buffer::Fixed::from([1, 2, 3, 4]);
145///
146/// // From a Vec.
147/// sample::ring_buffer::Fixed::from(vec![1, 2, 3, 4]);
148///
149/// // From a Boxed slice.
150/// sample::ring_buffer::Fixed::from(vec![1, 2, 3].into_boxed_slice());
151///
152/// // From a mutably borrowed slice.
153/// let mut slice = [1, 2, 3, 4];
154/// sample::ring_buffer::Fixed::from(&mut slice[..]);
155///
156/// // An immutable ring buffer from an immutable slice.
157/// let slice = [1, 2, 3, 4];
158/// sample::ring_buffer::Fixed::from(&slice[..]);
159/// }
160/// ```
161#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
162pub struct Fixed<S> {
163 first: usize,
164 data: S,
165}
166
167impl<S> Fixed<S>
168where
169 S: Slice,
170{
171 /// The fixed length of the buffer.
172 ///
173 /// ```
174 /// extern crate sample;
175 ///
176 /// use sample::ring_buffer;
177 ///
178 /// fn main() {
179 /// let rb = ring_buffer::Fixed::from([0; 4]);
180 /// assert_eq!(rb.len(), 4);
181 /// }
182 /// ```
183 #[inline]
184 pub fn len(&self) -> usize {
185 self.data.slice().len()
186 }
187
188 /// Push the given item onto the back of the queue and return the item at the front of the
189 /// queue, ensuring that the length is retained.
190 ///
191 /// ```
192 /// extern crate sample;
193 ///
194 /// use sample::ring_buffer;
195 ///
196 /// fn main() {
197 /// let mut rb = ring_buffer::Fixed::from([0, 1, 2, 3]);
198 /// assert_eq!(rb.push(4), 0);
199 /// assert_eq!(rb.push(5), 1);
200 /// assert_eq!(rb.push(6), 2);
201 /// assert_eq!(rb.push(7), 3);
202 /// assert_eq!(rb.push(8), 4);
203 /// assert_eq!([rb[0], rb[1], rb[2], rb[3]], [5, 6, 7, 8]);
204 /// }
205 /// ```
206 pub fn push(&mut self, item: S::Element) -> S::Element
207 where
208 S: SliceMut,
209 {
210 let mut next_index = self.first + 1;
211 if next_index == self.len() {
212 next_index = 0;
213 }
214 // We know there is a fixed length so we can safely avoid bounds checking.
215 let old_item =
216 unsafe { mem::replace(self.data.slice_mut().get_unchecked_mut(self.first), item) };
217 self.first = next_index;
218 old_item
219 }
220
221 /// Borrows the item at the given index.
222 ///
223 /// If `index` is out of range it will be looped around the length of the data slice.
224 ///
225 /// ```
226 /// extern crate sample;
227 ///
228 /// use sample::ring_buffer;
229 ///
230 /// fn main() {
231 /// let mut rb = ring_buffer::Fixed::from([0, 1, 2]);
232 /// assert_eq!(*rb.get(0), 0);
233 /// assert_eq!(*rb.get(1), 1);
234 /// assert_eq!(*rb.get(2), 2);
235 /// assert_eq!(*rb.get(3), 0);
236 /// assert_eq!(*rb.get(4), 1);
237 /// assert_eq!(*rb.get(5), 2);
238 /// }
239 /// ```
240 #[inline]
241 pub fn get(&self, index: usize) -> &S::Element {
242 let wrapped_index = (self.first + index) % self.len();
243 &self.data.slice()[wrapped_index]
244 }
245
246 /// Mutably borrows the item at the given index.
247 ///
248 /// If `index` is out of range it will be looped around the length of the data slice.
249 #[inline]
250 pub fn get_mut(&mut self, index: usize) -> &mut S::Element
251 where
252 S: SliceMut,
253 {
254 let wrapped_index = (self.first + index) % self.len();
255 &mut self.data.slice_mut()[wrapped_index]
256 }
257
258 /// Sets the index of the first element within the data slice.
259 ///
260 /// If `index` is out of range it will be looped around the length of the data slice.
261 ///
262 /// ```
263 /// extern crate sample;
264 ///
265 /// use sample::ring_buffer;
266 ///
267 /// fn main() {
268 /// let mut rb = ring_buffer::Fixed::from([0, 1, 2, 3]);
269 /// assert_eq!(rb[0], 0);
270 /// rb.set_first(2);
271 /// assert_eq!(rb[0], 2);
272 /// rb.set_first(5);
273 /// assert_eq!(rb[0], 1);
274 /// }
275 /// ```
276 #[inline]
277 pub fn set_first(&mut self, index: usize) {
278 self.first = index % self.len();
279 }
280
281 /// The start and end slices that make up the ring buffer.
282 ///
283 /// These two slices chained together represent all elements within the buffer in order.
284 ///
285 /// The first slice is always aligned contiguously behind the second slice.
286 ///
287 /// ```
288 /// extern crate sample;
289 ///
290 /// fn main() {
291 /// let mut ring_buffer = sample::ring_buffer::Fixed::from([0; 4]);
292 /// assert_eq!(ring_buffer.slices(), (&[0, 0, 0, 0][..], &[][..]));
293 /// ring_buffer.push(1);
294 /// ring_buffer.push(2);
295 /// assert_eq!(ring_buffer.slices(), (&[0, 0][..], &[1, 2][..]));
296 /// ring_buffer.push(3);
297 /// ring_buffer.push(4);
298 /// assert_eq!(ring_buffer.slices(), (&[1, 2, 3, 4][..], &[][..]));
299 /// }
300 /// ```
301 #[inline]
302 pub fn slices(&self) -> (&[S::Element], &[S::Element]) {
303 let (end, start) = self.data.slice().split_at(self.first);
304 (start, end)
305 }
306
307 /// The same as the `slices` method, but returns mutable slices instead.
308 #[inline]
309 pub fn slices_mut(&mut self) -> (&mut [S::Element], &mut [S::Element])
310 where
311 S: SliceMut,
312 {
313 let (end, start) = self.data.slice_mut().split_at_mut(self.first);
314 (start, end)
315 }
316
317 /// Produce an iterator that repeatedly yields a reference to each element in the buffer.
318 #[inline]
319 pub fn iter_loop(&self) -> Skip<Cycle<slice::Iter<S::Element>>> {
320 self.data.slice().iter().cycle().skip(self.first)
321 }
322
323 /// Produce an iterator that yields a reference to each element in the buffer.
324 #[inline]
325 pub fn iter(&self) -> Take<Skip<Cycle<slice::Iter<S::Element>>>> {
326 self.iter_loop().take(self.data.slice().len())
327 }
328
329 /// Produce an iterator that yields a mutable reference to each element in the buffer.
330 #[inline]
331 pub fn iter_mut(&mut self) -> Chain<slice::IterMut<S::Element>, slice::IterMut<S::Element>>
332 where
333 S: SliceMut,
334 {
335 let (start, end) = self.slices_mut();
336 start.iter_mut().chain(end.iter_mut())
337 }
338
339 /// Creates a `Fixed` ring buffer from its starting index and data buffer type.
340 ///
341 /// **Panic!**s if the given index is out of range of the given data slice.
342 ///
343 /// **Note:** This method should only be necessary if you require specifying a first index.
344 /// Please see the `ring_buffer::Fixed::from` function for a simpler constructor that does not
345 /// require a `first` index.
346 #[inline]
347 pub fn from_raw_parts(first: usize, data: S) -> Self {
348 assert!(first < data.slice().len());
349 Fixed { first, data }
350 }
351
352 /// Creates a `Fixed` ring buffer from its starting index and data buffer type.
353 ///
354 /// This method is unsafe as there is no guarantee that `first` < `data.slice().len()`.
355 #[inline]
356 pub unsafe fn from_raw_parts_unchecked(first: usize, data: S) -> Self {
357 Fixed { first, data }
358 }
359
360 /// Consumes the `Fixed` ring buffer and returns its parts:
361 ///
362 /// - `usize` is an index into the first element of the buffer.
363 /// - `S` is the buffer data.
364 #[inline]
365 pub fn into_raw_parts(self) -> (usize, S) {
366 let Fixed { first, data } = self;
367 (first, data)
368 }
369}
370
371impl<S> From<S> for Fixed<S>
372where
373 S: Slice,
374{
375 /// Construct a `Fixed` ring buffer from the given data slice.
376 ///
377 /// **Panic!**s if the given `data` buffer is empty.
378 #[inline]
379 fn from(data: S) -> Self {
380 Self::from_raw_parts(0, data)
381 }
382}
383
384impl<S, T> FromIterator<T> for Fixed<S>
385where
386 S: Slice<Element = T> + FromIterator<T>,
387{
388 #[inline]
389 fn from_iter<I>(iter: I) -> Self
390 where
391 I: IntoIterator<Item = T>,
392 {
393 let data = S::from_iter(iter);
394 Self::from(data)
395 }
396}
397
398impl<S> Index<usize> for Fixed<S>
399where
400 S: Slice,
401{
402 type Output = S::Element;
403 #[inline]
404 fn index(&self, index: usize) -> &Self::Output {
405 self.get(index)
406 }
407}
408
409impl<S> IndexMut<usize> for Fixed<S>
410where
411 S: SliceMut,
412{
413 #[inline]
414 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
415 self.get_mut(index)
416 }
417}
418
419///////////////////////////////
420///// BOUNDED RING BUFFER /////
421///////////////////////////////
422
423/// A ring buffer with an upper bound on its length.
424///
425/// *AKA Circular buffer, cyclic buffer, FIFO queue.*
426///
427/// Elements can be pushed to the back of the buffer and popped from the front.
428///
429/// Elements must be `Copy` due to the behaviour of the `push` and `pop` methods. If you require
430/// working with non-`Copy` elements, the `std` `VecDeque` type may be better suited.
431///
432/// A `Bounded` ring buffer can be created from any type providing a slice to use for pushing and
433/// popping elements.
434///
435/// ```
436/// extern crate sample;
437///
438/// use sample::ring_buffer;
439///
440/// fn main() {
441/// // From a fixed size array.
442/// ring_buffer::Bounded::from([0; 4]);
443///
444/// // From a Vec.
445/// ring_buffer::Bounded::from(vec![0; 4]);
446///
447/// // From a Boxed slice.
448/// ring_buffer::Bounded::from(vec![0; 3].into_boxed_slice());
449///
450/// // From a mutably borrowed slice.
451/// let mut slice = [0; 4];
452/// ring_buffer::Bounded::from(&mut slice[..]);
453///
454/// // An immutable ring buffer from an immutable slice.
455/// let slice = [0; 4];
456/// ring_buffer::Bounded::from(&slice[..]);
457/// }
458/// ```
459///
460/// Two slightly more efficient constructors are provided for fixed-size arrays and boxed slices.
461/// These are generally more efficient as they do not require initialising elements.
462///
463/// ```
464/// extern crate sample;
465///
466/// use sample::ring_buffer;
467///
468/// fn main() {
469/// // Fixed-size array.
470/// ring_buffer::Bounded::<[i32; 4]>::array();
471///
472/// // Boxed slice.
473/// let mut rb = ring_buffer::Bounded::boxed_slice(4);
474/// rb.push(1);
475/// }
476/// ```
477#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
478pub struct Bounded<S> {
479 start: usize,
480 len: usize,
481 data: S,
482}
483
484/// An iterator that drains the ring buffer by `pop`ping each element one at a time.
485///
486/// Note that only elements yielded by `DrainBounded::next` will be popped from the ring buffer.
487/// That is, all non-yielded elements will remain in the ring buffer.
488pub struct DrainBounded<'a, S: 'a> {
489 bounded: &'a mut Bounded<S>,
490}
491
492impl<T> Bounded<Box<[T]>>
493where
494 T: Copy,
495{
496 /// A `Bounded` ring buffer that uses a `Box`ed slice with the given maximum length to
497 /// represent the data.
498 ///
499 /// Slightly more efficient than using the similar `From` constructor as this creates the
500 /// underlying slice with uninitialised memory.
501 ///
502 /// ```
503 /// extern crate sample;
504 ///
505 /// use sample::ring_buffer;
506 ///
507 /// fn main() {
508 /// let mut rb = ring_buffer::Bounded::boxed_slice(4);
509 /// assert_eq!(rb.max_len(), 4);
510 /// assert_eq!(rb.len(), 0);
511 /// rb.push(1);
512 /// rb.push(2);
513 /// }
514 /// ```
515 pub fn boxed_slice(max_len: usize) -> Self {
516 let mut vec = Vec::new();
517 vec.reserve_exact(max_len);
518 unsafe {
519 vec.set_len(max_len);
520 let data = vec.into_boxed_slice();
521 Self::from_raw_parts(0, 0, data)
522 }
523 }
524}
525
526impl<S> Bounded<S>
527where
528 S: Slice,
529 S::Element: Copy,
530{
531 /// A `Bounded` buffer that uses a fixed-size array to represent data.
532 ///
533 /// Slightly more efficient than using the similar `From` constructor as this creates the
534 /// underlying array with uninitialised memory.
535 ///
536 /// ```
537 /// extern crate sample;
538 ///
539 /// use sample::ring_buffer;
540 ///
541 /// fn main() {
542 /// let mut rb = ring_buffer::Bounded::<[f32; 3]>::array();
543 /// assert_eq!(rb.len(), 0);
544 /// assert_eq!(rb.max_len(), 3);
545 /// }
546 /// ```
547 pub fn array() -> Self
548 where
549 S: FixedSizeArray,
550 {
551 unsafe {
552 let data = mem::uninitialized();
553 Self::from_raw_parts(0, 0, data)
554 }
555 }
556
557 /// The same as the `From` implementation, but assumes that the given `data` is full of valid
558 /// elements and initialises the ring buffer with a length equal to `max_len`.
559 ///
560 /// ```
561 /// extern crate sample;
562 ///
563 /// use sample::ring_buffer;
564 ///
565 /// fn main() {
566 /// let mut rb = ring_buffer::Bounded::from_full([0, 1, 2, 3]);
567 /// assert_eq!(rb.len(), rb.max_len());
568 /// assert_eq!(rb.pop(), Some(0));
569 /// assert_eq!(rb.pop(), Some(1));
570 /// assert_eq!(rb.pop(), Some(2));
571 /// assert_eq!(rb.pop(), Some(3));
572 /// assert_eq!(rb.pop(), None);
573 /// }
574 /// ```
575 pub fn from_full(data: S) -> Self {
576 Self::from_raw_parts(0, data.slice().len(), data)
577 }
578
579 /// The maximum length that the `Bounded` buffer can be before pushing would overwrite the
580 /// front of the buffer.
581 ///
582 /// ```
583 /// extern crate sample;
584 ///
585 /// fn main() {
586 /// let mut ring_buffer = sample::ring_buffer::Bounded::<[i32; 3]>::array();
587 /// assert_eq!(ring_buffer.max_len(), 3);
588 /// }
589 /// ```
590 #[inline]
591 pub fn max_len(&self) -> usize {
592 self.data.slice().len()
593 }
594
595 /// The current length of the ring buffer.
596 ///
597 /// ```
598 /// extern crate sample;
599 ///
600 /// fn main() {
601 /// let mut ring_buffer = sample::ring_buffer::Bounded::<[i32; 3]>::array();
602 /// assert_eq!(ring_buffer.len(), 0);
603 /// }
604 /// ```
605 #[inline]
606 pub fn len(&self) -> usize {
607 self.len
608 }
609
610 /// Whether or not the ring buffer's length is equal to `0`.
611 ///
612 /// Equivalent to `self.len() == 0`.
613 ///
614 /// ```
615 /// extern crate sample;
616 ///
617 /// use sample::ring_buffer;
618 ///
619 /// fn main() {
620 /// let mut rb = ring_buffer::Bounded::<[i32; 2]>::array();
621 /// assert!(rb.is_empty());
622 /// rb.push(0);
623 /// assert!(!rb.is_empty());
624 /// }
625 /// ```
626 pub fn is_empty(&self) -> bool {
627 self.len == 0
628 }
629
630 /// Whether or not the ring buffer's length is equal to the maximum length.
631 ///
632 /// Equivalent to `self.len() == self.max_len()`.
633 ///
634 /// ```
635 /// extern crate sample;
636 ///
637 /// use sample::ring_buffer;
638 ///
639 /// fn main() {
640 /// let mut rb = ring_buffer::Bounded::<[i32; 2]>::array();
641 /// assert!(!rb.is_full());
642 /// rb.push(0);
643 /// rb.push(1);
644 /// assert!(rb.is_full());
645 /// }
646 /// ```
647 #[inline]
648 pub fn is_full(&self) -> bool {
649 self.len == self.max_len()
650 }
651
652 /// The start and end slices that make up the ring buffer.
653 ///
654 /// These two slices chained together represent all elements within the buffer in order.
655 ///
656 /// The first slice is always aligned contiguously behind the second slice.
657 ///
658 /// ```
659 /// extern crate sample;
660 ///
661 /// fn main() {
662 /// let mut ring_buffer = sample::ring_buffer::Bounded::<[i32; 4]>::array();
663 /// assert_eq!(ring_buffer.slices(), (&[][..], &[][..]));
664 /// ring_buffer.push(1);
665 /// ring_buffer.push(2);
666 /// assert_eq!(ring_buffer.slices(), (&[1, 2][..], &[][..]));
667 /// ring_buffer.push(3);
668 /// ring_buffer.push(4);
669 /// assert_eq!(ring_buffer.slices(), (&[1, 2, 3, 4][..], &[][..]));
670 /// ring_buffer.push(5);
671 /// ring_buffer.push(6);
672 /// assert_eq!(ring_buffer.slices(), (&[3, 4][..], &[5, 6][..]));
673 /// }
674 /// ```
675 #[inline]
676 pub fn slices(&self) -> (&[S::Element], &[S::Element]) {
677 let (end, start) = self.data.slice().split_at(self.start);
678 if start.len() <= self.len {
679 let end_len = self.len - start.len();
680 (start, &end[..end_len])
681 } else {
682 (&start[..self.len], &end[..0])
683 }
684 }
685
686 /// The same as the `slices` method, but returns mutable slices instead.
687 #[inline]
688 pub fn slices_mut(&mut self) -> (&mut [S::Element], &mut [S::Element])
689 where
690 S: SliceMut,
691 {
692 let (end, start) = self.data.slice_mut().split_at_mut(self.start);
693 if start.len() <= self.len {
694 let end_len = self.len - start.len();
695 (start, &mut end[..end_len])
696 } else {
697 (&mut start[..self.len], &mut end[..0])
698 }
699 }
700
701 /// Produce an iterator that yields a reference to each element in the buffer.
702 ///
703 /// This method uses the `slices` method internally.
704 ///
705 /// ```
706 /// extern crate sample;
707 ///
708 /// use sample::ring_buffer;
709 ///
710 /// fn main() {
711 /// let mut rb = ring_buffer::Bounded::<[i32; 3]>::array();
712 /// assert_eq!(rb.iter().count(), 0);
713 /// rb.push(1);
714 /// rb.push(2);
715 /// assert_eq!(rb.iter().cloned().collect::<Vec<_>>(), vec![1, 2]);
716 /// }
717 /// ```
718 #[inline]
719 pub fn iter(&self) -> Chain<slice::Iter<S::Element>, slice::Iter<S::Element>> {
720 let (start, end) = self.slices();
721 start.iter().chain(end.iter())
722 }
723
724 /// Produce an iterator that yields a mutable reference to each element in the buffer.
725 ///
726 /// This method uses the `slices_mut` method internally.
727 #[inline]
728 pub fn iter_mut(&mut self) -> Chain<slice::IterMut<S::Element>, slice::IterMut<S::Element>>
729 where
730 S: SliceMut,
731 {
732 let (start, end) = self.slices_mut();
733 start.iter_mut().chain(end.iter_mut())
734 }
735
736 /// Borrows the item at the given index.
737 ///
738 /// Returns `None` if there is no element at the given index.
739 ///
740 /// ```
741 /// extern crate sample;
742 ///
743 /// use sample::ring_buffer;
744 ///
745 /// fn main() {
746 /// let mut rb = ring_buffer::Bounded::<[i32; 4]>::array();
747 /// assert_eq!(rb.get(1), None);
748 /// rb.push(0);
749 /// rb.push(1);
750 /// assert_eq!(rb.get(1), Some(&1));
751 /// }
752 /// ```
753 #[inline]
754 pub fn get(&self, index: usize) -> Option<&S::Element> {
755 if index >= self.len {
756 return None;
757 }
758 let wrapped_index = index % self.max_len();
759 unsafe { Some(self.data.slice().get_unchecked(wrapped_index) as &_) }
760 }
761
762 /// Mutably borrows the item at the given index.
763 ///
764 /// Returns `None` if there is no element at the given index.
765 #[inline]
766 pub fn get_mut(&mut self, index: usize) -> Option<&mut S::Element>
767 where
768 S: SliceMut,
769 {
770 if index >= self.len {
771 return None;
772 }
773 let wrapped_index = index % self.max_len();
774 unsafe {
775 Some(self.data.slice_mut().get_unchecked_mut(wrapped_index) as
776 &mut _)
777 }
778 }
779
780 /// Pushes the given element to the back of the buffer.
781 ///
782 /// If the buffer length is currently the max length, this replaces the element at the front of
783 /// the buffer and returns it.
784 ///
785 /// If the buffer length is less than the max length, this pushes the element to the back of
786 /// the buffer and increases the length of the buffer by `1`. `None` is returned.
787 ///
788 /// ```
789 /// extern crate sample;
790 ///
791 /// fn main() {
792 /// let mut ring_buffer = sample::ring_buffer::Bounded::<[i32; 3]>::array();
793 /// assert_eq!(ring_buffer.push(1), None);
794 /// assert_eq!(ring_buffer.push(2), None);
795 /// assert_eq!(ring_buffer.len(), 2);
796 /// assert_eq!(ring_buffer.push(3), None);
797 /// assert_eq!(ring_buffer.len(), 3);
798 /// assert_eq!(ring_buffer.push(4), Some(1));
799 /// assert_eq!(ring_buffer.len(), 3);
800 /// }
801 /// ```
802 pub fn push(&mut self, elem: S::Element) -> Option<S::Element>
803 where
804 S: SliceMut,
805 {
806 // If the length is equal to the max, the buffer is full and we overwrite the start.
807 if self.len == self.max_len() {
808 let mut next_start = self.start + 1;
809
810 // Wrap the start around the max length.
811 if next_start >= self.max_len() {
812 next_start = 0;
813 }
814
815 // Replace the element currently at the end.
816 let old_elem =
817 unsafe { mem::replace(self.data.slice_mut().get_unchecked_mut(self.start), elem) };
818
819 self.start = next_start;
820 return Some(old_elem);
821 }
822
823 // Otherwise the buffer is not full and has a free index to write to.
824 let index = (self.start + self.len) % self.max_len();
825 unsafe {
826 ptr::write(self.data.slice_mut().get_unchecked_mut(index), elem);
827 }
828 self.len += 1;
829 None
830 }
831
832 /// Pop an element from the front of the ring buffer.
833 ///
834 /// If the buffer is empty, this returns `None`.
835 ///
836 /// ```
837 /// extern crate sample;
838 ///
839 /// use sample::ring_buffer;
840 ///
841 /// fn main() {
842 /// let mut rb = ring_buffer::Bounded::from_full([0, 1, 2]);
843 /// assert_eq!(rb.len(), rb.max_len());
844 /// assert_eq!(rb.pop(), Some(0));
845 /// assert_eq!(rb.pop(), Some(1));
846 /// assert_eq!(rb.push(3), None);
847 /// assert_eq!(rb.pop(), Some(2));
848 /// assert_eq!(rb.pop(), Some(3));
849 /// assert_eq!(rb.pop(), None);
850 /// }
851 /// ```
852 pub fn pop(&mut self) -> Option<S::Element>
853 where
854 S: SliceMut,
855 {
856 if self.len == 0 {
857 return None;
858 }
859
860 let mut next_start = self.start + 1;
861
862 // Wrap the start around the max length.
863 if next_start >= self.max_len() {
864 next_start = 0;
865 }
866
867 let old_elem = unsafe { ptr::read(self.data.slice_mut().get_unchecked_mut(self.start)) };
868
869 self.start = next_start;
870 self.len -= 1;
871 Some(old_elem)
872 }
873
874 /// Produce an iterator that drains the ring buffer by `pop`ping each element one at a time.
875 ///
876 /// Note that only elements yielded by `DrainBounded::next` will be popped from the ring buffer.
877 /// That is, all non-yielded elements will remain in the ring buffer.
878 ///
879 /// ```
880 /// extern crate sample;
881 ///
882 /// use sample::ring_buffer;
883 ///
884 /// fn main() {
885 /// let mut rb = ring_buffer::Bounded::from_full([0, 1, 2, 3]);
886 /// assert_eq!(rb.drain().take(2).collect::<Vec<_>>(), vec![0, 1]);
887 /// assert_eq!(rb.pop(), Some(2));
888 /// assert_eq!(rb.pop(), Some(3));
889 /// assert_eq!(rb.pop(), None);
890 /// }
891 /// ```
892 pub fn drain(&mut self) -> DrainBounded<S> {
893 DrainBounded {
894 bounded: self,
895 }
896 }
897
898 /// Creates a `Bounded` ring buffer from its start index, length and data slice.
899 ///
900 /// The maximum length of the `Bounded` ring buffer is assumed to the length of the given slice.
901 ///
902 /// **Note:** Existing elements within the given `data`'s `slice` will not be dropped when
903 /// overwritten by calls to push. Thus, it is safe for the slice to contain uninitialized
904 /// elements when using this method.
905 ///
906 /// **Note:** This method should only be necessary if you require specifying the `start` and
907 /// initial `len`. Please see the `Bounded::array` and `Bounded::boxed_slice` functions for
908 /// simpler constructor options that do not require manually passing indices.
909 ///
910 /// **Panic!**s if the following conditions are not met:
911 ///
912 /// - `start` < `data.slice().len()`
913 /// - `len` <= `data.slice().len()`
914 #[inline]
915 pub fn from_raw_parts(start: usize, len: usize, data: S) -> Self {
916 assert!(start < data.slice().len());
917 assert!(len <= data.slice().len());
918 Bounded { start, len, data }
919 }
920
921 /// Creates a `Bounded` ring buffer from its `start` index, `len` and data slice.
922 ///
923 /// This method is unsafe as there is no guarantee that either:
924 ///
925 /// - `start` < `data.slice().len()` or
926 /// - `len` <= `data.slice().len()`.
927 #[inline]
928 pub unsafe fn from_raw_parts_unchecked(start: usize, len: usize, data: S) -> Self {
929 Bounded { start, len, data }
930 }
931
932 /// Consumes the `Bounded` ring buffer and returns its parts:
933 ///
934 /// - The first `usize` is an index into the first element of the buffer.
935 /// - The second `usize` is the length of the ring buffer.
936 /// - `S` is the buffer data.
937 ///
938 /// This method is unsafe as the returned data may contain uninitialised memory in the case
939 /// that the ring buffer is not full.
940 #[inline]
941 pub unsafe fn into_raw_parts(self) -> (usize, usize, S) {
942 let Bounded { start, len, data } = self;
943 (start, len, data)
944 }
945}
946
947impl<S> From<S> for Bounded<S>
948where
949 S: Slice,
950 S::Element: Copy,
951{
952 /// Construct a `Bounded` ring buffer from the given data slice.
953 ///
954 /// **Panic!**s if the given `data` buffer is empty.
955 #[inline]
956 fn from(data: S) -> Self {
957 Self::from_raw_parts(0, 0, data)
958 }
959}
960
961impl<S, T> FromIterator<T> for Bounded<S>
962where
963 S: Slice<Element = T> + FromIterator<T>,
964 T: Copy,
965{
966 #[inline]
967 fn from_iter<I>(iter: I) -> Self
968 where
969 I: IntoIterator<Item = T>,
970 {
971 let data = S::from_iter(iter);
972 Self::from(data)
973 }
974}
975
976impl<S> Index<usize> for Bounded<S>
977where
978 S: Slice,
979 S::Element: Copy,
980{
981 type Output = S::Element;
982 #[inline]
983 fn index(&self, index: usize) -> &Self::Output {
984 self.get(index).expect("index out of range")
985 }
986}
987
988impl<S> IndexMut<usize> for Bounded<S>
989where
990 S: SliceMut,
991 S::Element: Copy,
992{
993 #[inline]
994 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
995 self.get_mut(index).expect("index out of range")
996 }
997}
998
999impl<'a, S> Iterator for DrainBounded<'a, S>
1000where
1001 S: SliceMut,
1002 S::Element: Copy,
1003{
1004 type Item = S::Element;
1005 #[inline]
1006 fn next(&mut self) -> Option<Self::Item> {
1007 self.bounded.pop()
1008 }
1009 #[inline]
1010 fn size_hint(&self) -> (usize, Option<usize>) {
1011 (self.bounded.len(), Some(self.bounded.len()))
1012 }
1013}
1014
1015impl<'a, S> ExactSizeIterator for DrainBounded<'a, S>
1016where
1017 S: SliceMut,
1018 S::Element: Copy,
1019{
1020 fn len(&self) -> usize {
1021 self.bounded.len()
1022 }
1023}