neon-bindings / neon

Rust bindings for writing safe and fast native Node.js modules.
https://www.neon-bindings.com/
Apache License 2.0
8k stars 283 forks source link

How to turn Rust Image buffer Vec<u8> to JsBuffer? #980

Closed WeismannS closed 1 year ago

WeismannS commented 1 year ago

Code snipper: I'm using the image and imageproc crates


let buffer =  image3.into_raw();
 Ok(cx.buffer(buffer as usize)?)``` obviously doesn't work but i don't what to do
kjvalencik commented 1 year ago

https://docs.rs/neon/1.0.0-alpha.2/neon/types/buffer/trait.TypedArray.html#tymethod.from_slice

use neon::types::JsUint8Array;

// Replace with the real data in a `Vec<u8>`
let data: Vec<u8> = vec![1, 2, 3, 4];

JsUint8Array::from_slice(&data)

Note, as of writing this is only available in the 1.0 pre-release (1.0.0-alpha.2). In 0.10, there is a bit more boilerplate.

let mut buf = cx.array_buffer(data.len());

buf.as_mut_slice(&mut cx).copy_from_slice(&data);

Ok(buf)
kjvalencik commented 1 year ago

As linked above, that method is on the TypedArray trait which needs to be in scope to call it.

use neon::types::buffer::TypedArray;

I hope this helps. I'm going to close this issue since it's more of a support request than an issue with Neon. Cheers!