Skip to content

Commit f6f09b2

Browse files
committed
ringbuffer_trait: add extend_from_slice
This adds an extend_from_slice function to the RingBuffer trait. The default implementation calls push() for each element. However, by creating specialized implementations for the various buffers, one can do various performance optimizations in a follow-up.
1 parent 0b7f2c1 commit f6f09b2

File tree

4 files changed

+38
-0
lines changed

4 files changed

+38
-0
lines changed

src/ringbuffer_trait.rs

+9
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,15 @@ pub unsafe trait RingBuffer<T>:
230230
RingBufferIterator::new(self)
231231
}
232232

233+
/// Extends the ringbuffer with elements from a slice.
234+
fn extend_from_slice(&mut self, elements: &[T]) where T: Clone {
235+
// Default implementation.
236+
// For performance reasons, specific RingBuffers should use an optimized implementation.
237+
for element in elements {
238+
self.push(element.clone())
239+
}
240+
}
241+
233242
/// Converts the buffer to a vector. This Copies all elements in the ringbuffer.
234243
#[cfg(feature = "alloc")]
235244
fn to_vec(&self) -> Vec<T>

src/with_alloc/alloc_ringbuffer.rs

+8
Original file line numberDiff line numberDiff line change
@@ -469,4 +469,12 @@ mod tests {
469469
assert_eq!(buf.capacity, 4);
470470
assert_eq!(buf.to_vec(), alloc::vec![1, 2, 3, 4]);
471471
}
472+
473+
#[test]
474+
fn test_extend_from_slice() {
475+
let mut buf = AllocRingBuffer::new(3);
476+
let elems = [1, 2, 3];
477+
buf.extend_from_slice(&elems);
478+
assert_eq!(buf.to_vec().as_slice(), elems)
479+
}
472480
}

src/with_alloc/vecdeque.rs

+13
Original file line numberDiff line numberDiff line change
@@ -280,3 +280,16 @@ impl<T> FromIterator<T> for GrowableAllocRingBuffer<T> {
280280
Self(VecDeque::from_iter(iter))
281281
}
282282
}
283+
284+
#[cfg(test)]
285+
mod tests {
286+
use super::*;
287+
288+
#[test]
289+
fn test_extend_from_slice() {
290+
let mut buf = GrowableAllocRingBuffer::new();
291+
let elems = [1, 2, 3];
292+
buf.extend_from_slice(&elems);
293+
assert_eq!(buf.to_vec().as_slice(), elems)
294+
}
295+
}

src/with_const_generics.rs

+8
Original file line numberDiff line numberDiff line change
@@ -492,5 +492,13 @@ mod tests {
492492
vec![1, 2, 3]
493493
);
494494
}
495+
496+
#[test]
497+
fn test_extend_from_slice() {
498+
let mut buf = ConstGenericRingBuffer::<i32, 3>::new();
499+
let elems = [1, 2, 3];
500+
buf.extend_from_slice(&elems);
501+
assert_eq!(buf.to_vec().as_slice(), elems)
502+
}
495503
}
496504
}

0 commit comments

Comments
 (0)