rodio/source/
repeat.rs

1use std::time::Duration;
2
3use crate::source::buffered::Buffered;
4
5use super::SeekError;
6use crate::common::{ChannelCount, SampleRate};
7use crate::Source;
8
9/// Internal function that builds a `Repeat` object.
10pub fn repeat<I>(input: I) -> Repeat<I>
11where
12    I: Source,
13{
14    let input = input.buffered();
15    Repeat {
16        inner: input.clone(),
17        next: input,
18    }
19}
20
21/// A source that repeats the given source.
22pub struct Repeat<I>
23where
24    I: Source,
25{
26    inner: Buffered<I>,
27    next: Buffered<I>,
28}
29
30impl<I> Iterator for Repeat<I>
31where
32    I: Source,
33{
34    type Item = <I as Iterator>::Item;
35
36    #[inline]
37    fn next(&mut self) -> Option<<I as Iterator>::Item> {
38        if let Some(value) = self.inner.next() {
39            return Some(value);
40        }
41
42        self.inner = self.next.clone();
43        self.inner.next()
44    }
45
46    #[inline]
47    fn size_hint(&self) -> (usize, Option<usize>) {
48        // infinite
49        (0, None)
50    }
51}
52
53impl<I> Source for Repeat<I>
54where
55    I: Iterator + Source,
56{
57    #[inline]
58    fn current_span_len(&self) -> Option<usize> {
59        match self.inner.current_span_len() {
60            Some(0) => self.next.current_span_len(),
61            a => a,
62        }
63    }
64
65    #[inline]
66    fn channels(&self) -> ChannelCount {
67        match self.inner.current_span_len() {
68            Some(0) => self.next.channels(),
69            _ => self.inner.channels(),
70        }
71    }
72
73    #[inline]
74    fn sample_rate(&self) -> SampleRate {
75        match self.inner.current_span_len() {
76            Some(0) => self.next.sample_rate(),
77            _ => self.inner.sample_rate(),
78        }
79    }
80
81    #[inline]
82    fn total_duration(&self) -> Option<Duration> {
83        None
84    }
85
86    #[inline]
87    fn try_seek(&mut self, pos: Duration) -> Result<(), SeekError> {
88        self.inner.try_seek(pos)
89    }
90}
91
92impl<I> Clone for Repeat<I>
93where
94    I: Source,
95{
96    #[inline]
97    fn clone(&self) -> Repeat<I> {
98        Repeat {
99            inner: self.inner.clone(),
100            next: self.next.clone(),
101        }
102    }
103}