denoland / deno_bindgen

Write high-level Deno FFI libraries in Rust.
MIT License
287 stars 28 forks source link

why &[u8] use TextEncoder ? can't pass binary ... #95

Closed usrtax closed 2 years ago

usrtax commented 2 years ago
use deno_bindgen::deno_bindgen;
use image::{load_from_memory, EncodableLayout};
use webp::Encoder;

#[deno_bindgen]
pub struct Img {
    bin: Option<Vec<u8>>,
}

#[deno_bindgen]
pub fn toWebp(img: &[u8], quality: u8) -> Img {
    if let Ok(img) = load_from_memory(img) {
        let encoder = Encoder::from_image(&img).unwrap();
        let encoded_webp = encoder.encode((quality as f32) / 100.0);
        return Img {
            bin: Some(encoded_webp.as_bytes().into()),
        };
    }

    Img { bin: None }
}
export function toWebp(a0: Uint8Array, a1: number) {
  const a0_buf = encode(a0)
usrtax commented 2 years ago
image

when I delete encode, the error is error: Uncaught (in promise) TypeError: Invalid FFI pointer type, expected null, integer or BigInt

+ deno run --unstable -A test.js
Uint8Array(223418) [
  137,  80,  78,  71,  13,  10,  26,  10,  0,   0,   0,  13,  73,  72,  68,
   82,   0,   0,   3,  32,   0,   0,   3, 32,   8,   6,   0,   0,   0, 219,
  112,   6, 104,   0,   3, 104, 129,  73, 68,  65,  84, 120, 156, 236, 253,
  125, 172,  37, 231, 125, 223,   9, 214, 83,  85, 247, 165,  95, 216, 162,
  152,  38,  77, 133, 140,  68, 135, 132, 69, 209, 145,  32, 197,  14, 163,
  216, 227,  73,  35, 241, 174,  55,  26,  5, 144,  98, 216, 142, 227, 137,
  200, 205, 219, 172, 181,  99, 197, 246, 96, 118,
  ... 223318 more items
] 223418
error: Uncaught (in promise) TypeError: Invalid FFI pointer type, expected null, integer or BigInt
  let rawResult = _lib.symbols.toWebp(a0, a0.byteLength, a1)
littledivy commented 2 years ago

It's not TextEncoder, encode function returns back the input its a TypedArray

skanehira commented 2 years ago

@usrtax deno_bindgen cannot return binary data which included by structs because struct is always convert to the JavaScript's Object through JSON.parse

I think If you want to return binary, you have two choice.

  1. Return TypeArray only.
  2. Use base64 for encode binary to String, and decode string to bytes in Deno.

https://github.com/skanehira/deno-clippy/blob/b4b5eabc82964bf97a00394b31f86190923e2482/mod.ts#L38-L50

https://github.com/skanehira/deno-clippy/blob/b4b5eabc82964bf97a00394b31f86190923e2482/src/lib.rs#L15-L26