owl_patch/sample_buffer/
convert.rs

1/// Sample / Buffer conversion trait
2pub trait ConvertFrom<T: ?Sized> {
3    /// Read from `other`, converting into the correct format
4    fn convert_from(&mut self, other: T);
5}
6
7impl<T> ConvertFrom<T> for T {
8    fn convert_from(&mut self, value: T) {
9        *self = value
10    }
11}
12
13/// Sample / Buffer conversion trait
14pub trait ConvertTo<T> {
15    /// Write to `other`, converting into the correct format
16    fn convert_to(&self, other: &mut T);
17}
18
19/// Auto implementation
20impl<A, B> ConvertTo<B> for A
21where
22    for<'a> B: ConvertFrom<&'a A>,
23{
24    fn convert_to(&self, other: &mut B) {
25        other.convert_from(self)
26    }
27}
28
29impl ConvertFrom<i32> for f32 {
30    /// Convertion to float, so that i32::MAX => 1.0 and i32::MIN => -1.0
31    fn convert_from(&mut self, other: i32) {
32        const MUL: f32 = 1.0 / (0x80000000i64 as f32);
33        *self = other as f32 * MUL
34    }
35}
36
37impl ConvertFrom<f32> for i32 {
38    /// Convertion from float, so that 1.0 => i32::MAX and -1.0 => i32::MIN
39    fn convert_from(&mut self, other: f32) {
40        const MUL: f32 = 0x80000000i64 as f32;
41        *self = (other * MUL) as i32
42    }
43}
44
45impl ConvertFrom<i16> for f32 {
46    /// Convertion to float, so that i16::MAX => 1.0 and i16::MIN => -1.0
47    fn convert_from(&mut self, other: i16) {
48        const MUL: f32 = 1.0 / i16::MAX as f32;
49        *self = other as f32 * MUL
50    }
51}
52
53impl ConvertFrom<f32> for i16 {
54    /// Convertion from float, so that 1.0 => i16::MAX and -1.0 => i16::MIN
55    fn convert_from(&mut self, other: f32) {
56        const MUL: f32 = i16::MAX as f32;
57        *self = (other * MUL) as i16
58    }
59}