denoland / deno_bindgen

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

Encode as cstring instead of ptr + len #110

Closed sigmaSd closed 1 year ago

sigmaSd commented 1 year ago

Currently encode encodes as u8 array and then gives the ptr and array len.

I suggest to use cstrings instead so encoding as an u8 array that ends with a null byte.

The why is the current use method requires Deno.UnsafePointer.of(), which requires unbounded --allow-ffi (similar issue https://github.com/denoland/deno/issues/15511)

With the second method, there is no issue, and I can use --allow-ffi=lib

sigmaSd commented 1 year ago

Something like:

export function encode<T>(data: T): Uint8Array {
  return new TextEncoder().encode(JSON.stringify(data) + "\0");
}

export function decode<T>(ptr: bigint): T {
  // ptr is a cstring
  const cstr = new Deno.UnsafePointerView(ptr).getCString();
  return JSON.parse(cstr);
}
sigmaSd commented 1 year ago

Ah wait nvm the cstring method also uses UnsafePointerView which have the same problem