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

Implement DoubleEndedIterator for HistoryBuffer::oldest_ordered #431

Closed
Eugeny opened this issue Dec 28, 2023 · 3 comments
Closed

Implement DoubleEndedIterator for HistoryBuffer::oldest_ordered #431

Eugeny opened this issue Dec 28, 2023 · 3 comments

Comments

@Eugeny
Copy link

Eugeny commented Dec 28, 2023

Would be very useful and seems relatively straightforward to implement ✌️

@Eugeny Eugeny changed the title Add DoubleEndedIterator to HistoryBuffer::oldest_ordered Implement DoubleEndedIterator for HistoryBuffer::oldest_ordered Dec 28, 2023
@Eugeny
Copy link
Author

Eugeny commented Dec 29, 2023

Here's a "dumb" outside-the-crate implementation:

pub struct HistoryBufferDoubleEndedIterator<'a, T, const N: usize> {
    buf: &'a HistoryBuffer<T, N>,
    cur: usize,
    cur_back: usize,
}

impl<'a, T, const N: usize> HistoryBufferDoubleEndedIterator<'a, T, N> {
    pub fn new(buf: &'a HistoryBuffer<T, N>) -> Self {
        Self {
            buf,
            cur: 0,
            cur_back: buf.len(),
        }
    }
}

impl<'a, T, const N: usize> ExactSizeIterator for HistoryBufferDoubleEndedIterator<'a, T, N> {}

impl<'a, T, const N: usize> Iterator for HistoryBufferDoubleEndedIterator<'a, T, N> {
    type Item = &'a T;

    fn next(&mut self) -> Option<&'a T> {
        let (a, b) = self.buf.as_slices();
        self.cur += 1;
        if self.cur < a.len() {
            Some(&a[self.cur])
        } else if self.cur < a.len() + b.len() {
            Some(&b[self.cur - a.len()])
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.buf.len(), Some(self.buf.len()))
    }
}

impl<'a, T, const N: usize> DoubleEndedIterator for HistoryBufferDoubleEndedIterator<'_, T, N> {
    fn next_back(&mut self) -> Option<Self::Item> {
        let (a, b) = self.buf.as_slices();
        if self.cur_back == 0 {
            return None;
        }
        self.cur_back -= 1;
        if self.cur_back < a.len() {
            Some(&a[self.cur_back])
        } else if self.cur_back < a.len() + b.len() {
            Some(&b[self.cur_back - a.len()])
        } else {
            None
        }
    }
}

@witek103
Copy link
Contributor

you can look at #449

@Dirbaio
Copy link
Member

Dirbaio commented Jul 1, 2024

done in #449

@Dirbaio Dirbaio closed this as completed Jul 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants