Skip to content

Commit

Permalink
fix(js): utilize JSOO externals to convert between uint8array & bytes (
Browse files Browse the repository at this point in the history
  • Loading branch information
phated committed Mar 16, 2021
1 parent 0d2fcde commit 61d28c5
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 22 deletions.
3 changes: 3 additions & 0 deletions js/dune
Expand Up @@ -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)))
Expand Down
26 changes: 4 additions & 22 deletions 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

Expand Down Expand Up @@ -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 ->
Expand All @@ -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 |]
Expand Down
15 changes: 15 additions & 0 deletions js/stubs.c
@@ -0,0 +1,15 @@
// Ref https://github.com/ocsigen/js_of_ocaml/issues/804#issuecomment-495826520
#include <stdlib.h>
#include <stdio.h>
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);
}

0 comments on commit 61d28c5

Please sign in to comment.