Skip to content

Commit

Permalink
CR
Browse files Browse the repository at this point in the history
  • Loading branch information
hhugo committed Aug 24, 2024
1 parent ca5c991 commit 01f74af
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 23 deletions.
4 changes: 3 additions & 1 deletion lib/js_of_ocaml/json.ml
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,10 @@ let use_native_stringify () = !use_native_stringify_

let set_use_native_stringify b = use_native_stringify_ := b

let output_ x = to_json (Obj.repr x)

let output obj =
match Sys.backend_type with
| Other "js_of_ocaml" when use_native_stringify () ->
json##stringify_ obj (Js.wrap_callback output_reviver)
| _ -> Js.string (to_json (Obj.repr obj))
| _ -> Js.string (output_ obj)
4 changes: 4 additions & 0 deletions lib/js_of_ocaml/json.mli
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ val unsafe_input : Js.js_string Js.t -> 'a
(** Unmarshal a string in JSON format as an OCaml value (unsafe but
fast !). *)

(**/**)

val output_ : 'a -> string

val set_use_native_stringify : bool -> unit
(** Only affects js_of_ocaml. Whether to use native Javascript [stringify] to
turn a value into JSON in {!val:output}. Otherwise, fall back to the slower
Expand Down
50 changes: 28 additions & 22 deletions lib/tests/test_json.ml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,16 @@ open Js_of_ocaml

let round_trip x =
let s = Json.output x in
Printf.printf "%s\n" (Js.to_bytestring s);
let s1 = Js.to_bytestring s in
let s2 =
let old = Json.use_native_stringify () in
Json.set_use_native_stringify false;
let s = Json.output x in
Json.set_use_native_stringify old;
Js.to_bytestring s
in
Printf.printf "%s\n" s1;
if s1 <> s2 then Printf.printf "Json.output mismatch: %s vs %s\n" s1 s2;
(* Other direction of the round-trip (unmarshalling from JSON) is only
available with js_of_ocaml *)
match Sys.backend_type with
Expand All @@ -32,26 +41,23 @@ let round_trip x =
| _ -> ()

let%expect_test _ =
let tests ~use_native_stringify =
let () = Json.set_use_native_stringify use_native_stringify in
round_trip 123L;
[%expect {|
round_trip 123L;
[%expect {|
[255,123,0,0] |}];
round_trip "asd";
[%expect {|
round_trip "asd";
[%expect {|
"asd" |}];
round_trip "\000\255\254";
[%expect {|
"\u0000ÿþ" |}];
round_trip (2, 3);
round_trip (2., 3.);
round_trip (2.2, 3.3);
[%expect {|
[0,2,3]
[0,2,3]
[0,2.2,3.3] |}]
in
tests ~use_native_stringify:false;
match Sys.backend_type with
| Other "js_of_ocaml" -> tests ~use_native_stringify:true
| _ -> ()
round_trip "\000\255\254";
[%expect {| "\u0000ÿþ" |}];
round_trip (2, 3);
round_trip (2., 3.);
round_trip (2.2, 3.3);
[%expect {|
[0,2,3]
[0,2,3]
[0,2.2,3.3]
|}];
round_trip [| 1.; 2.; 3. |];
[%expect {| [254,1,2,3] |}];
round_trip 2n;
[%expect {| 2 |}]

0 comments on commit 01f74af

Please sign in to comment.