Skip to content

Commit 68bb7d0

Browse files
HEnquistsimlay
andauthored
Fix clippy warnings (#137)
* Include OSStatus when formatting the Unknown error * Mark unsafe functions, fix other clippy warnings * Unused import in example * Add fmt and clippy to ci * Remove needless cast --------- Co-authored-by: simlay <[email protected]>
1 parent fe637bb commit 68bb7d0

File tree

7 files changed

+78
-40
lines changed

7 files changed

+78
-40
lines changed

.github/workflows/coreaudio-rs.yml

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,28 @@ jobs:
2020
# - name: cargo test - all features
2121
# run: cargo test --all-features --verbose
2222

23+
macos-clippy:
24+
runs-on: macOS-latest
25+
steps:
26+
- uses: actions/checkout@v4
27+
- uses: dtolnay/rust-toolchain@master
28+
with:
29+
toolchain: stable
30+
components: clippy
31+
- name: cargo clippy
32+
run: cargo clippy -- -D warnings
33+
34+
macos-rustfmt:
35+
runs-on: macOS-latest
36+
steps:
37+
- uses: actions/checkout@v4
38+
- uses: dtolnay/rust-toolchain@master
39+
with:
40+
toolchain: stable
41+
components: rustfmt
42+
- name: cargo fmt
43+
run: cargo fmt --all -- --check
44+
2345
security-audit:
2446
runs-on: ubuntu-latest
2547
steps:

examples/sine_advanced.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@ use coreaudio::audio_unit::audio_format::LinearPcmFlags;
77
use coreaudio::audio_unit::macos_helpers::{
88
audio_unit_from_device_id, find_matching_physical_format, get_default_device_id,
99
get_hogging_pid, get_supported_physical_stream_formats, set_device_physical_stream_format,
10-
set_device_sample_rate, toggle_hog_mode, AliveListener, RateListener,
10+
toggle_hog_mode, AliveListener, RateListener,
1111
};
12+
// This import is not needed since the use of set_device_sample_rate
13+
// is commented out and left as an example.
14+
// use coreaudio::audio_unit::macos_helpers::set_device_sample_rate;
1215
use coreaudio::audio_unit::render_callback::{self, data};
1316
use coreaudio::audio_unit::{Element, SampleFormat, Scope, StreamFormat};
1417
use objc2_audio_toolbox::kAudioUnitProperty_StreamFormat;

src/audio_unit/macos_helpers.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ pub fn get_default_device_id(input: bool) -> Option<AudioDeviceID> {
6363
NonNull::from(&mut audio_device_id).cast(),
6464
)
6565
};
66-
if status != kAudioHardwareNoError as i32 {
66+
if status != kAudioHardwareNoError {
6767
return None;
6868
}
6969

@@ -248,7 +248,7 @@ pub fn get_audio_device_supports_scope(devid: AudioDeviceID, scope: Scope) -> Re
248248
NonNull::from(&data_size),
249249
NonNull::new(buffers).unwrap().cast(),
250250
);
251-
if status != kAudioHardwareNoError as i32 {
251+
if status != kAudioHardwareNoError {
252252
return Err(Error::Unknown(status));
253253
}
254254

@@ -333,7 +333,7 @@ pub fn set_device_sample_rate(device_id: AudioDeviceID, new_rate: f64) -> Result
333333
Error::from_os_status(status)?;
334334
let n_ranges = data_size as usize / mem::size_of::<AudioValueRange>();
335335
let mut ranges: Vec<AudioValueRange> = vec![];
336-
ranges.reserve_exact(n_ranges as usize);
336+
ranges.reserve_exact(n_ranges);
337337
ranges.set_len(n_ranges);
338338
let status = AudioObjectGetPropertyData(
339339
device_id,
@@ -559,7 +559,7 @@ pub fn get_supported_physical_stream_formats(
559559
Error::from_os_status(status)?;
560560
let n_formats = data_size as usize / mem::size_of::<AudioStreamRangedDescription>();
561561
let mut formats: Vec<AudioStreamRangedDescription> = vec![];
562-
formats.reserve_exact(n_formats as usize);
562+
formats.reserve_exact(n_formats);
563563
formats.set_len(n_formats);
564564

565565
let status = AudioObjectGetPropertyData(
@@ -848,7 +848,7 @@ pub fn toggle_hog_mode(device_id: AudioDeviceID) -> Result<pid_t, Error> {
848848
NonNull::from(&property_address),
849849
0,
850850
null(),
851-
data_size as u32,
851+
data_size,
852852
NonNull::from(&temp_pid).cast(),
853853
);
854854
Error::from_os_status(status)?;

src/audio_unit/mod.rs

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ impl AudioUnit {
227227
elem: Element,
228228
maybe_data: Option<&T>,
229229
) -> Result<(), Error> {
230-
set_property(self.instance, id, scope, elem, maybe_data)
230+
unsafe { set_property(self.instance, id, scope, elem, maybe_data) }
231231
}
232232

233233
/// Gets the value of an **AudioUnit** property.
@@ -241,7 +241,7 @@ impl AudioUnit {
241241
/// - **scope**: The audio unit scope for the property.
242242
/// - **elem**: The audio unit element for the property.
243243
pub fn get_property<T>(&self, id: u32, scope: Scope, elem: Element) -> Result<T, Error> {
244-
get_property(self.instance, id, scope, elem)
244+
unsafe { get_property(self.instance, id, scope, elem) }
245245
}
246246

247247
/// Starts an I/O **AudioUnit**, which in turn starts the audio unit processing graph that it is
@@ -290,10 +290,10 @@ impl AudioUnit {
290290
/// >
291291
/// > - iOS input and output: Linear PCM with 16-bit integer samples.
292292
/// > - iOS audio units and other audio processing: Noninterleaved linear PCM with 8.24-bit
293-
/// fixed-point samples
293+
/// > fixed-point samples
294294
/// > - Mac input and output: Linear PCM with 32-bit floating point samples.
295295
/// > - Mac audio units and other audio processing: Noninterleaved linear PCM with 32-bit
296-
/// floating-point
296+
/// > floating-point
297297
pub fn set_stream_format(
298298
&mut self,
299299
stream_format: StreamFormat,
@@ -375,7 +375,14 @@ impl Drop for AudioUnit {
375375
/// - **scope**: The audio unit scope for the property.
376376
/// - **elem**: The audio unit element for the property.
377377
/// - **maybe_data**: The value that you want to apply to the property.
378-
pub fn set_property<T>(
378+
///
379+
/// Safety
380+
/// ------
381+
/// This function is safe as long as the **au** parameter is a valid pointer to an AudioUnit instance.
382+
/// The caller is responsible for ensuring this.
383+
/// For a safer alternative, consider using an [AudioUnit] instance
384+
/// and calling the associated [AudioUnit::set_property] method.
385+
pub unsafe fn set_property<T>(
379386
au: InnerAudioUnit,
380387
id: u32,
381388
scope: Scope,
@@ -391,7 +398,7 @@ pub fn set_property<T>(
391398
.unwrap_or_else(|| (::std::ptr::null(), 0));
392399
let scope = scope as c_uint;
393400
let elem = elem as c_uint;
394-
unsafe { try_os_status!(AudioUnitSetProperty(au, id, scope, elem, data_ptr, size)) }
401+
try_os_status!(AudioUnitSetProperty(au, id, scope, elem, data_ptr, size));
395402
Ok(())
396403
}
397404

@@ -406,7 +413,14 @@ pub fn set_property<T>(
406413
/// - **id**: The identifier of the property.
407414
/// - **scope**: The audio unit scope for the property.
408415
/// - **elem**: The audio unit element for the property.
409-
pub fn get_property<T>(
416+
///
417+
/// Safety
418+
/// ------
419+
/// This function is safe as long as the **au** parameter is a valid pointer to an AudioUnit instance.
420+
/// The caller is responsible for ensuring this.
421+
/// For a safer alternative, consider using an [AudioUnit] instance
422+
/// and calling the associated [AudioUnit::get_property] method.
423+
pub unsafe fn get_property<T>(
410424
au: InnerAudioUnit,
411425
id: u32,
412426
scope: Scope,
@@ -415,16 +429,14 @@ pub fn get_property<T>(
415429
let scope = scope as c_uint;
416430
let elem = elem as c_uint;
417431
let mut size = ::std::mem::size_of::<T>() as u32;
418-
unsafe {
419-
let mut data_uninit = ::std::mem::MaybeUninit::<T>::uninit();
420-
let data_ptr = NonNull::from(&mut data_uninit).cast::<c_void>();
421-
let size_ptr = NonNull::from(&mut size);
422-
try_os_status!(AudioUnitGetProperty(
423-
au, id, scope, elem, data_ptr, size_ptr
424-
));
425-
let data: T = data_uninit.assume_init();
426-
Ok(data)
427-
}
432+
let mut data_uninit = ::std::mem::MaybeUninit::<T>::uninit();
433+
let data_ptr = NonNull::from(&mut data_uninit).cast::<c_void>();
434+
let size_ptr = NonNull::from(&mut size);
435+
try_os_status!(AudioUnitGetProperty(
436+
au, id, scope, elem, data_ptr, size_ptr
437+
));
438+
let data: T = data_uninit.assume_init();
439+
Ok(data)
428440
}
429441

430442
/// Gets the value of a specified audio session property.

src/audio_unit/render_callback.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,7 @@ impl AudioUnit {
504504
data,
505505
time_stamp: in_time_stamp.read(),
506506
flags,
507-
bus_number: in_bus_number as u32,
507+
bus_number: in_bus_number,
508508
num_frames: in_number_frames as usize,
509509
}
510510
};
@@ -678,7 +678,7 @@ impl AudioUnit {
678678
data,
679679
time_stamp: in_time_stamp.read(),
680680
flags,
681-
bus_number: in_bus_number as u32,
681+
bus_number: in_bus_number,
682682
num_frames: in_number_frames as usize,
683683
}
684684
};
@@ -744,7 +744,7 @@ impl AudioUnit {
744744
// Take ownership over the AudioBufferList in order to safely free it.
745745
let buffer_list: Box<AudioBufferList> = Box::from_raw(buffer_list);
746746
// Free the allocated data from the individual audio buffers.
747-
let ptr = buffer_list.mBuffers.as_ptr() as *const AudioBuffer;
747+
let ptr = buffer_list.mBuffers.as_ptr();
748748
let len = buffer_list.mNumberBuffers as usize;
749749
let buffers: &[AudioBuffer] = slice::from_raw_parts(ptr, len);
750750
for &buffer in buffers {

src/audio_unit/stream_format.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,18 +23,18 @@ use crate::error::{self, Error};
2323
/// `bits_per_channel = size_of::<S>()` / channels_per_frame * 8
2424
///
2525
/// > A *packet* is a collection of one or more contiguous frames. In linear PCM audio, a packet is
26-
/// always a single frame.
26+
/// > always a single frame.
2727
///
2828
/// [from *Core Audio Overview*](https://developer.apple.com/library/ios/documentation/MusicAudio/Conceptual/CoreAudioOverview/WhatisCoreAudio/WhatisCoreAudio.html)
2929
///
3030
/// > The canonical formats in Core Audio are as follows:
3131
/// >
3232
/// > - iOS input and output: Linear PCM with 16-bit integer samples.
3333
/// > - iOS audio units and other audio processing: Noninterleaved linear PCM with 8.24-bit
34-
/// fixed-point samples
34+
/// > fixed-point samples
3535
/// > - Mac input and output: Linear PCM with 32-bit floating point samples.
3636
/// > - Mac audio units and other audio processing: Noninterleaved linear PCM with 32-bit floating
37-
/// point samples.
37+
/// > point samples.
3838
#[derive(Copy, Clone, Debug)]
3939
pub struct StreamFormat {
4040
/// The number of frames of audio data per second used to represent a signal.
@@ -61,7 +61,7 @@ impl StreamFormat {
6161
/// specified in the documentation:
6262
///
6363
/// > Specify kAudioFormatLinearPCM for the mFormatID field. Audio units use uncompressed audio
64-
/// data, so this is the correct format identifier to use whenever you work with audio units.
64+
/// > data, so this is the correct format identifier to use whenever you work with audio units.
6565
///
6666
/// [*Audio Unit Hosting Guide for iOS*](https://developer.apple.com/library/ios/documentation/MusicAudio/Conceptual/AudioUnitHostingGuide_iOS/AudioUnitHostingFundamentals/AudioUnitHostingFundamentals.html)
6767
///
@@ -118,7 +118,7 @@ impl StreamFormat {
118118
let (format, maybe_flag) =
119119
AudioFormat::LinearPCM(flags | LinearPcmFlags::IS_PACKED).as_format_and_flag();
120120

121-
let flag = maybe_flag.unwrap_or(::std::u32::MAX - 2147483647);
121+
let flag = maybe_flag.unwrap_or(u32::MAX - 2147483647);
122122

123123
let non_interleaved = flags.contains(LinearPcmFlags::IS_NON_INTERLEAVED);
124124
let bytes_per_frame = if non_interleaved {

src/error.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ pub mod audio {
5555
Error::MemFull => "Memory full",
5656
Error::Unknown => "An unknown error occurred",
5757
};
58-
write!(f, "{}", description)
58+
write!(f, "{description}")
5959
}
6060
}
6161
}
@@ -109,7 +109,7 @@ pub mod audio_codec {
109109
Error::NotEnoughBufferSpace => "Not enough buffer space",
110110
Error::Unknown => "Unknown error occurred",
111111
};
112-
write!(f, "{}", description)
112+
write!(f, "{description}")
113113
}
114114
}
115115
}
@@ -156,7 +156,7 @@ pub mod audio_format {
156156
Error::UnknownFormat => "The specified data format is not a known format",
157157
Error::Unknown => "Unknown error occurred",
158158
};
159-
write!(f, "{}", description)
159+
write!(f, "{description}")
160160
}
161161
}
162162
}
@@ -239,7 +239,7 @@ pub mod audio_unit {
239239
Error::Unauthorized => "Unauthorized",
240240
Error::Unknown => "Unknown error occurred",
241241
};
242-
write!(f, "{}", description)
242+
write!(f, "{description}")
243243
}
244244
}
245245
}
@@ -324,11 +324,12 @@ impl ::std::fmt::Display for Error {
324324
Error::NonInterleavedInputOnlySupportsMono => write!(f, "In non-interleaved mode input only supports one channel"),
325325
Error::UnsupportedSampleRate => write!(f, "The requested sample rate is not available"),
326326
Error::UnsupportedStreamFormat => write!(f, "The requested stream format is not available"),
327-
Error::Audio(ref err) => write!(f, "{}", err),
328-
Error::AudioCodec(ref err) => write!(f, "{}", err),
329-
Error::AudioFormat(ref err) => write!(f, "{}", err),
330-
Error::AudioUnit(ref err) => write!(f, "{}", err),
331-
Error::Unknown(os_status) => write!(f, "An error unknown to the coreaudio-rs API occurred, OSStatus: {}", os_status),
327+
Error::Audio(ref err) => write!(f, "{err}"),
328+
Error::AudioCodec(ref err) => write!(f, "{err}"),
329+
Error::AudioFormat(ref err) => write!(f, "{err}"),
330+
Error::AudioUnit(ref err) => write!(f, "{err}"),
331+
Error::Unknown(os_status) => write!(f, "An error unknown to the coreaudio-rs API occurred, OSStatus: {os_status}"),
332+
332333
}
333334
}
334335
}

0 commit comments

Comments
 (0)