diff --git a/src/bb_queue.ml b/src/bb_queue.ml index e8b8c485..67390c17 100644 --- a/src/bb_queue.ml +++ b/src/bb_queue.ml @@ -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) diff --git a/src/bb_queue.mli b/src/bb_queue.mli index 75ce1521..3d38456e 100644 --- a/src/bb_queue.mli +++ b/src/bb_queue.mli @@ -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 *)