Skip to main content

Module cast

Module cast 

Source
Expand description

Numeric-cast helpers for the audio-plugin → host FFI boundary.

Audio-plugin code routinely casts at three points where Rust’s type system can’t help:

  • FFI struct sizes / element counts: usize (Rust) vs u32 (every C ABI we ship to).
  • Host f64 ↔ DSP f32: parameter values, audio samples, sample-position counters, sample rates.
  • Discrete-index ↔ normalized: GUI selector / dropdown widgets bridge an integer “which option” to a normalized f64 ∈ [0.0, 1.0] parameter value.

MIDI value-domain helpers (7/14/16/32-bit ↔ f32) live in crate::midi alongside the spec’s MIDI 1.0 ↔ MIDI 2.0 bit-replication bridges.

Each helper is #[inline], debug-asserts the input range so a NaN-bearing or overflowing caller fails loud in tests, and is the only place in the workspace that’s allowed to reach for as on its specific shape. The lints cast_possible_truncation, cast_sign_loss, and cast_precision_loss are allowed at the module level so the helpers can do their job without per-site annotations.

Functions§

discrete_index
Map a normalized value in [0.0, 1.0] to a discrete index in [0, count - 1]. Returns 0 when count <= 1 - the index is pinned to the only valid slot.
discrete_norm
Map a discrete index in [0, count - 1] to a normalized value in [0.0, 1.0]. Returns 0.0 when count <= 1 - there’s only one valid index, so any input collapses to the bottom of the range.
frame_count_f64
Inverse of sample_count_usize: convert a sample/frame count to f64 for time math (frames / sample_rate → seconds, frames * ratio → resampled length, etc.).
len_u32
Cast a usize element count (Vec::len(), iterator count) to u32 for an FFI field.
sample_count_usize
Convert a sample-count expressed as f64 (e.g. seconds * sample_rate) to usize, saturating on overflow / negative / non-finite inputs. NaN and negative inputs collapse to 0; positive infinity and any value past usize::MAX clamp to usize::MAX.
sample_pos_i64
Convert a host-supplied sample-position f64 to the i64 truce’s TransportInfo::position_samples carries.
sample_rate_u32
Cast a host-supplied sample rate (f64) to the u32 audio APIs (cpal, hound, Core Audio’s AudioStreamBasicDescription) carry.
size_of_u32
Cast core::mem::size_of::<T>() to u32 for an FFI struct’s size field.