Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimised extend #127

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions benches/bench.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![no_coverage]
use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion};
#![cfg(not(tarpaulin_include))]

use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion, BatchSize};
use ringbuffer::{AllocRingBuffer, ConstGenericRingBuffer, RingBuffer};

fn benchmark_push<T: RingBuffer<i32>, F: Fn() -> T>(b: &mut Bencher, new: F) {
Expand Down Expand Up @@ -180,6 +181,47 @@ fn criterion_benchmark(c: &mut Criterion) {
8192,
8195
];

c.bench_function("extend too many", extend_too_many);
c.bench_function("extend many too many", extend_many_too_many);
c.bench_function("extend exact cap", extend_exact_cap);
c.bench_function("extend too few", extend_too_few);
}

fn extend_many_too_many(b: &mut Bencher) {
let rb = ConstGenericRingBuffer::new::<8192>();
let input = (0..16384).collect::<Vec<_>>();

b.iter_batched(&|| rb.clone(), |mut r| {
black_box(r.extend(black_box(input.as_slice())))
}, BatchSize::SmallInput);
}

fn extend_too_many(b: &mut Bencher) {
let rb = ConstGenericRingBuffer::new::<8192>();
let input = (0..10000).collect::<Vec<_>>();

b.iter_batched(&|| rb.clone(), |mut r| {
black_box(r.extend(black_box(input.as_slice())))
}, BatchSize::SmallInput);
}

fn extend_exact_cap(b: &mut Bencher) {
let rb = ConstGenericRingBuffer::new::<8192>();
let input = (0..8192).collect::<Vec<_>>();

b.iter_batched(&|| rb.clone(), |mut r| {
black_box(r.extend(black_box(input.as_slice())))
}, BatchSize::SmallInput);
}

fn extend_too_few(b: &mut Bencher) {
let rb = ConstGenericRingBuffer::new::<8192>();
let input = (0..4096).collect::<Vec<_>>();

b.iter_batched(&|| rb.clone(), |mut r| {
black_box(r.extend(black_box(input.as_slice())))
}, BatchSize::LargeInput);
}

criterion_group!(benches, criterion_benchmark);
Expand Down
78 changes: 67 additions & 11 deletions src/ringbuffer_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use core::ops::{Index, IndexMut};

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

Expand All @@ -19,8 +20,10 @@ use alloc::vec::Vec;
/// implementation, since these safety guarantees are necessary for
/// [`iter_mut`](RingBuffer::iter_mut) to work
pub unsafe trait RingBuffer<T>:
Sized + IntoIterator<Item = T> + Extend<T> + Index<usize, Output = T> + IndexMut<usize>
{
Sized +
IntoIterator<Item=T> +
Extend<T> +
Index<usize, Output=T> + IndexMut<usize> {
/// Returns the length of the internal buffer.
/// This length grows up to the capacity and then stops growing.
/// This is because when the length is reached, new items are appended at the start.
Expand Down Expand Up @@ -83,6 +86,41 @@ pub unsafe trait RingBuffer<T>:
self.push(value);
}

/// alias for [`extend`](RingBuffer::extend).
#[inline]
fn enqueue_many<I: IntoIterator<Item=T>>(&mut self, items: I) {
self.extend(items);
}

/// Clones and appends all elements in a slice to the `Vec`.
///
/// Iterates over the slice `other`, clones each element, and then appends
/// it to this `RingBuffer`. The `other` slice is traversed in-order.
///
/// Depending on the RingBuffer implementation, may be faster than inserting items in a loop
///
/// Note that this function is same as [`extend`] except that it is
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this actually specialized now or will it be?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in constgeneric yes

/// specialized to work with slices instead. If and when Rust gets
/// specialization this function will likely be deprecated (but still
/// available).
///
/// # Examples
///
/// ```
/// use ringbuffer::{ConstGenericRingBuffer, RingBuffer};
///
/// let mut rb = ConstGenericRingBuffer::<_, 6>::new();
/// rb.push(1);
///
/// rb.extend_from_slice(&[2, 3, 4]);
/// assert_eq!(rb.to_vec(), vec![1, 2, 3, 4]);
/// ```
///
/// [`extend`]: RingBuffer::extend
fn extend_from_slice(&mut self, other: &[T]) where T: Clone {
self.extend(other.into_iter().cloned())
}

/// dequeues the top item off the ringbuffer, and moves this item out.
fn dequeue(&mut self) -> Option<T>;

Expand Down Expand Up @@ -119,21 +157,39 @@ pub unsafe trait RingBuffer<T>:
RingBufferDrainingIterator::new(self)
}

/// Moves all the elements of `other` into `self`, leaving `other` empty.
///
/// # Examples
///
/// ```
/// use ringbuffer::{ConstGenericRingBuffer, RingBuffer};
///
/// let mut vec = ConstGenericRingBuffer::<_, 6>::from(vec![1, 2, 3]);
/// let mut vec2 = ConstGenericRingBuffer::<_, 6>::from(vec![4, 5, 6]);
///
/// vec.append(&mut vec2);
/// assert_eq!(vec.to_vec(), &[1, 2, 3, 4, 5, 6]);
/// assert_eq!(vec2.to_vec(), &[]);
/// ```
fn append(&mut self, other: &mut Self) {
self.extend(other.drain());
}

/// Sets every element in the ringbuffer to the value returned by f.
fn fill_with<F: FnMut() -> T>(&mut self, f: F);

/// Sets every element in the ringbuffer to it's default value
fn fill_default(&mut self)
where
T: Default,
where
T: Default,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rustfmt?

{
self.fill_with(Default::default);
}

/// Sets every element in the ringbuffer to `value`
fn fill(&mut self, value: T)
where
T: Clone,
where
T: Clone,
{
self.fill_with(|| value.clone());
}
Expand Down Expand Up @@ -233,16 +289,16 @@ pub unsafe trait RingBuffer<T>:
/// Converts the buffer to a vector. This Copies all elements in the ringbuffer.
#[cfg(feature = "alloc")]
fn to_vec(&self) -> Vec<T>
where
T: Clone,
where
T: Clone,
{
self.iter().cloned().collect()
}

/// Returns true if elem is in the ringbuffer.
fn contains(&self, elem: &T) -> bool
where
T: PartialEq,
where
T: PartialEq,
{
self.iter().any(|i| i == elem)
}
Expand Down Expand Up @@ -339,7 +395,7 @@ mod iter {
impl<'rb, T: 'rb, RB: RingBuffer<T> + 'rb> ExactSizeIterator for RingBufferMutIterator<'rb, T, RB> {}

impl<'rb, T: 'rb, RB: RingBuffer<T> + 'rb> DoubleEndedIterator
for RingBufferMutIterator<'rb, T, RB>
for RingBufferMutIterator<'rb, T, RB>
{
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
Expand Down
Loading
Loading