Skip to content

Commit 5182c4f

Browse files
authored
Merge pull request #430 from orottier/feature/unify-panic-messages
Unify panic messages
2 parents 07c6d0f + bc31604 commit 5182c4f

24 files changed

+313
-268
lines changed

src/analysis.rs

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -33,42 +33,42 @@ const MAX_FFT_SIZE: usize = 32768;
3333

3434
// [spec] This MUST be a power of two in the range 32 to 32768, otherwise an
3535
// IndexSizeError exception MUST be thrown.
36+
#[allow(clippy::manual_range_contains)]
3637
fn assert_valid_fft_size(fft_size: usize) {
37-
if !fft_size.is_power_of_two() {
38-
panic!(
39-
"IndexSizeError - Invalid fft size: {:?} is not a power of two",
40-
fft_size
41-
);
42-
}
43-
44-
if !(MIN_FFT_SIZE..=MAX_FFT_SIZE).contains(&fft_size) {
45-
panic!(
46-
"IndexSizeError - Invalid fft size: {:?} is outside range [{:?}, {:?}]",
47-
fft_size, MIN_FFT_SIZE, MAX_FFT_SIZE
48-
);
49-
}
38+
assert!(
39+
fft_size.is_power_of_two(),
40+
"IndexSizeError - Invalid fft size: {:?} is not a power of two",
41+
fft_size
42+
);
43+
44+
assert!(
45+
fft_size >= MIN_FFT_SIZE && fft_size <= MAX_FFT_SIZE,
46+
"IndexSizeError - Invalid fft size: {:?} is outside range [{:?}, {:?}]",
47+
fft_size,
48+
MIN_FFT_SIZE,
49+
MAX_FFT_SIZE
50+
);
5051
}
5152

5253
// [spec] If the value of this attribute is set to a value less than 0 or more
5354
// than 1, an IndexSizeError exception MUST be thrown.
55+
#[allow(clippy::manual_range_contains)]
5456
fn assert_valid_smoothing_time_constant(smoothing_time_constant: f64) {
55-
if !(0. ..=1.).contains(&smoothing_time_constant) {
56-
panic!(
57-
"IndexSizeError - Invalid smoothing time constant: {:?} is outside range [0, 1]",
58-
smoothing_time_constant
59-
);
60-
}
57+
assert!(
58+
smoothing_time_constant >= 0. && smoothing_time_constant <= 1.,
59+
"IndexSizeError - Invalid smoothing time constant: {:?} is outside range [0, 1]",
60+
smoothing_time_constant
61+
);
6162
}
6263

6364
// [spec] If the value of minDecibels is set to a value more than or equal to maxDecibels, an
6465
// IndexSizeError exception MUST be thrown.
6566
fn assert_valid_decibels(min_decibels: f64, max_decibels: f64) {
66-
if min_decibels >= max_decibels {
67-
panic!(
68-
"IndexSizeError - Invalid min decibels: {:?} is greater than or equals to max decibels {:?}",
69-
min_decibels, max_decibels
70-
);
71-
}
67+
assert!(
68+
min_decibels < max_decibels,
69+
"IndexSizeError - Invalid min decibels: {:?} is greater than or equals to max decibels {:?}",
70+
min_decibels, max_decibels
71+
);
7272
}
7373

7474
// as the queue is composed of AtomicF32 having only 1 render quantum of extra

