Skip to content

Commit fc1857f

Browse files
committed
Convert directly to array
1 parent 23c3601 commit fc1857f

3 files changed

Lines changed: 25 additions & 1 deletion

File tree

ocaml/file_formats/cms_format.ml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ let save_cms filename modname binary_annots sourcefile initial_env shape =
120120
cms_source_digest = source_digest;
121121
cms_initial_env = if Cmt_format.need_to_clear_env
122122
then Env.keep_only_summary initial_env else initial_env;
123-
cms_uid_to_loc = cms_uid_to_loc |> Shape.Uid.Tbl.to_list |> Array.of_list;
123+
cms_uid_to_loc = cms_uid_to_loc |> Shape.Uid.Tbl.to_array;
124124
cms_uid_to_attributes;
125125
cms_impl_shape = shape;
126126
cms_ident_occurrences

ocaml/utils/identifiable.ml

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ module type Tbl = sig
8282
val of_map : 'a Map.Make(T).t -> 'a t
8383
val memoize : 'a t -> (key -> 'a) -> key -> 'a
8484
val map : 'a t -> ('a -> 'b) -> 'b t
85+
val to_array : 'a t -> (T.t * 'a) array
8586
end
8687

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

227228
let map t f =
228229
of_map (T_map.map f (to_map t))
230+
231+
let to_array t =
232+
let build_array key value acc =
233+
match acc with
234+
| None ->
235+
(* acc is None if we're on the first element. If this is the case, allocate the
236+
array, duplicating the first value for each entry *)
237+
let arr = Array.make (length t) (key, value) in
238+
Some (arr, 1)
239+
| Some (arr, i) ->
240+
(* If acc is Some, then the array has been allocated and we want to write the
241+
i-th value *)
242+
arr.(i) <- (key, value);
243+
Some (arr, i + 1)
244+
in
245+
let result = fold build_array t None in
246+
match result with
247+
| Some (arr, _) -> arr
248+
| None ->
249+
(* The result is None iff the map is empty, in which case we return an empty
250+
array *)
251+
[||]
229252
end
230253

231254
module type S = sig

ocaml/utils/identifiable.mli

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ module type Tbl = sig
9797
val of_map : 'a Map.Make(T).t -> 'a t
9898
val memoize : 'a t -> (key -> 'a) -> key -> 'a
9999
val map : 'a t -> ('a -> 'b) -> 'b t
100+
val to_array : 'a t -> (T.t * 'a) array
100101
end
101102

102103
module type S = sig

0 commit comments

Comments
 (0)