Skip to content

Commit

Permalink
Convert directly to array
Browse files Browse the repository at this point in the history
  • Loading branch information
liam923 committed Aug 5, 2024
1 parent 23c3601 commit fc1857f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion ocaml/file_formats/cms_format.ml
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ let save_cms filename modname binary_annots sourcefile initial_env shape =
cms_source_digest = source_digest;
cms_initial_env = if Cmt_format.need_to_clear_env
then Env.keep_only_summary initial_env else initial_env;
cms_uid_to_loc = cms_uid_to_loc |> Shape.Uid.Tbl.to_list |> Array.of_list;
cms_uid_to_loc = cms_uid_to_loc |> Shape.Uid.Tbl.to_array;
cms_uid_to_attributes;
cms_impl_shape = shape;
cms_ident_occurrences
Expand Down
23 changes: 23 additions & 0 deletions ocaml/utils/identifiable.ml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ module type Tbl = sig
val of_map : 'a Map.Make(T).t -> 'a t
val memoize : 'a t -> (key -> 'a) -> key -> 'a
val map : 'a t -> ('a -> 'b) -> 'b t
val to_array : 'a t -> (T.t * 'a) array
end

module Pair (A : Thing) (B : Thing) : Thing with type t = A.t * B.t = struct
Expand Down Expand Up @@ -226,6 +227,28 @@ module Make_tbl (T : Thing) = struct

let map t f =
of_map (T_map.map f (to_map t))

let to_array t =
let build_array key value acc =
match acc with
| None ->
(* acc is None if we're on the first element. If this is the case, allocate the
array, duplicating the first value for each entry *)
let arr = Array.make (length t) (key, value) in
Some (arr, 1)
| Some (arr, i) ->
(* If acc is Some, then the array has been allocated and we want to write the
i-th value *)
arr.(i) <- (key, value);
Some (arr, i + 1)
in
let result = fold build_array t None in
match result with
| Some (arr, _) -> arr
| None ->
(* The result is None iff the map is empty, in which case we return an empty
array *)
[||]
end

module type S = sig
Expand Down
1 change: 1 addition & 0 deletions ocaml/utils/identifiable.mli
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ module type Tbl = sig
val of_map : 'a Map.Make(T).t -> 'a t
val memoize : 'a t -> (key -> 'a) -> key -> 'a
val map : 'a t -> ('a -> 'b) -> 'b t
val to_array : 'a t -> (T.t * 'a) array
end

module type S = sig
Expand Down

0 comments on commit fc1857f

Please sign in to comment.