From 9a598b1efcd2bc2e9e373e09c338b7b06f9ef789 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Fri, 18 Oct 2024 12:52:21 -0400 Subject: [PATCH] feat: add `Fut.make_promise`, have `'a promise = private 'a fut` --- src/core/fut.ml | 8 ++++---- src/core/fut.mli | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/core/fut.ml b/src/core/fut.ml index 58b6e443..847a1156 100644 --- a/src/core/fut.ml +++ b/src/core/fut.ml @@ -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 diff --git a/src/core/fut.mli b/src/core/fut.mli index bd0ee0dd..03e3c728 100644 --- a/src/core/fut.mli +++ b/src/core/fut.mli @@ -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 ;