From 3d1826007e9dcfd6bd102016b173154524ec5080 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Fri, 12 May 2023 16:52:06 +0200 Subject: [PATCH] Avoid panics when incorrect buffer sizes are provided to read/write_frames --- src/errors.rs | 6 ++++++ src/wavereader.rs | 12 ++++++------ src/wavewriter.rs | 19 ++++++++++--------- 3 files changed, 22 insertions(+), 15 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index 378efd3..7fd988f 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -41,6 +41,12 @@ pub enum Error { /// The file is not optimized for writing new data DataChunkNotPreparedForAppend, + + /// A buffer with a length that isn't a multiple of channel_count was provided + InvalidBufferSize { + buffer_size: usize, + channel_count: u16, + }, } impl StdError for Error {} diff --git a/src/wavereader.rs b/src/wavereader.rs index f0e3320..9d71102 100644 --- a/src/wavereader.rs +++ b/src/wavereader.rs @@ -110,12 +110,12 @@ impl AudioFrameReader { let common_format = self.format.common_format(); let bits_per_sample = self.format.bits_per_sample; - assert!( - buffer.len() % channel_count == 0, - "read_frames was called with a mis-sized buffer, expected a multiple of {}, was {}", - channel_count, - buffer.len() - ); + if buffer.len() % channel_count != 0 { + return Err(Error::InvalidBufferSize { + buffer_size: buffer.len(), + channel_count: self.format.channel_count, + }); + } let position = self.inner.stream_position()? - self.start; let frames_requested = (buffer.len() / channel_count) as u64; diff --git a/src/wavewriter.rs b/src/wavewriter.rs index c3aa0c5..c5df769 100644 --- a/src/wavewriter.rs +++ b/src/wavewriter.rs @@ -37,21 +37,22 @@ where /// Write interleaved samples in `buffer` /// - /// # Panics - /// - /// This function will panic if `buffer.len()` modulo the Wave file's channel count - /// is not zero. - pub fn write_frames(&mut self, buffer: &[S]) -> Result + /// The writer will convert from the buffer's sample type into the file's sample type. + /// Note that no dithering will be applied during sample type conversion, + /// if dithering is required then it will need to be applied manually. + pub fn write_frames(&mut self, buffer: &[S]) -> Result<(), Error> where S: Sample, { let format = &self.inner.inner.format; let channel_count = format.channel_count as usize; - assert!( - buffer.len() % channel_count == 0, - "frames buffer does not contain a number of samples % channel_count == 0" - ); + if buffer.len() % channel_count != 0 { + return Err(Error::InvalidBufferSize { + buffer_size: buffer.len(), + channel_count: format.channel_count, + }); + } let mut write_buffer = self .inner