Skip to content

Commit

Permalink
shifting shared logic to companion object
Browse files Browse the repository at this point in the history
  • Loading branch information
neomaclin committed Jan 6, 2024
1 parent 31a1d66 commit 6707156
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
4 changes: 2 additions & 2 deletions std/shared/src/main/scala/cats/effect/std/PQueue.scala
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ trait PQueueSource[F[_], A] extends QueueSource[F, A] {
* dequeued is undefined.
*/
override def tryTakeN(maxN: Option[Int])(implicit F: Monad[F]): F[List[A]] =
super.tryTakeN(maxN)
QueueSource.tryTakeN[F, A](maxN, tryTake)

}

Expand Down Expand Up @@ -265,7 +265,7 @@ trait PQueueSink[F[_], A] extends QueueSink[F, A] {
* an effect that contains the remaining valus that could not be offered.
*/
override def tryOfferN(list: List[A])(implicit F: Monad[F]): F[List[A]] =
super.tryOfferN(list)
QueueSink.tryOfferN(list, tryOffer)

}

Expand Down
29 changes: 20 additions & 9 deletions std/shared/src/main/scala/cats/effect/std/Queue.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1135,7 +1135,16 @@ trait QueueSource[F[_], A] {
* @return
* an effect that contains the dequeued elements
*/
def tryTakeN(maxN: Option[Int])(implicit F: Monad[F]): F[List[A]] = {
def tryTakeN(maxN: Option[Int])(implicit F: Monad[F]): F[List[A]] =
QueueSource.tryTakeN[F, A](maxN, tryTake)

def size: F[Int]
}

object QueueSource {

private[std] def tryTakeN[F[_], A](maxN: Option[Int], tryTake: F[Option[A]])(
implicit F: Monad[F]): F[List[A]] = {
QueueSource.assertMaxNPositive(maxN)

def loop(i: Int, limit: Int, acc: List[A]): F[List[A]] =
Expand All @@ -1153,10 +1162,6 @@ trait QueueSource[F[_], A] {
}
}

def size: F[Int]
}

object QueueSource {
private[std] def assertMaxNPositive(maxN: Option[Int]): Unit = maxN match {
case Some(n) if n <= 0 =>
throw new IllegalArgumentException(s"Provided maxN parameter must be positive, was $n")
Expand Down Expand Up @@ -1212,17 +1217,23 @@ trait QueueSink[F[_], A] {
* @return
* an effect that contains the remaining valus that could not be offered.
*/
def tryOfferN(list: List[A])(implicit F: Monad[F]): F[List[A]] = list match {
def tryOfferN(list: List[A])(implicit F: Monad[F]): F[List[A]] =
QueueSink.tryOfferN[F, A](list, tryOffer)

}

object QueueSink {

private[std] def tryOfferN[F[_], A](list: List[A], tryOffer: A => F[Boolean])(
implicit F: Monad[F]): F[List[A]] = list match {
case Nil => F.pure(list)
case h :: t =>
tryOffer(h).ifM(
tryOfferN(t),
tryOfferN(t, tryOffer),
F.pure(list)
)
}
}

object QueueSink {
implicit def catsContravariantForQueueSink[F[_]]: Contravariant[QueueSink[F, *]] =
new Contravariant[QueueSink[F, *]] {
override def contramap[A, B](fa: QueueSink[F, A])(f: B => A): QueueSink[F, B] =
Expand Down

0 comments on commit 6707156

Please sign in to comment.