From 093c676a3913efd7b1dd857c5f5c4908bae0ab48 Mon Sep 17 00:00:00 2001 From: Adam Gausmann Date: Sat, 3 Feb 2024 23:08:31 -0600 Subject: [PATCH] Add non-panicking variant of with_sample_rate --- src/lib.rs | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index fe14f844e..3b6683c5e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -633,15 +633,28 @@ impl SupportedStreamConfigRange { /// /// # Panics /// - /// Panics if the given `sample_rate` is outside the range specified within this - /// [`SupportedStreamConfigRange`] instance. + /// Panics if the given `sample_rate` is outside the range specified within + /// this [`SupportedStreamConfigRange`] instance. For a non-panicking + /// variant, use [`try_with_sample_rate`](#method.try_with_sample_rate). pub fn with_sample_rate(self, sample_rate: SampleRate) -> SupportedStreamConfig { - assert!(self.min_sample_rate <= sample_rate && sample_rate <= self.max_sample_rate); - SupportedStreamConfig { - channels: self.channels, - sample_rate, - sample_format: self.sample_format, - buffer_size: self.buffer_size, + self.try_with_sample_rate(sample_rate) + .expect("sample rate out of range") + } + + /// Retrieve a [`SupportedStreamConfig`] with the given sample rate and buffer size. + /// + /// Returns `None` if the given sample rate is outside the range specified + /// within this [`SupportedStreamConfigRange`] instance. + pub fn try_with_sample_rate(self, sample_rate: SampleRate) -> Option { + if self.min_sample_rate <= sample_rate && sample_rate <= self.max_sample_rate { + Some(SupportedStreamConfig { + channels: self.channels, + sample_rate, + sample_format: self.sample_format, + buffer_size: self.buffer_size, + }) + } else { + None } }