Skip to content

Commit 43f82d7

Browse files
committed
feat(Ref): add protect function
1 parent d535cfe commit 43f82d7

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/core/CCRef.ml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,17 @@ let swap a b =
3232
a := !b;
3333
b := x
3434

35+
let protect r x f =
36+
let old = !r in
37+
r := x;
38+
try
39+
let res = f () in
40+
r := old;
41+
res
42+
with e ->
43+
r := old;
44+
raise e
45+
3546
let to_list r = [ !r ]
3647
let to_iter r yield = yield !r
3748
let pp pp_x out r = pp_x out !r

src/core/CCRef.mli

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ val swap : 'a t -> 'a t -> unit
3333
(** [swap t1 t2] puts [!t2] in [t1] and [!t1] in [t2].
3434
@since 1.4 *)
3535

36+
val protect : 'a t -> 'a -> (unit -> 'b) -> 'b
37+
(** [protect r x f] sets [r := x]; calls [f()]; restores [r] to its old value;
38+
and returns the result of [f()].
39+
@since NEXT_RELEASE *)
40+
3641
val compare : 'a ord -> 'a t ord
3742
val equal : 'a eq -> 'a t eq
3843
val to_list : 'a t -> 'a list

0 commit comments

Comments
 (0)