audio_core/sample.rs
1/// A sample that can be stored in an audio buffer. Types implementing this are
2/// known as being sample apt.
3///
4/// Sample apt types have the following gurantees:
5///
6/// * The type does not need to be dropped (by implementing [Copy]).
7/// * The type can safely be initialized with the all-zeros bit pattern.
8///
9/// # Safety
10///
11/// Implementor must make sure that a bit-pattern of all-zeros is a legal
12/// bit-pattern for the implemented type.
13pub unsafe trait Sample: Copy {
14 /// The zero pattern for the sample.
15 const ZERO: Self;
16}
17
18/// The bit-pattern of all zeros is a legal bit-pattern for floats.
19///
20/// See for example:
21/// <https://doc.rust-lang.org/std/primitive.f32.html#method.to_bits>.
22///
23/// Proof:
24///
25/// ```
26/// use audio::Sample;
27///
28/// assert_eq!((f64::ZERO).to_bits(), 0u64);
29/// ```
30unsafe impl Sample for f32 {
31 const ZERO: Self = 0.0;
32}
33
34/// The bit-pattern of all zeros is a legal bit-pattern for floats.
35///
36/// See for example:
37/// <https://doc.rust-lang.org/std/primitive.f64.html#method.to_bits>.
38///
39/// Proof:
40///
41/// ```
42/// use audio::Sample;
43///
44/// assert_eq!((f64::ZERO).to_bits(), 0u64);
45/// ```
46unsafe impl Sample for f64 {
47 const ZERO: Self = 0.0;
48}
49
50// Helper macro to implement [Sample] for integer types.
51macro_rules! impl_int {
52 ($ty:ty) => {
53 unsafe impl Sample for $ty {
54 const ZERO: Self = 0;
55 }
56 };
57}
58
59// Note: trivial integer implementations.
60impl_int!(u8);
61impl_int!(u16);
62impl_int!(u32);
63impl_int!(u64);
64impl_int!(u128);
65impl_int!(i8);
66impl_int!(i16);
67impl_int!(i32);
68impl_int!(i64);
69impl_int!(i128);
70impl_int!(usize);
71impl_int!(isize);
72
73// Implement for byte arrays of any length
74unsafe impl<const N: usize> Sample for [u8; N] {
75 const ZERO: Self = [0; N];
76}