11package fs2 .async .mutable
22
33import fs2 ._
4-
4+ import fs2 . util . Functor
55import fs2 .async .immutable
66
77/**
@@ -10,7 +10,7 @@ import fs2.async.immutable
1010 * a queue may have a bound on its size, in which case enqueuing may
1111 * block until there is an offsetting dequeue.
1212 */
13- trait Queue [F [_],A ] {
13+ trait Queue [F [_],A ] { self =>
1414
1515 /**
1616 * Enqueues one element in this `Queue`.
@@ -40,17 +40,17 @@ trait Queue[F[_],A] {
4040 def dequeue1 : F [A ]
4141
4242 /** Like `dequeue1` but provides a way to cancel the dequeue. */
43- def cancellableDequeue1 : F [(F [A ],F [Unit ])]
43+ def cancellableDequeue1 : F [(F [A ], F [Unit ])]
4444
4545 /** Repeatedly call `dequeue1` forever. */
46- def dequeue : Stream [F ,A ] = Stream .bracket(cancellableDequeue1)(d => Stream .eval(d._1), d => d._2).repeat
46+ def dequeue : Stream [F , A ] = Stream .bracket(cancellableDequeue1)(d => Stream .eval(d._1), d => d._2).repeat
4747
4848 /**
4949 * The time-varying size of this `Queue`. This signal refreshes
5050 * only when size changes. Offsetting enqueues and de-queues may
5151 * not result in refreshes.
5252 */
53- def size : immutable.Signal [F ,Int ]
53+ def size : immutable.Signal [F , Int ]
5454
5555 /** The size bound on the queue. `None` if the queue is unbounded. */
5656 def upperBound : Option [Int ]
@@ -59,13 +59,30 @@ trait Queue[F[_],A] {
5959 * Returns the available number of entries in the queue.
6060 * Always `Int.MaxValue` when the queue is unbounded.
6161 */
62- def available : immutable.Signal [F ,Int ]
62+ def available : immutable.Signal [F , Int ]
6363
6464 /**
6565 * Returns `true` when the queue has reached its upper size bound.
6666 * Always `false` when the queue is unbounded.
6767 */
68- def full : immutable.Signal [F ,Boolean ]
68+ def full : immutable.Signal [F , Boolean ]
69+
70+ /**
71+ * Returns an alternate view of this `Queue` where its elements are of type [[B ]],
72+ * given back and forth function from `A` to `B`.
73+ */
74+ def imap [B ](f : A => B )(g : B => A )(implicit F : Functor [F ]): Queue [F , B ] =
75+ new Queue [F , B ] {
76+ def available : immutable.Signal [F , Int ] = self.available
77+ def full : immutable.Signal [F , Boolean ] = self.full
78+ def size : immutable.Signal [F , Int ] = self.size
79+ def upperBound : Option [Int ] = self.upperBound
80+ def enqueue1 (a : B ): F [Unit ] = self.enqueue1(g(a))
81+ def offer1 (a : B ): F [Boolean ] = self.offer1(g(a))
82+ def dequeue1 : F [B ] = F .map(self.dequeue1)(f)
83+ def cancellableDequeue1 : F [(F [B ],F [Unit ])] =
84+ F .map(self.cancellableDequeue1)(bu => F .map(bu._1)(f) -> bu._2)
85+ }
6986}
7087
7188object Queue {
0 commit comments