src/context/offline.rs

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -125,10 +125,12 @@ impl OfflineAudioContext {
125125
/// Panics if this method is called multiple times
126126
#[must_use]
127127
pub fn start_rendering_sync(&mut self) -> AudioBuffer {
128-
let renderer = match self.renderer.lock().unwrap().take() {
129-
None => panic!("InvalidStateError: Cannot call `startRendering` twice"),
130-
Some(v) => v,
131-
};
128+
let renderer = self
129+
.renderer
130+
.lock()
131+
.unwrap()
132+
.take()
133+
.expect("InvalidStateError - Cannot call `startRendering` twice");
132134
let OfflineAudioContextRenderer {
133135
renderer,
134136
suspend_callbacks,
@@ -155,10 +157,12 @@ impl OfflineAudioContext {
155157
/// Panics if this method is called multiple times.
156158
pub async fn start_rendering(&self) -> AudioBuffer {
157159
// We are mixing async with a std Mutex, so be sure not to `await` while the lock is held
158-
let renderer = match self.renderer.lock().unwrap().take() {
159-
None => panic!("InvalidStateError: Cannot call `startRendering` twice"),
160-
Some(v) => v,
161-
};
160+
let renderer = self
161+
.renderer
162+
.lock()
163+
.unwrap()
164+
.take()
165+
.expect("InvalidStateError - Cannot call `startRendering` twice");
162166

163167
let OfflineAudioContextRenderer {
164168
renderer,
@@ -248,18 +252,15 @@ impl OfflineAudioContext {
248252
// We are mixing async with a std Mutex, so be sure not to `await` while the lock is held
249253
{
250254
let mut lock = self.renderer.lock().unwrap();
251-
let renderer = match lock.as_mut() {
252-
Some(r) => r,
253-
None => {
254-
panic!("InvalidStateError: cannot suspend when rendering has already started")
255-
}
256-
};
255+
let renderer = lock
256+
.as_mut()
257+
.expect("InvalidStateError - cannot suspend when rendering has already started");
257258

258259
let insert_pos = renderer
259260
.suspend_promises
260261
.binary_search_by_key(&quantum, |&(q, _)| q)
261262
.expect_err(
262-
"InvalidStateError: cannot suspend multiple times at the same render quantum",
263+
"InvalidStateError - cannot suspend multiple times at the same render quantum",
263264
);
264265

265266
renderer
@@ -316,16 +317,15 @@ impl OfflineAudioContext {
316317
let quantum = self.calculate_suspend_frame(suspend_time);
317318

318319
let mut lock = self.renderer.lock().unwrap();
319-
let renderer = match lock.as_mut() {
320-
Some(r) => r,
321-
None => panic!("InvalidStateError: cannot suspend when rendering has already started"),
322-
};
320+
let renderer = lock
321+
.as_mut()
322+
.expect("InvalidStateError - cannot suspend when rendering has already started");
323323

324324
let insert_pos = renderer
325325
.suspend_callbacks
326326
.binary_search_by_key(&quantum, |(q, _c)| *q)
327327
.expect_err(
328-
"InvalidStateError: cannot suspend multiple times at the same render quantum",
328+
"InvalidStateError - cannot suspend multiple times at the same render quantum",
329329
);
330330

331331
let boxed_callback = Box::new(|ctx: &mut OfflineAudioContext| {

src/decoding.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ impl<R: Read> Read for MediaInput<R> {
3434

3535
impl<R> Seek for MediaInput<R> {
3636
fn seek(&mut self, _pos: SeekFrom) -> std::io::Result<u64> {
37-
panic!("MediaInput does not support seeking")
37+
panic!("NotSupportedError - MediaInput does not support seeking")
3838
}
3939
}
4040

src/io/cpal.rs

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -132,23 +132,23 @@ impl AudioBackendManager for CpalBackend {
132132

133133
let device = if options.sink_id.is_empty() {
134134
host.default_output_device()
135-
.expect("no output device available")
135+
.expect("InvalidStateError - no output device available")
136136
} else {
137137
Self::enumerate_devices_sync()
138138
.into_iter()
139139
.find(|e| e.device_id() == options.sink_id)
140140
.map(|e| *e.device().downcast::<cpal::Device>().unwrap())
141141
.unwrap_or_else(|| {
142142
host.default_output_device()
143-
.expect("no output device available")
143+
.expect("InvalidStateError - no output device available")
144144
})
145145
};
146146

147147
log::info!("Output device: {:?}", device.name());
148148

149149
let default_device_config = device
150150
.default_output_config()
151-
.expect("error while querying config");
151+
.expect("InvalidStateError - error while querying device output config");
152152

153153
// we grab the largest number of channels provided by the soundcard
154154
// clamped to MAX_CHANNELS, this value cannot be changed by the user
@@ -247,11 +247,15 @@ impl AudioBackendManager for CpalBackend {
247247
Arc::clone(&output_latency),
248248
);
249249

250-
spawned.expect("OutputStream build failed with default config")
250+
spawned
251+
.expect("InvalidStateError - Unable to spawn output stream with default config")
251252
}
252253
};
253254

254-
stream.play().expect("Stream refused to play");
255+
// Required because some hosts don't play the stream automatically
256+
stream
257+
.play()
258+
.expect("InvalidStateError - Output stream refused to play");
255259

256260
CpalBackend {
257261
stream: ThreadSafeClosableStream::new(stream),
@@ -272,23 +276,23 @@ impl AudioBackendManager for CpalBackend {
272276

273277
let device = if options.sink_id.is_empty() {
274278
host.default_input_device()
275-
.expect("no input device available")
279+
.expect("InvalidStateError - no input device available")
276280
} else {
277281
Self::enumerate_devices_sync()
278282
.into_iter()
279283
.find(|e| e.device_id() == options.sink_id)
280284
.map(|e| *e.device().downcast::<cpal::Device>().unwrap())
281285
.unwrap_or_else(|| {
282286
host.default_input_device()
283-
.expect("no input device available")
287+
.expect("InvalidStateError - no input device available")
284288
})
285289
};
286290

287291
log::info!("Input device: {:?}", device.name());
288292

289293
let supported = device
290294
.default_input_config()
291-
.expect("error while querying configs");
295+
.expect("InvalidStateError - error while querying device input config");
292296

293297
// clone the config, we may need to fall back on it later
294298
let mut preferred: StreamConfig = supported.clone().into();
@@ -349,12 +353,15 @@ impl AudioBackendManager for CpalBackend {
349353
&supported_config,
350354
renderer,
351355
);
352-
spawned.expect("Unable to spawn input stream with default config")
356+
spawned
357+
.expect("InvalidStateError - Unable to spawn input stream with default config")
353358
}
354359
};
355360

356361
// Required because some hosts don't play the stream automatically
357-
stream.play().expect("Input stream refused to play");
362+
stream
363+
.play()
364+
.expect("InvalidStateError - Input stream refused to play");
358365

359366
let backend = CpalBackend {
360367
stream: ThreadSafeClosableStream::new(stream),

src/io/cubeb.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,9 @@ fn init_output_backend<const N: usize>(
132132
println!("stream state changed: {state:?}");
133133
});
134134

135-
let stream = builder.init(ctx).expect("Failed to create cubeb stream");
135+
let stream = builder
136+
.init(ctx)
137+
.expect("InvalidStateError - Failed to create cubeb stream");
136138
ThreadSafeClosableStream::new(stream)
137139
}
138140

@@ -346,7 +348,9 @@ impl AudioBackendManager for CubebBackend {
346348
println!("stream state changed: {state:?}");
347349
});
348350

349-
let stream = builder.init(&ctx).expect("Failed to create cubeb stream");
351+
let stream = builder
352+
.init(&ctx)
353+
.expect("InvalidStateError - Failed to create cubeb stream");
350354

351355
stream.start().unwrap();
352356

src/io/mod.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -204,12 +204,11 @@ fn buffer_size_for_latency_category(
204204
#[allow(clippy::cast_sign_loss)]
205205
#[allow(clippy::cast_possible_truncation)]
206206
AudioContextLatencyCategory::Custom(latency) => {
207-
if latency <= 0. {
208-
panic!(
209-
"RangeError - Invalid custom latency: {:?}, should be strictly positive",
210-
latency
211-
);
212-
}
207+
assert!(
208+
latency > 0.,
209+
"RangeError - Invalid custom latency: {:?}, should be strictly positive",
210+
latency
211+
);
213212

214213
let buffer_size = (latency * sample_rate as f64) as usize;
215214
buffer_size.next_power_of_two()

src/lib.rs

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -158,12 +158,11 @@ impl AtomicF64 {
158158
pub(crate) fn assert_valid_sample_rate(sample_rate: f32) {
159159
// 1000 Hertz is a just a random cutoff, but it helps a if someone accidentally puts a
160160
// timestamp in the sample_rate variable
161-
if sample_rate <= 1000. {
162-
panic!(
163-
"NotSupportedError - Invalid sample rate: {:?}, should be greater than 1000",
164-
sample_rate
165-
);
166-
}
161+
assert!(
162+
sample_rate > 1000.,
163+
"NotSupportedError - Invalid sample rate: {:?}, should be greater than 1000",
164+
sample_rate
165+
);
167166
}
168167

169168
/// Assert that the given number of channels is valid.
@@ -177,12 +176,12 @@ pub(crate) fn assert_valid_sample_rate(sample_rate: f32) {
177176
#[track_caller]
178177
#[inline(always)]
179178
pub(crate) fn assert_valid_number_of_channels(number_of_channels: usize) {
180-
if number_of_channels == 0 || number_of_channels > MAX_CHANNELS {
181-
panic!(
182-
"NotSupportedError - Invalid number of channels: {:?} is outside range [1, {:?}]",
183-
number_of_channels, MAX_CHANNELS
184-
);
185-
}
179+
assert!(
180+
number_of_channels > 0 && number_of_channels <= MAX_CHANNELS,
181+
"NotSupportedError - Invalid number of channels: {:?} is outside range [1, {:?}]",
182+
number_of_channels,
183+
MAX_CHANNELS
184+
);
186185
}
187186

188187
/// Assert that the given channel number is valid according to the number of channels
@@ -196,12 +195,12 @@ pub(crate) fn assert_valid_number_of_channels(number_of_channels: usize) {
196195
#[track_caller]
197196
#[inline(always)]
198197
pub(crate) fn assert_valid_channel_number(channel_number: usize, number_of_channels: usize) {
199-
if channel_number >= number_of_channels {
200-
panic!(
201-
"IndexSizeError - Invalid channel number {:?} (number of channels: {:?})",
202-
channel_number, number_of_channels
203-
);
204-
}
198+
assert!(
199+
channel_number < number_of_channels,
200+
"IndexSizeError - Invalid channel number {:?} (number of channels: {:?})",
201+
channel_number,
202+
number_of_channels
203+
);
205204
}
206205

207206
/// Assert that the given value number is a valid time information, i.e. greater
@@ -215,16 +214,16 @@ pub(crate) fn assert_valid_channel_number(channel_number: usize, number_of_chann
215214
#[track_caller]
216215
#[inline(always)]
217216
pub(crate) fn assert_valid_time_value(value: f64) {
218-
if !value.is_finite() {
219-
panic!("TypeError - The provided time value is non-finite.");
220-
}
221-
222-
if value < 0. {
223-
panic!(
224-
"RangeError - The provided time value ({:?}) cannot be negative",
225-
value
226-
);
227-
}
217+
assert!(
218+
value.is_finite(),
219+
"TypeError - The provided time value is non-finite.",
220+
);
221+
222+
assert!(
223+
value >= 0.,
224+
"RangeError - The provided time value ({:?}) cannot be negative",
225+
value
226+
);
228227
}
229228

230229
pub(crate) trait AudioBufferIter: Iterator<Item = FallibleBuffer> + Send + 'static {}

src/media_recorder/mod.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -204,9 +204,11 @@ impl MediaRecorder {
204204
///
205205
/// Will panic when the recorder has already started
206206
pub fn start(&self) {
207-
if self.inner.active.swap(true, Ordering::Relaxed) {
208-
panic!("InvalidStateError: recorder has already started")
209-
}
207+
let prev_active = self.inner.active.swap(true, Ordering::Relaxed);
208+
assert!(
209+
!prev_active,
210+
"InvalidStateError - recorder has already started"
211+
);
210212

211213
let inner = Arc::clone(&self.inner);
212214
let blob = Vec::with_capacity(128 * 1024);

src/node/audio_buffer_source.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -280,9 +280,10 @@ impl AudioBufferSourceNode {
280280
pub fn set_buffer(&mut self, audio_buffer: AudioBuffer) {
281281
let clone = audio_buffer.clone();
282282

283-
if self.buffer.is_some() {
284-
panic!("InvalidStateError - cannot assign buffer twice");
285-
}
283+
assert!(
284+
self.buffer.is_none(),
285+
"InvalidStateError - cannot assign buffer twice",
286+
);
286287
self.buffer = Some(audio_buffer);
287288

288289
self.registration.post_message(clone);

0 commit comments

Comments
 (0)