Make unix representation more efficient

By not allocation a closure on every update
This commit is contained in:
Rudi Grinberg 2018-03-12 09:52:52 +07:00
parent e604c69510
commit 26d6b03c66
1 changed files with 26 additions and 21 deletions

View File

@ -15,31 +15,13 @@ module Map = Map.Make(Var)
type t =
{ base : string array
; extra : string Map.t
; combined : string array Lazy.t
; mutable unix : string array option
}
let make ~base ~extra =
{ base
; extra
; combined = lazy (
if Map.is_empty extra then
base
else
let imported =
Array.to_list base
|> List.filter ~f:(fun s ->
match String.index s '=' with
| None -> true
| Some i ->
let key = String.sub s ~pos:0 ~len:i in
not (Map.mem extra key))
in
List.rev_append
(List.map (Map.to_list extra)
~f:(fun (k, v) -> sprintf "%s=%s" k v))
imported
|> Array.of_list
)
; unix = None
}
let get_env_base env var =
@ -60,7 +42,30 @@ let get t v =
| None -> get_env_base t.base v
| Some _ as v -> v
let to_unix t = Lazy.force t.combined
let to_unix t =
match t.unix with
| Some v -> v
| None ->
let res =
if Map.is_empty t.extra then
t.base
else
let imported =
Array.to_list t.base
|> List.filter ~f:(fun s ->
match String.index s '=' with
| None -> true
| Some i ->
let key = String.sub s ~pos:0 ~len:i in
not (Map.mem t.extra key))
in
List.rev_append
(List.map (Map.to_list t.extra)
~f:(fun (k, v) -> sprintf "%s=%s" k v))
imported
|> Array.of_list in
t.unix <- Some res;
res
let initial =
let i =