diff --git a/CHANGES.md b/CHANGES.md index afcad1d9..429f376f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -30,6 +30,7 @@ - Avoid copying unnecessarily large amounts of strings when parsing (#85, #108, @Leonidas-from-XIV) +- Fix `stream_to_file` (#133, @tcoopman and @gasche) ## 1.7.0 diff --git a/lib/write.ml b/lib/write.ml index 0e2090c9..16ebb987 100644 --- a/lib/write.ml +++ b/lib/write.ml @@ -489,7 +489,11 @@ let stream_to_channel ?buf ?(len=2096) ?std oc st = None -> Buffer.create len | Some ob -> ob in - stream_to_buffer ?std ob st + Stream.iter (fun json -> + to_buffer ?std ob json; + Buffer.output_buffer oc ob; + Buffer.clear ob; + ) st let stream_to_file ?len ?std file st = let oc = open_out file in diff --git a/test/test_write.ml b/test/test_write.ml index 6fad0706..9a9cd8d8 100644 --- a/test/test_write.ml +++ b/test/test_write.ml @@ -29,7 +29,24 @@ let to_file () = test ~newline:true (); test ~newline:false () +let stream_to_file () = + let output_file = Filename.temp_file "test_yojson_stream_to_file" ".json" in + let data = [`String "foo"; `String "bar"] in + Yojson.Safe.stream_to_file output_file (Stream.of_list data); + let read_data = + let stream = Yojson.Safe.stream_from_file output_file in + let acc = ref [] in + Stream.iter (fun v -> acc := v :: !acc) stream; + List.rev !acc + in + Sys.remove output_file; + if data <> read_data then + (* TODO: it would be nice to use Alcotest.check, + but we don't have a 'testable' instance for JSON values. *) + Alcotest.fail "stream_{to,from}_file roundtrip failure" + let single_json = [ "to_string", `Quick, to_string; "to_file", `Quick, to_file; + "stream_to_file", `Quick, stream_to_file; ]