geng_rodio/source/
stoppable.rs

1use std::time::Duration;
2
3use crate::{Sample, Source};
4
5/// Internal function that builds a `Stoppable` object.
6pub fn stoppable<I>(source: I) -> Stoppable<I> {
7    Stoppable {
8        input: source,
9        stopped: false,
10    }
11}
12
13#[derive(Clone, Debug)]
14pub struct Stoppable<I> {
15    input: I,
16    stopped: bool,
17}
18
19impl<I> Stoppable<I> {
20    /// Stops the sound.
21    #[inline]
22    pub fn stop(&mut self) {
23        self.stopped = true;
24    }
25
26    /// Returns a reference to the inner source.
27    #[inline]
28    pub fn inner(&self) -> &I {
29        &self.input
30    }
31
32    /// Returns a mutable reference to the inner source.
33    #[inline]
34    pub fn inner_mut(&mut self) -> &mut I {
35        &mut self.input
36    }
37
38    /// Returns the inner source.
39    #[inline]
40    pub fn into_inner(self) -> I {
41        self.input
42    }
43}
44
45impl<I> Iterator for Stoppable<I>
46where
47    I: Source,
48    I::Item: Sample,
49{
50    type Item = I::Item;
51
52    #[inline]
53    fn next(&mut self) -> Option<I::Item> {
54        if self.stopped {
55            None
56        } else {
57            self.input.next()
58        }
59    }
60
61    #[inline]
62    fn size_hint(&self) -> (usize, Option<usize>) {
63        self.input.size_hint()
64    }
65}
66
67impl<I> Source for Stoppable<I>
68where
69    I: Source,
70    I::Item: Sample,
71{
72    #[inline]
73    fn current_frame_len(&self) -> Option<usize> {
74        self.input.current_frame_len()
75    }
76
77    #[inline]
78    fn channels(&self) -> u16 {
79        self.input.channels()
80    }
81
82    #[inline]
83    fn sample_rate(&self) -> u32 {
84        self.input.sample_rate()
85    }
86
87    #[inline]
88    fn total_duration(&self) -> Option<Duration> {
89        self.input.total_duration()
90    }
91}