diff --git a/crates/wasi-nn/examples/classification-component-onnx/src/main.rs b/crates/wasi-nn/examples/classification-component-onnx/src/main.rs index affa61681557..3f19ca7e0596 100644 --- a/crates/wasi-nn/examples/classification-component-onnx/src/main.rs +++ b/crates/wasi-nn/examples/classification-component-onnx/src/main.rs @@ -116,13 +116,13 @@ fn main() { } pub fn bytes_to_f32_vec(data: Vec) -> Vec { - let chunks: Vec<&[u8]> = data.chunks(4).collect(); - let v: Vec = chunks - .into_iter() - .map(|c| f32::from_le_bytes(c.try_into().unwrap())) - .collect(); - - v.into_iter().collect() + assert_eq!(data.len() % 4, 0); + data.chunks(4) + .map(|c| { + let arr: [u8; 4] = c.try_into().unwrap(); + f32::from_le_bytes(arr) + }) + .collect() } // Take the image located at 'path', open it, resize it to height x width, and then converts diff --git a/crates/wasi-nn/examples/classification-example-winml/src/main.rs b/crates/wasi-nn/examples/classification-example-winml/src/main.rs index a435fb5f5cc3..59231d13aed9 100644 --- a/crates/wasi-nn/examples/classification-example-winml/src/main.rs +++ b/crates/wasi-nn/examples/classification-example-winml/src/main.rs @@ -121,13 +121,13 @@ fn postprocess(output_tensor: Vec) -> Vec { } pub fn bytes_to_f32_vec(data: Vec) -> Vec { - let chunks: Vec<&[u8]> = data.chunks(4).collect(); - let v: Vec = chunks - .into_iter() - .map(|c| f32::from_ne_bytes(c.try_into().unwrap())) - .collect(); - - v.into_iter().collect() + assert_eq!(data.len() % 4, 0); + data.chunks(4) + .map(|c| { + let arr: [u8; 4] = c.try_into().unwrap(); + f32::from_ne_bytes(arr) + }) + .collect() } // A wrapper for class ID and match probabilities. diff --git a/crates/wasi-nn/src/backend/onnx.rs b/crates/wasi-nn/src/backend/onnx.rs index 13ac2dbed8ac..23f4930f939f 100644 --- a/crates/wasi-nn/src/backend/onnx.rs +++ b/crates/wasi-nn/src/backend/onnx.rs @@ -437,19 +437,21 @@ fn to_input_value(slot: &TensorSlot) -> Result<[SessionInputValue<'_>; 1], Backe } pub fn f32_vec_to_bytes(data: Vec) -> Vec { - let chunks: Vec<[u8; 4]> = data.into_iter().map(|f| f.to_le_bytes()).collect(); - let result: Vec = chunks.iter().flatten().copied().collect(); - result + let mut bytes = Vec::with_capacity(data.len() * 4); + for f in data { + bytes.extend_from_slice(&f.to_le_bytes()); + } + bytes } pub fn bytes_to_f32_vec(data: Vec) -> Vec { - let chunks: Vec<&[u8]> = data.chunks(4).collect(); - let v: Vec = chunks - .into_iter() - .map(|c| f32::from_le_bytes(c.try_into().unwrap())) - .collect(); - - v.into_iter().collect() + assert_eq!(data.len() % 4, 0); + data.chunks(4) + .map(|c| { + let arr: [u8; 4] = c.try_into().unwrap(); + f32::from_le_bytes(arr) + }) + .collect() } /// Returns whether the dimension is dynamic.