diff --git a/js/dune b/js/dune index 98197ce..2b6e598 100644 --- a/js/dune +++ b/js/dune @@ -5,6 +5,9 @@ (libraries js_of_ocaml) (preprocess (pps js_of_ocaml-ppx)) + (foreign_stubs + (language c) + (names stubs)) (js_of_ocaml (flags --no-sourcemap) (javascript_files binaryen.js postlude.js))) diff --git a/js/module.ml b/js/module.ml index c60158c..61616f3 100644 --- a/js/module.ml +++ b/js/module.ml @@ -1,28 +1,12 @@ -open Js_of_ocaml open Js_of_ocaml.Js open Js_of_ocaml.Js.Unsafe -let make_encoder () = new_obj global ##. TextEncoder [||] +external u8a_to_bytes : 'a -> bytes = "caml_bytes_of_array" -let encode encoder (value : string) = - meth_call encoder "encode" [| inject (string value) |] +(* TODO: Verify this converts to bytes correctly? *) +external bytes_to_u8a : bytes -> 'a = "caml_array_of_bytes" -let make_decoder () = new_obj global ##. TextDecoder [||] - -let decode decoder u8a = to_string (meth_call decoder "decode" [| inject u8a |]) - -(* Uint8Array/Byte utilities *) -let u8a_to_bytes u8a = - let decoder = make_decoder () in - Bytes.of_string (decode decoder u8a) - -let bytes_to_u8a byts = - let encoder = make_encoder () in - encode encoder (Bytes.to_string byts) - -let string_to_u8a str = - let encoder = make_encoder () in - encode encoder str +external string_to_u8a : string -> 'a = "caml_array_of_string" type t @@ -108,7 +92,6 @@ let run_passes wasm_mod passes = let auto_drop wasm_mod = meth_call wasm_mod "autoDrop" [||] -(* TODO: This returns the wrong type, need to convert from `Uint8Array` to `bytes` *) let write wasm_mod sourcemap_url = match sourcemap_url with | Some url -> @@ -124,7 +107,6 @@ let write_text wasm_mod = let text = meth_call wasm_mod "emitText" [||] in to_string text -(* TODO: This doesn't handle `bytes` correctly *) let read byts = let data = bytes_to_u8a byts in meth_call global##.binaryen "readBinary" [| inject data |] diff --git a/js/stubs.c b/js/stubs.c new file mode 100644 index 0000000..927a34c --- /dev/null +++ b/js/stubs.c @@ -0,0 +1,15 @@ +// Ref https://github.com/ocsigen/js_of_ocaml/issues/804#issuecomment-495826520 +#include +#include +void caml_bytes_of_array () { + fprintf(stderr, "Unimplemented Javascript primitive caml_bytes_of_array!\n"); + exit(1); +} +void caml_array_of_bytes () { + fprintf(stderr, "Unimplemented Javascript primitive caml_array_of_bytes!\n"); + exit(1); +} +void caml_array_of_string () { + fprintf(stderr, "Unimplemented Javascript primitive caml_array_of_string!\n"); + exit(1); +}