add Bb_queue.to_{iter,gen,seq}

This commit is contained in:
Simon Cruanes 2023-09-12 23:07:04 -04:00
parent 2800a3e0a6
commit f90773a99a
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
2 changed files with 39 additions and 0 deletions

View file

@ -93,3 +93,26 @@ let size (self : _ t) : int =
let n = Queue.length self.q in
Mutex.unlock self.mutex;
n
type 'a gen = unit -> 'a option
type 'a iter = ('a -> unit) -> unit
let to_iter self k =
try
while true do
let x = pop self in
k x
done
with Closed -> ()
let to_gen self : _ gen =
fun () ->
match pop self with
| exception Closed -> None
| x -> Some x
let rec to_seq self : _ Seq.t =
fun () ->
match pop self with
| exception Closed -> Seq.Nil
| x -> Seq.Cons (x, to_seq self)

View file

@ -34,3 +34,19 @@ val try_push : 'a t -> 'a -> bool
val close : _ t -> unit
(** Close the queue, meaning there won't be any more [push] allowed. *)
type 'a gen = unit -> 'a option
type 'a iter = ('a -> unit) -> unit
val to_iter : 'a t -> 'a iter
(** [to_iter q] returns an iterator over all items in the queue.
This might not terminate if [q] is never closed.
@since NEXT_RELEASE *)
val to_gen : 'a t -> 'a gen
(** [to_gen q] returns a generator from the queue.
@since NEXT_RELEASE *)
val to_seq : 'a t -> 'a Seq.t
(** [to_gen q] returns a (transient) sequence from the queue.
@since NEXT_RELEASE *)