I’m creating a terminal_io struct which has a large number of mutable fields. Before modifying them, I want to create a copy of the struct in order to be able to restore it later. Currently I’m making a duplicate call to Unix.tcgetattr:
let savedTio = Unix.tcgetattr Unix.stdin in
let tio = Unix.tcgetattr Unix.stdin in
I know you can create a copy with modified variables e.g. with:
let tio = Unix.tcgetattr Unix.stdin in
let savedTio = { tio with ... = ... } in
I thought that might be an option, but I was trying to avoid it as there’s 38 fields in this struct. I think I’ll stick with the existing approach of two syscalls.
module Make (X : sig type t end) : sig
val copy : X.t -> X.t
end = struct
let copy x : X.t = Obj.(obj (dup (repr x)))
end
let copy_my_struct =
let module M = Make (struct type t = my_struct end) in
M.copy
Obj.dup always performs a shallow copy. If you want a deep copy you can use Marshal to serialise and de-serialise, but I would advise to actually write the copy function yourself. It’s often not that much work and you can keep the sharing on the immutable parts (or the mutable parts you don’t need to duplicate).