Skip to content

Commit

Permalink
Always binary when reading marshalled AST
Browse files Browse the repository at this point in the history
+ Document assumptions in [with_output] using binary mode.

+ Remove unneeded changes in print_magic_number.ml.

Signed-off-by: Jonah Beckford <[email protected]>
  • Loading branch information
jonahbeckford committed Jan 30, 2024
1 parent cd8d6f6 commit b0e2367
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
13 changes: 13 additions & 0 deletions src/utils.ml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ open Import
let with_output fn ~binary ~f =
match fn with
| None | Some "-" ->
(* Flipping back and forth from binary to text is not
a good idea, so we'll make two simplifying assumptions:
1. Assume that nothing is buffered on stdout before
entering [with_output]. That means we don't need to
flush the stdout on entry.
2. Assume that nothing else is sent to stdout after
[with_output]. That means it is safe to leave stdout
channel in binary mode (or text mode if [binary=true])
after the function is done. *)
set_binary_mode_out stdout binary;
f stdout
| Some fn -> Out_channel.with_file fn ~binary ~f
Expand Down Expand Up @@ -114,6 +123,10 @@ module Ast_io = struct
parse_source_code ~kind ~input_name ~prefix_read_from_source ch
| Necessarily_binary -> Error Not_a_binary_ast
in
(* Marshalled AST must be read in binary mode. Even though we don't know
before reading the magic number when the file has a marshalled AST,
it is safe to read source files in binary mode. *)
set_binary_mode_in ch true;
match read_magic ch with
| Error s -> handle_non_binary s
| Ok s -> (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
let magic_length = String.length Astlib.Config.ast_impl_magic_number
let buf = Bytes.create magic_length

let len =
set_binary_mode_in stdin true;
input stdin buf 0 magic_length

let len = input stdin buf 0 magic_length
let s = Bytes.sub_string buf 0 len
let () = Printf.printf "Magic number: %s" s

0 comments on commit b0e2367

Please sign in to comment.