Implement f32 to i16 and f32 to u16 conversions

This commit is contained in:
Pierre Krieger 2014-12-22 16:35:10 +01:00
parent 4239fae948
commit 6f01c38a62
1 changed files with 14 additions and 4 deletions

View File

@ -96,11 +96,23 @@ impl Sample for f32 {
} }
fn to_vec_i16(input: &[f32]) -> Cow<Vec<i16>, [i16]> { fn to_vec_i16(input: &[f32]) -> Cow<Vec<i16>, [i16]> {
unimplemented!() Cow::Owned(input.iter().map(|&value| {
if value >= 0.0 {
(value * 32767.0) as i16
} else {
(value * 32768.0) as i16
}
}).collect())
} }
fn to_vec_u16(input: &[f32]) -> Cow<Vec<u16>, [u16]> { fn to_vec_u16(input: &[f32]) -> Cow<Vec<u16>, [u16]> {
unimplemented!() Cow::Owned(input.iter().map(|&value| {
if value >= 0.0 {
((value * 32767.0) + 32768.0) as u16
} else {
((value * 32768.0) + 32768.0) as u16
}
}).collect())
} }
fn to_vec_f32(input: &[f32]) -> Cow<Vec<f32>, [f32]> { fn to_vec_f32(input: &[f32]) -> Cow<Vec<f32>, [f32]> {
@ -149,14 +161,12 @@ mod test {
} }
#[test] #[test]
#[ignore] // TODO: not yet implemented
fn f32_to_i16() { fn f32_to_i16() {
let out = Sample::to_vec_i16(&[0.0f32, -0.5, 1.0, -1.0]).into_owned(); let out = Sample::to_vec_i16(&[0.0f32, -0.5, 1.0, -1.0]).into_owned();
assert_eq!(out, vec![0, -16384, 32767, -32768]); assert_eq!(out, vec![0, -16384, 32767, -32768]);
} }
#[test] #[test]
#[ignore] // TODO: not yet implemented
fn f32_to_u16() { fn f32_to_u16() {
let out = Sample::to_vec_u16(&[-1.0f32, 0.0, 1.0]).into_owned(); let out = Sample::to_vec_u16(&[-1.0f32, 0.0, 1.0]).into_owned();
assert_eq!(out, vec![0, 32768, 65535]); assert_eq!(out, vec![0, 32768, 65535]);