feat: add Fut.make_promise, have 'a promise = private 'a fut

This commit is contained in:
Simon Cruanes 2024-10-18 12:52:21 -04:00
parent a143cc8489
commit 9a598b1efc
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
2 changed files with 17 additions and 6 deletions

View file

@ -6,12 +6,12 @@ type 'a waiter = 'a or_error -> unit
type 'a t = { st: 'a C.t } [@@unboxed]
type 'a promise = 'a t
let[@inline] make_ () : _ t =
let[@inline] make_promise () : _ t =
let fut = { st = C.create ~mode:`LIFO () } in
fut
let make () =
let fut = make_ () in
let fut = make_promise () in
fut, fut
let[@inline] return x : _ t = { st = C.returned x }
@ -99,7 +99,7 @@ let fulfill (self : _ t) (r : _ result) : unit =
(* ### combinators ### *)
let spawn ~on f : _ t =
let fut = make_ () in
let fut = make_promise () in
let task () =
try
@ -122,7 +122,7 @@ let reify_error (f : 'a t) : 'a or_error t =
match peek f with
| Some res -> return res
| None ->
let fut = make_ () in
let fut = make_promise () in
on_result f (fun r -> fulfill fut (Ok r));
fut

View file

@ -22,13 +22,24 @@ type 'a or_error = ('a, Exn_bt.t) result
type 'a t
(** A future with a result of type ['a]. *)
type 'a promise
type 'a promise = private 'a t
(** A promise, which can be fulfilled exactly once to set
the corresponding future *)
the corresponding future.
This is a private alias of ['a t] since NEXT_RELEASE, previously it was opaque. *)
val make : unit -> 'a t * 'a promise
(** Make a new future with the associated promise. *)
val make_promise : unit -> 'a promise
(** Same as {!make} but returns a single promise (which can be upcast to a
future). This is useful mostly to preserve memory.
How to upcast to a future:
{[let prom = Fut.make_promise();;
let fut: _ Fut.t = (prom :> _ Fut.t)
]}
@since NEXT_RELEASE *)
val on_result : 'a t -> ('a or_error -> unit) -> unit
(** [on_result fut f] registers [f] to be called in the future
when [fut] is set ;