diff --git a/.scalafmt.conf b/.scalafmt.conf index de98a494a059..7f9696e5cd53 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,4 +1,4 @@ -version = "2.1.0" +version = "2.3.2" maxColumn = 120 align = most continuationIndent.defnSite = 2 diff --git a/benchmarks/src/main/scala/zio/IODeepAttemptBenchmark.scala b/benchmarks/src/main/scala/zio/IODeepAttemptBenchmark.scala index 91fdabcf2fe4..7b8a6bc32a00 100644 --- a/benchmarks/src/main/scala/zio/IODeepAttemptBenchmark.scala +++ b/benchmarks/src/main/scala/zio/IODeepAttemptBenchmark.scala @@ -35,7 +35,8 @@ class IODeepAttemptBenchmark { def descend(n: Int): Future[BigInt] = if (n == depth) Future.failed(new Exception("Oh noes!")) - else if (n == halfway) descend(n + 1).recover { case _ => 50 } else descend(n + 1).map(_ + n) + else if (n == halfway) descend(n + 1).recover { case _ => 50 } + else descend(n + 1).map(_ + n) Await.result(descend(0), Inf) } @@ -97,7 +98,8 @@ class IODeepAttemptBenchmark { if (n == depth) Future.exception(new Error("Oh noes!")) else if (n == halfway) - descent(n + 1).handle { case _ => 50 } else descent(n + 1).map(_ + n) + descent(n + 1).handle { case _ => 50 } + else descent(n + 1).map(_ + n) Await.result(descent(0)) } diff --git a/benchmarks/src/main/scala/zio/IOShallowAttemptBenchmark.scala b/benchmarks/src/main/scala/zio/IOShallowAttemptBenchmark.scala index 15e18dd50099..0f2bb096e1e4 100644 --- a/benchmarks/src/main/scala/zio/IOShallowAttemptBenchmark.scala +++ b/benchmarks/src/main/scala/zio/IOShallowAttemptBenchmark.scala @@ -33,7 +33,8 @@ class IOShallowAttemptBenchmark { import scala.concurrent.duration.Duration.Inf def throwup(n: Int): Future[BigInt] = - if (n == 0) throwup(n + 1) recover { case _ => 0 } else if (n == depth) Future(1) + if (n == 0) throwup(n + 1) recover { case _ => 0 } + else if (n == depth) Future(1) else throwup(n + 1).recover { case _ => 0 } .flatMap(_ => Future.failed(new Exception("Oh noes!"))) @@ -51,11 +52,11 @@ class IOShallowAttemptBenchmark { else throwup(n + 1) .exceptionally(_ => 0) - .thenCompose(_ => { + .thenCompose { _ => val f = new CompletableFuture[BigInt]() f.completeExceptionally(new Exception("Oh noes!")) f - }) + } throwup(0) .get() @@ -101,7 +102,8 @@ class IOShallowAttemptBenchmark { def throwup(n: Int): Future[BigInt] = if (n == 0) throwup(n + 1).rescue { case _ => Future.value(0) - } else if (n == depth) Future(1) + } + else if (n == depth) Future(1) else throwup(n + 1).transform { case Throw(_) => Future.value[BigInt](0) diff --git a/core-tests/jvm/src/test/scala-2.12/zio/StacktracesSpec.scala b/core-tests/jvm/src/test/scala-2.12/zio/StacktracesSpec.scala index 4e2298069791..41673fba501f 100644 --- a/core-tests/jvm/src/test/scala-2.12/zio/StacktracesSpec.scala +++ b/core-tests/jvm/src/test/scala-2.12/zio/StacktracesSpec.scala @@ -393,10 +393,9 @@ object StackTracesSpec extends DefaultRunnableSpec { _ <- ZIO.unit _ <- ZIO.unit } yield t) - .flatMap( - t => - IO.trace - .map(tuple(t)) + .flatMap(t => + IO.trace + .map(tuple(t)) ) } diff --git a/core-tests/jvm/src/test/scala/zio/RTSSpec.scala b/core-tests/jvm/src/test/scala/zio/RTSSpec.scala index 111760ce4b54..fd44bf61ad52 100644 --- a/core-tests/jvm/src/test/scala/zio/RTSSpec.scala +++ b/core-tests/jvm/src/test/scala/zio/RTSSpec.scala @@ -82,10 +82,9 @@ object RTSSpec extends ZIOBaseSpec { exitLatch <- Promise.make[Nothing, Int] bracketed = IO .succeed(21) - .bracketExit( - (r: Int, exit: Exit[Any, Any]) => - if (exit.interrupted) exitLatch.succeed(r) - else IO.die(new Error("Unexpected case")) + .bracketExit((r: Int, exit: Exit[Any, Any]) => + if (exit.interrupted) exitLatch.succeed(r) + else IO.die(new Error("Unexpected case")) )(a => startLatch.succeed(a) *> IO.never *> IO.succeed(1)) fiber <- bracketed.fork startValue <- startLatch.await diff --git a/core-tests/shared/src/test/scala/zio/FunctionIOSpec.scala b/core-tests/shared/src/test/scala/zio/FunctionIOSpec.scala index 06edb154fb91..23431aac9731 100644 --- a/core-tests/shared/src/test/scala/zio/FunctionIOSpec.scala +++ b/core-tests/shared/src/test/scala/zio/FunctionIOSpec.scala @@ -127,7 +127,5 @@ object FunctionIOSpec extends ZIOBaseSpec { val greaterThan0 = fromFunction[Int, Boolean](_ > 0) val lessThan10 = fromFunction[Int, Boolean](_ < 10) - val thrower = effect[String, Int, Int] { case _: Throwable => "error" }( - _ => throw new Exception - ) + val thrower = effect[String, Int, Int] { case _: Throwable => "error" }(_ => throw new Exception) } diff --git a/core-tests/shared/src/test/scala/zio/ScheduleSpec.scala b/core-tests/shared/src/test/scala/zio/ScheduleSpec.scala index f8e8d9f94725..ec1d917eea26 100644 --- a/core-tests/shared/src/test/scala/zio/ScheduleSpec.scala +++ b/core-tests/shared/src/test/scala/zio/ScheduleSpec.scala @@ -297,9 +297,7 @@ object ScheduleSpec extends ZIOBaseSpec { ok => ZIO.succeed(Right(ScheduleSuccess(ok))) ) .retry(Schedule.spaced(2.seconds) && Schedule.recurs(1)) - .catchAll( - error => ZIO.succeed(Left(ScheduleFailure(error.message))) - ) + .catchAll(error => ZIO.succeed(Left(ScheduleFailure(error.message)))) val expected = Right(ScheduleSuccess("Ok")) assertM(foo("Ok"))(equalTo(expected)) diff --git a/core-tests/shared/src/test/scala/zio/SemaphoreSpec.scala b/core-tests/shared/src/test/scala/zio/SemaphoreSpec.scala index 2cae174a6f8d..34eedfe1a415 100644 --- a/core-tests/shared/src/test/scala/zio/SemaphoreSpec.scala +++ b/core-tests/shared/src/test/scala/zio/SemaphoreSpec.scala @@ -25,14 +25,10 @@ object SemaphoreSpec extends ZIOBaseSpec { } yield assert(available)(forall(isLessThan(20L))) }, testM("`acquireN`s can be parallel with `releaseN`s") { - offsettingWithPermits( - (s, permits) => IO.foreach(permits)(s.withPermits(_)(IO.unit)).unit - ) + offsettingWithPermits((s, permits) => IO.foreach(permits)(s.withPermits(_)(IO.unit)).unit) }, testM("individual `acquireN`s can be parallel with individual `releaseN`s") { - offsettingWithPermits( - (s, permits) => IO.foreachPar(permits)(s.withPermits(_)(IO.unit)).unit - ) + offsettingWithPermits((s, permits) => IO.foreachPar(permits)(s.withPermits(_)(IO.unit)).unit) }, testM("semaphores and fibers play ball together") { val n = 1L diff --git a/core-tests/shared/src/test/scala/zio/ZIOSpec.scala b/core-tests/shared/src/test/scala/zio/ZIOSpec.scala index 66ae7d2a3cc3..89cd8a308b83 100644 --- a/core-tests/shared/src/test/scala/zio/ZIOSpec.scala +++ b/core-tests/shared/src/test/scala/zio/ZIOSpec.scala @@ -1566,8 +1566,8 @@ object ZIOSpec extends ZIOBaseSpec { log = makeLogger(ref) f <- ZIO .bracket( - ZIO.bracket(ZIO.unit)(_ => log("start 1") *> clock.sleep(10.millis) *> log("release 1"))( - _ => ZIO.unit + ZIO.bracket(ZIO.unit)(_ => log("start 1") *> clock.sleep(10.millis) *> log("release 1"))(_ => + ZIO.unit ) )(_ => log("start 2") *> clock.sleep(10.millis) *> log("release 2"))(_ => ZIO.unit) .fork @@ -2116,9 +2116,7 @@ object ZIOSpec extends ZIOBaseSpec { for { promise <- Promise.make[Nothing, Unit] fiber <- IO - .bracketExit(promise.succeed(()) *> IO.never *> IO.succeed(1))( - (_, _: Exit[Any, Any]) => IO.unit - )( + .bracketExit(promise.succeed(()) *> IO.never *> IO.succeed(1))((_, _: Exit[Any, Any]) => IO.unit)( _ => IO.unit: IO[Nothing, Unit] ) .fork @@ -2156,10 +2154,7 @@ object ZIOSpec extends ZIOBaseSpec { for { done <- Promise.make[Nothing, Unit] fiber <- withLatch { release => - IO.bracketExit(IO.unit)((_, _: Exit[Any, Any]) => done.succeed(()))( - _ => release *> IO.never - ) - .fork + IO.bracketExit(IO.unit)((_, _: Exit[Any, Any]) => done.succeed(()))(_ => release *> IO.never).fork } _ <- fiber.interrupt @@ -2185,8 +2180,8 @@ object ZIOSpec extends ZIOBaseSpec { p2 <- Promise.make[Nothing, Unit] p3 <- Promise.make[Nothing, Unit] s <- IO - .bracketForkExit(p1.succeed(()) *> p2.await)((_, _: Exit[Any, Any]) => p3.await)( - _ => IO.unit: IO[Nothing, Unit] + .bracketForkExit(p1.succeed(()) *> p2.await)((_, _: Exit[Any, Any]) => p3.await)(_ => + IO.unit: IO[Nothing, Unit] ) .fork _ <- p1.await @@ -2223,9 +2218,7 @@ object ZIOSpec extends ZIOBaseSpec { for { done <- Promise.make[Nothing, Unit] fiber <- withLatch { release => - IO.bracketForkExit(IO.unit)((_, _: Exit[Any, Any]) => done.succeed(()))( - _ => release *> IO.never - ) + IO.bracketForkExit(IO.unit)((_, _: Exit[Any, Any]) => done.succeed(()))(_ => release *> IO.never) .fork } @@ -2504,8 +2497,8 @@ object ZIOSpec extends ZIOBaseSpec { for { ref <- Ref.make(Option.empty[internal.Executor]) exec = internal.Executor.fromExecutionContext(100)(scala.concurrent.ExecutionContext.Implicits.global) - _ <- withLatch( - release => IO.descriptor.map(_.executor).flatMap(e => ref.set(Some(e)) *> release).fork.lock(exec) + _ <- withLatch(release => + IO.descriptor.map(_.executor).flatMap(e => ref.set(Some(e)) *> release).fork.lock(exec) ) v <- ref.get } yield v.contains(exec) diff --git a/core-tests/shared/src/test/scala/zio/ZManagedSpec.scala b/core-tests/shared/src/test/scala/zio/ZManagedSpec.scala index 10631aae4836..bc997a44fdfe 100644 --- a/core-tests/shared/src/test/scala/zio/ZManagedSpec.scala +++ b/core-tests/shared/src/test/scala/zio/ZManagedSpec.scala @@ -1310,12 +1310,10 @@ object ZManagedSpec extends ZIOBaseSpec { effects <- Ref.make(0) countDown <- countDownLatch(n + 1) reserveLatch <- Promise.make[Nothing, Unit] - baseRes = ZManaged.make(effects.update(_ + 1) *> countDown *> reserveLatch.await)( - _ => ZIO.unit - ) - res = f(baseRes) - _ <- res.use_(ZIO.unit).fork *> countDown - count <- effects.get - _ <- reserveLatch.succeed(()) + baseRes = ZManaged.make(effects.update(_ + 1) *> countDown *> reserveLatch.await)(_ => ZIO.unit) + res = f(baseRes) + _ <- res.use_(ZIO.unit).fork *> countDown + count <- effects.get + _ <- reserveLatch.succeed(()) } yield assert(count)(equalTo(n)) } diff --git a/core-tests/shared/src/test/scala/zio/stm/ZSTMSpec.scala b/core-tests/shared/src/test/scala/zio/stm/ZSTMSpec.scala index b05937a9d276..1633045a9643 100644 --- a/core-tests/shared/src/test/scala/zio/stm/ZSTMSpec.scala +++ b/core-tests/shared/src/test/scala/zio/stm/ZSTMSpec.scala @@ -228,13 +228,12 @@ object ZSTMSpec extends ZIOBaseSpec { for { tvar <- TRef.makeCommit(0) fiber <- IO.forkAll( - (0 to 20).map( - i => - (for { - v <- tvar.get - _ <- STM.check(v == i) - _ <- tvar.update(_ + 1) - } yield ()).commit + (0 to 20).map(i => + (for { + v <- tvar.get + _ <- STM.check(v == i) + _ <- tvar.update(_ + 1) + } yield ()).commit ) ) _ <- fiber.join diff --git a/core/shared/src/main/scala/zio/Chunk.scala b/core/shared/src/main/scala/zio/Chunk.scala index a03404060a2a..0be7c58ed863 100644 --- a/core/shared/src/main/scala/zio/Chunk.scala +++ b/core/shared/src/main/scala/zio/Chunk.scala @@ -637,10 +637,9 @@ sealed trait Chunk[+A] { self => i += 1 } - array.map( - array => - if (array == null) Chunk.empty - else Chunk.fromArray(array) + array.map(array => + if (array == null) Chunk.empty + else Chunk.fromArray(array) ) } @@ -942,10 +941,9 @@ object Chunk { i += 1 } - dest.map( - array => - if (array == null) Chunk.empty - else Chunk.Slice(Chunk.Arr(array), 0, j) + dest.map(array => + if (array == null) Chunk.empty + else Chunk.Slice(Chunk.Arr(array), 0, j) ) } @@ -1012,10 +1010,9 @@ object Chunk { i += 1 } - dest.map( - array => - if (array == null) Chunk.empty - else Chunk.Slice(Chunk.Arr(array), 0, j) + dest.map(array => + if (array == null) Chunk.empty + else Chunk.Slice(Chunk.Arr(array), 0, j) ) } diff --git a/core/shared/src/main/scala/zio/FunctionIO.scala b/core/shared/src/main/scala/zio/FunctionIO.scala index 54898dc4876f..f23e2158b3e1 100644 --- a/core/shared/src/main/scala/zio/FunctionIO.scala +++ b/core/shared/src/main/scala/zio/FunctionIO.scala @@ -341,8 +341,8 @@ object FunctionIO extends Serializable { case _ => lazy val loop: FunctionIO[E, A, A] = - FunctionIO.fromFunctionM( - (a: A) => check.run(a).flatMap((b: Boolean) => if (b) body.run(a).flatMap(loop.run) else IO.succeed(a)) + FunctionIO.fromFunctionM((a: A) => + check.run(a).flatMap((b: Boolean) => if (b) body.run(a).flatMap(loop.run) else IO.succeed(a)) ) loop @@ -394,12 +394,11 @@ object FunctionIO extends Serializable { }) case _ => - FunctionIO.fromFunctionM( - (a: A) => - for { - b <- l.run(a) - c <- r.run(a) - } yield f(b, c) + FunctionIO.fromFunctionM((a: A) => + for { + b <- l.run(a) + c <- r.run(a) + } yield f(b, c) ) } diff --git a/core/shared/src/main/scala/zio/Schedule.scala b/core/shared/src/main/scala/zio/Schedule.scala index e757ac2e5dd8..4cad062270cc 100644 --- a/core/shared/src/main/scala/zio/Schedule.scala +++ b/core/shared/src/main/scala/zio/Schedule.scala @@ -176,14 +176,13 @@ trait Schedule[-R, -A, +B] extends Serializable { self => * Returns a new schedule with the effectfully calculated delay added to every update. */ final def addDelayM[R1 <: R](f: B => ZIO[R1, Nothing, Duration]): Schedule[R1 with Clock, A, B] = - updated( - update => - (a, s) => - for { - delay <- f(extract(a, s)) - s1 <- update(a, s) - _ <- ZIO.sleep(delay) - } yield s1 + updated(update => + (a, s) => + for { + delay <- f(extract(a, s)) + s1 <- update(a, s) + _ <- ZIO.sleep(delay) + } yield s1 ) /** @@ -233,13 +232,12 @@ trait Schedule[-R, -A, +B] extends Serializable { self => * then continues the schedule or not based on the specified state predicate. */ final def check[A1 <: A](test: (A1, B) => UIO[Boolean]): Schedule[R, A1, B] = - updated( - update => - (a, s) => - test(a, self.extract(a, s)).flatMap { - case false => ZIO.fail(()) - case true => update(a, s) - } + updated(update => + (a, s) => + test(a, self.extract(a, s)).flatMap { + case false => ZIO.fail(()) + case true => update(a, s) + } ) /** @@ -450,13 +448,12 @@ trait Schedule[-R, -A, +B] extends Serializable { self => * that log failures, decisions, or computed values. */ final def onDecision[A1 <: A, R1 <: R](f: (A1, Option[self.State]) => URIO[R1, Any]): Schedule[R1, A1, B] = - updated( - update => - (a, s) => - update(a, s).tapBoth( - _ => f(a, None), - state => f(a, Some(state)) - ) + updated(update => + (a, s) => + update(a, s).tapBoth( + _ => f(a, None), + state => f(a, Some(state)) + ) ) /** @@ -485,13 +482,12 @@ trait Schedule[-R, -A, +B] extends Serializable { self => final def reconsider[R1 <: R, A1 <: A]( f: (A1, Either[State, State]) => ZIO[R1, Unit, State] ): Schedule[R1, A1, B] = - updated( - update => - (a: A1, s: State) => - update(a, s).foldM( - _ => f(a, Left(s)), - s1 => f(a, Right(s1)) - ) + updated(update => + (a: A1, s: State) => + update(a, s).foldM( + _ => f(a, Left(s)), + s1 => f(a, Right(s1)) + ) ) /** @@ -554,13 +550,12 @@ trait Schedule[-R, -A, +B] extends Serializable { self => * is satisfied on the input of the schedule. */ final def untilInputM[A1 <: A](f: A1 => UIO[Boolean]): Schedule[R, A1, B] = - updated( - update => - (a, s) => - f(a).flatMap { - case true => ZIO.fail(()) - case false => update(a, s) - } + updated(update => + (a, s) => + f(a).flatMap { + case true => ZIO.fail(()) + case false => update(a, s) + } ) /** @@ -574,13 +569,12 @@ trait Schedule[-R, -A, +B] extends Serializable { self => * is satisfied on the output value of the schedule. */ final def untilOutputM(f: B => UIO[Boolean]): Schedule[R, A, B] = - updated( - update => - (a, s) => - f(self.extract(a, s)).flatMap { - case true => ZIO.fail(()) - case false => update(a, s) - } + updated(update => + (a, s) => + f(self.extract(a, s)).flatMap { + case true => ZIO.fail(()) + case false => update(a, s) + } ) /** diff --git a/core/shared/src/main/scala/zio/Semaphore.scala b/core/shared/src/main/scala/zio/Semaphore.scala index b863e64f5947..8ea7f48a9915 100644 --- a/core/shared/src/main/scala/zio/Semaphore.scala +++ b/core/shared/src/main/scala/zio/Semaphore.scala @@ -58,9 +58,7 @@ final class Semaphore private (private val state: Ref[State]) extends Serializab * Acquires `n` permits, executes the action and releases the permits right after. */ def withPermits[R, E, A](n: Long)(task: ZIO[R, E, A]): ZIO[R, E, A] = - prepare(n).bracket( - e => e.release - )(r => r.awaitAcquire *> task) + prepare(n).bracket(e => e.release)(r => r.awaitAcquire *> task) /** * Acquires `n` permits in a [[zio.ZManaged]] and releases the permits in the finalizer. diff --git a/core/shared/src/main/scala/zio/ZIO.scala b/core/shared/src/main/scala/zio/ZIO.scala index 41a5ed98c018..60ea391557fd 100644 --- a/core/shared/src/main/scala/zio/ZIO.scala +++ b/core/shared/src/main/scala/zio/ZIO.scala @@ -167,12 +167,11 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self => final def bracketOnError[R1 <: R, E1 >: E, B]( release: A => URIO[R1, Any] )(use: A => ZIO[R1, E1, B]): ZIO[R1, E1, B] = - ZIO.bracketExit(self)( - (a: A, eb: Exit[E1, B]) => - eb match { - case Exit.Failure(_) => release(a) - case _ => ZIO.unit - } + ZIO.bracketExit(self)((a: A, eb: Exit[E1, B]) => + eb match { + case Exit.Failure(_) => release(a) + case _ => ZIO.unit + } )(use) /** @@ -226,12 +225,11 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self => final def bracketForkOnError[R1 <: R, E1 >: E, B]( release: A => URIO[R1, Any] )(use: A => ZIO[R1, E1, B]): ZIO[R1, E1, B] = - ZIO.bracketForkExit(self)( - (a: A, eb: Exit[E1, B]) => - eb match { - case Exit.Failure(_) => release(a) - case _ => ZIO.unit - } + ZIO.bracketForkExit(self)((a: A, eb: Exit[E1, B]) => + eb match { + case Exit.Failure(_) => release(a) + case _ => ZIO.unit + } )(use) /** @@ -397,21 +395,20 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self => * logic built on `ensuring`, see `ZIO#bracket`. */ final def ensuring[R1 <: R](finalizer: URIO[R1, Any]): ZIO[R1, E, A] = - ZIO.uninterruptibleMask( - restore => - restore(self) - .foldCauseM( - cause1 => - finalizer.foldCauseM[R1, E, Nothing]( - cause2 => ZIO.halt(cause1 ++ cause2), - _ => ZIO.halt(cause1) - ), - value => - finalizer.foldCauseM[R1, E, A]( - cause1 => ZIO.halt(cause1), - _ => ZIO.succeed(value) - ) - ) + ZIO.uninterruptibleMask(restore => + restore(self) + .foldCauseM( + cause1 => + finalizer.foldCauseM[R1, E, Nothing]( + cause2 => ZIO.halt(cause1 ++ cause2), + _ => ZIO.halt(cause1) + ), + value => + finalizer.foldCauseM[R1, E, A]( + cause1 => ZIO.halt(cause1), + _ => ZIO.succeed(value) + ) + ) ) /** @@ -783,12 +780,11 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self => * effect if it exists. The provided effect will not be interrupted. */ final def onError[R1 <: R](cleanup: Cause[E] => URIO[R1, Any]): ZIO[R1, E, A] = - ZIO.bracketExit(ZIO.unit)( - (_, eb: Exit[E, A]) => - eb match { - case Exit.Success(_) => ZIO.unit - case Exit.Failure(cause) => cleanup(cause) - } + ZIO.bracketExit(ZIO.unit)((_, eb: Exit[E, A]) => + eb match { + case Exit.Success(_) => ZIO.unit + case Exit.Failure(cause) => cleanup(cause) + } )(_ => self) /** @@ -833,12 +829,11 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self => * a defect or because of interruption. */ final def onTermination[R1 <: R](cleanup: Cause[Nothing] => URIO[R1, Any]): ZIO[R1, E, A] = - ZIO.bracketExit(ZIO.unit)( - (_, eb: Exit[E, A]) => - eb match { - case Exit.Failure(cause) => cause.failureOrCause.fold(_ => ZIO.unit, cleanup) - case _ => ZIO.unit - } + ZIO.bracketExit(ZIO.unit)((_, eb: Exit[E, A]) => + eb match { + case Exit.Failure(cause) => cause.failureOrCause.fold(_ => ZIO.unit, cleanup) + case _ => ZIO.unit + } )(_ => self) /** @@ -1060,10 +1055,9 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self => a => promise .succeed(a -> winner) - .flatMap( - set => - if (set) fibers.foldLeft(IO.unit)((io, f) => if (f eq winner) io else io <* f.interrupt) - else ZIO.unit + .flatMap(set => + if (set) fibers.foldLeft(IO.unit)((io, f) => if (f eq winner) io else io <* f.interrupt) + else ZIO.unit ) ) @@ -1110,20 +1104,19 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self => final def raceEither[R1 <: R, E1 >: E, B](that: ZIO[R1, E1, B]): ZIO[R1, E1, Either[A, B]] = ZIO.descriptor .map(_.id) - .flatMap( - parentFiberId => - raceWith(that)( - (exit, right) => - exit.foldM[Any, E1, Either[A, B]]( - _ => right.join.map(Right(_)), - a => ZIO.succeedLeft(a) <* right.interruptAs(parentFiberId) - ), - (exit, left) => - exit.foldM[Any, E1, Either[A, B]]( - _ => left.join.map(Left(_)), - b => ZIO.succeedRight(b) <* left.interruptAs(parentFiberId) - ) - ) + .flatMap(parentFiberId => + raceWith(that)( + (exit, right) => + exit.foldM[Any, E1, Either[A, B]]( + _ => right.join.map(Right(_)), + a => ZIO.succeedLeft(a) <* right.interruptAs(parentFiberId) + ), + (exit, left) => + exit.foldM[Any, E1, Either[A, B]]( + _ => left.join.map(Left(_)), + b => ZIO.succeedRight(b) <* left.interruptAs(parentFiberId) + ) + ) ) .refailWithTrace @@ -1678,15 +1671,13 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self => } val g = (b: B, a: A) => f(a, b) - ZIO.fiberId.flatMap( - parentFiberId => - (self raceWith that)(coordinate(parentFiberId, f, true), coordinate(parentFiberId, g, false)).fork.flatMap { - f => - f.await.flatMap { exit => - if (exit.succeeded) f.inheritRefs *> ZIO.done(exit) - else ZIO.done(exit) - } + ZIO.fiberId.flatMap(parentFiberId => + (self raceWith that)(coordinate(parentFiberId, f, true), coordinate(parentFiberId, g, false)).fork.flatMap { f => + f.await.flatMap { exit => + if (exit.succeeded) f.inheritRefs *> ZIO.done(exit) + else ZIO.done(exit) } + } ) } @@ -1859,16 +1850,15 @@ object ZIO { release: (A, Exit[E, B]) => URIO[R, Any], use: A => ZIO[R, E, B] ): ZIO[R, E, B] = - ZIO.uninterruptibleMask[R, E, B]( - restore => - acquire.flatMap(ZIOFn(traceAs = use) { a => - restore(use(a)).run.flatMap(ZIOFn(traceAs = release) { e => - release(a, e).foldCauseM( - cause2 => ZIO.halt(e.fold(_ ++ cause2, _ => cause2)), - _ => ZIO.done(e) - ) - }) + ZIO.uninterruptibleMask[R, E, B](restore => + acquire.flatMap(ZIOFn(traceAs = use) { a => + restore(use(a)).run.flatMap(ZIOFn(traceAs = release) { e => + release(a, e).foldCauseM( + cause2 => ZIO.halt(e.fold(_ ++ cause2, _ => cause2)), + _ => ZIO.done(e) + ) }) + }) ) /** @@ -2077,11 +2067,11 @@ object ZIO { register: (ZIO[R, E, A] => Unit) => Unit, blockingOn: List[Fiber.Id] = Nil ): ZIO[R, E, A] = - effectAsyncMaybe(ZIOFn(register)((callback: ZIO[R, E, A] => Unit) => { + effectAsyncMaybe(ZIOFn(register) { (callback: ZIO[R, E, A] => Unit) => register(callback) None - }), blockingOn) + }, blockingOn) /** * Imports an asynchronous effect into a pure `IO` value. The effect has the @@ -2107,7 +2097,7 @@ object ZIO { case (started, cancel) => flatten { effectAsyncMaybe( - ZIOFn(register)((k: UIO[ZIO[R, E, A]] => Unit) => { + ZIOFn(register) { (k: UIO[ZIO[R, E, A]] => Unit) => started.set(true) try register(io => k(ZIO.succeed(io))) match { @@ -2116,7 +2106,7 @@ object ZIO { None case Right(io) => Some(ZIO.succeed(io)) } finally if (!cancel.isSet) cancel.set(ZIO.unit) - }), + }, blockingOn ) }.onInterrupt(effectSuspendTotal(if (started.get) cancel.get() else ZIO.unit)) @@ -2322,11 +2312,13 @@ object ZIO { succeed <- Ref.make(0) fibers <- ZIO.traverse(as) { f(_) - .foldCauseM(c => causes.update(_ && c) *> result.fail(()), _ => { - (succeed.update(_ + 1) >>= { succeed => - ZIO.when(succeed == size)(result.succeed(())) - }).uninterruptible - }) + .foldCauseM( + c => causes.update(_ && c) *> result.fail(()), + _ => + (succeed.update(_ + 1) >>= { succeed => + ZIO.when(succeed == size)(result.succeed(())) + }).uninterruptible + ) .fork } interrupter = result.await @@ -3128,9 +3120,7 @@ object ZIO { def apply[B1 >: B](f: A => B1)(duration: Duration): ZIO[R with Clock, E, B1] = self .map(f) - .sandboxWith[R with Clock, E, B1]( - io => ZIO.absolve(io.either race ZIO.succeedRight(b).delay(duration)) - ) + .sandboxWith[R with Clock, E, B1](io => ZIO.absolve(io.either race ZIO.succeedRight(b).delay(duration))) } final class BracketAcquire_[-R, +E](private val acquire: ZIO[R, E, Any]) extends AnyVal { diff --git a/core/shared/src/main/scala/zio/ZManaged.scala b/core/shared/src/main/scala/zio/ZManaged.scala index 6f2c66d2f3bb..fd783cd80dd5 100644 --- a/core/shared/src/main/scala/zio/ZManaged.scala +++ b/core/shared/src/main/scala/zio/ZManaged.scala @@ -517,8 +517,8 @@ final class ZManaged[-R, +E, +A] private (reservation: ZIO[R, E, Reservation[R, ZManaged { Ref.make[Exit[Any, Any] => ZIO[R1, Nothing, Any]](_ => UIO.unit).map { finalizer => Reservation( - acquire = ZIO.bracketExit(self.reserve)( - (res, exitA: Exit[E, A]) => finalizer.set(exitU => res.release(exitU).ensuring(cleanup(exitA))) + acquire = ZIO.bracketExit(self.reserve)((res, exitA: Exit[E, A]) => + finalizer.set(exitU => res.release(exitU).ensuring(cleanup(exitA))) )(_.acquire), release = e => finalizer.get.flatMap(f => f(e)) ) @@ -533,8 +533,8 @@ final class ZManaged[-R, +E, +A] private (reservation: ZIO[R, E, Reservation[R, ZManaged { Ref.make[Exit[Any, Any] => ZIO[R1, Nothing, Any]](_ => UIO.unit).map { finalizer => Reservation( - acquire = ZIO.bracketExit(self.reserve)( - (res, exitA: Exit[E, A]) => finalizer.set(exitU => cleanup(exitA).ensuring(res.release(exitU))) + acquire = ZIO.bracketExit(self.reserve)((res, exitA: Exit[E, A]) => + finalizer.set(exitU => cleanup(exitA).ensuring(res.release(exitU))) )(_.acquire), release = e => finalizer.get.flatMap(f => f(e)) ) @@ -602,8 +602,8 @@ final class ZManaged[-R, +E, +A] private (reservation: ZIO[R, E, Reservation[R, res <- reserve _ <- finalizer.set(res.release) resource <- restore(res.acquire) - } yield ZManaged.make(ZIO.succeed(resource))( - _ => res.release(Exit.Success(resource)).provide(env) *> finalizer.set(_ => ZIO.unit) + } yield ZManaged.make(ZIO.succeed(resource))(_ => + res.release(Exit.Success(resource)).provide(env) *> finalizer.set(_ => ZIO.unit) ) } } @@ -854,12 +854,11 @@ final class ZManaged[-R, +E, +A] private (reservation: ZIO[R, E, Reservation[R, .raceWith(ZIO.sleep(d))( { case (leftDone, rightFiber) => - rightFiber.interrupt.flatMap( - _ => - leftDone.foldM( - ZIO.halt, - succ => clock.nanoTime.map(end => Some((Duration.fromNanos(end - start), succ))) - ) + rightFiber.interrupt.flatMap(_ => + leftDone.foldM( + ZIO.halt, + succ => clock.nanoTime.map(end => Some((Duration.fromNanos(end - start), succ))) + ) ) }, { case (exit, leftFiber) => @@ -1555,8 +1554,8 @@ object ZManaged { release = res.release.andThen(_.provide(env)) _ <- finalizers.update(_ + release) } yield ZManaged - .make(ZIO.succeed(resource))( - _ => release(Exit.Success(resource)).ensuring(finalizers.update(_ - release)) + .make(ZIO.succeed(resource))(_ => + release(Exit.Success(resource)).ensuring(finalizers.update(_ - release)) ) } } diff --git a/core/shared/src/main/scala/zio/ZQueue.scala b/core/shared/src/main/scala/zio/ZQueue.scala index f2c2d903b797..3f917e82c196 100644 --- a/core/shared/src/main/scala/zio/ZQueue.scala +++ b/core/shared/src/main/scala/zio/ZQueue.scala @@ -565,12 +565,11 @@ object ZQueue { val size: UIO[Int] = checkShutdownState.map(_ => queue.size() - takers.size() + strategy.surplusSize) val shutdown: UIO[Unit] = - ZIO.fiberId.flatMap( - fiberId => - IO.whenM(shutdownHook.succeed(()))( - IO.effectTotal(unsafePollAll(takers)) >>= (IO.foreachPar(_)(_.interruptAs(fiberId)) *> strategy.shutdown) - ) - .uninterruptible + ZIO.fiberId.flatMap(fiberId => + IO.whenM(shutdownHook.succeed(()))( + IO.effectTotal(unsafePollAll(takers)) >>= (IO.foreachPar(_)(_.interruptAs(fiberId)) *> strategy.shutdown) + ) + .uninterruptible ) val isShutdown: UIO[Boolean] = shutdownHook.poll.map(_.isDefined) diff --git a/core/shared/src/main/scala/zio/internal/FiberContext.scala b/core/shared/src/main/scala/zio/internal/FiberContext.scala index 0202593b345e..80cfdc2a9ad6 100644 --- a/core/shared/src/main/scala/zio/internal/FiberContext.scala +++ b/core/shared/src/main/scala/zio/internal/FiberContext.scala @@ -346,11 +346,12 @@ private[zio] final class FiberContext[E, A]( val kTrace = fastPathTrace(k, effect) var failIO = null.asInstanceOf[IO[E, Any]] - val value = try effect() - catch { - case t: Throwable if !platform.fatal(t) => - failIO = ZIO.fail(t.asInstanceOf[E]) - } + val value = + try effect() + catch { + case t: Throwable if !platform.fatal(t) => + failIO = ZIO.fail(t.asInstanceOf[E]) + } if (failIO eq null) { // delete continuation as it was "popped" after success @@ -455,11 +456,12 @@ private[zio] final class FiberContext[E, A]( if (traceEffects && inTracingRegion) addTrace(effect) var nextIo = null.asInstanceOf[IO[E, Any]] - val value = try effect() - catch { - case t: Throwable if !platform.fatal(t) => - nextIo = ZIO.fail(t.asInstanceOf[E]) - } + val value = + try effect() + catch { + case t: Throwable if !platform.fatal(t) => + nextIo = ZIO.fail(t.asInstanceOf[E]) + } if (nextIo eq null) curZio = nextInstr(value) else curZio = nextIo @@ -545,10 +547,11 @@ private[zio] final class FiberContext[E, A]( val k = zio.f if (traceExec && inTracingRegion) addTrace(k) - curZio = try k(platform, fiberId).asInstanceOf[ZIO[Any, E, Any]] - catch { - case t: Throwable if !platform.fatal(t) => ZIO.fail(t.asInstanceOf[E]) - } + curZio = + try k(platform, fiberId).asInstanceOf[ZIO[Any, E, Any]] + catch { + case t: Throwable if !platform.fatal(t) => ZIO.fail(t.asInstanceOf[E]) + } case ZIO.Tags.EffectSuspendTotalWith => val zio = curZio.asInstanceOf[ZIO.EffectSuspendTotalWith[Any, E, Any]] diff --git a/core/shared/src/main/scala/zio/stm/TReentrantLock.scala b/core/shared/src/main/scala/zio/stm/TReentrantLock.scala index fd2005733c28..ac5c6378b40d 100644 --- a/core/shared/src/main/scala/zio/stm/TReentrantLock.scala +++ b/core/shared/src/main/scala/zio/stm/TReentrantLock.scala @@ -106,19 +106,18 @@ final class TReentrantLock private (data: TRef[Either[ReadLock, WriteLock]]) { * number of write locks held by this fiber. */ lazy val releaseWrite: STM[Nothing, Int] = - STM.fiberId.flatMap( - fiberId => - data.modify { - case Right(WriteLock(1, m, `fiberId`)) => - 0 -> Left(ReadLock(fiberId, m)) + STM.fiberId.flatMap(fiberId => + data.modify { + case Right(WriteLock(1, m, `fiberId`)) => + 0 -> Left(ReadLock(fiberId, m)) - case Right(WriteLock(n, m, `fiberId`)) if n > 1 => - val newCount = n - 1 + case Right(WriteLock(n, m, `fiberId`)) if n > 1 => + val newCount = n - 1 - newCount -> Right(WriteLock(newCount, m, fiberId)) + newCount -> Right(WriteLock(newCount, m, fiberId)) - case s => die(s"Defect: Fiber ${fiberId} releasing write lock it does not hold: ${s}") - } + case s => die(s"Defect: Fiber ${fiberId} releasing write lock it does not hold: ${s}") + } ) /** diff --git a/stacktracer/jvm/src/main/scala/zio/internal/stacktracer/impl/AkkaLineNumbers.scala b/stacktracer/jvm/src/main/scala/zio/internal/stacktracer/impl/AkkaLineNumbers.scala index 6d100ffb8880..86934c6ed931 100644 --- a/stacktracer/jvm/src/main/scala/zio/internal/stacktracer/impl/AkkaLineNumbers.scala +++ b/stacktracer/jvm/src/main/scala/zio/internal/stacktracer/impl/AkkaLineNumbers.scala @@ -294,7 +294,8 @@ object AkkaLineNumbers { } match { case (Int.MaxValue, 0) => None case other => Some(other) - } else { + } + else { if (debug) println(s"LNB: (skipped)") var i = 1 while (i <= count) { diff --git a/streams-tests/jvm/src/test/scala/zio/stream/SinkSpec.scala b/streams-tests/jvm/src/test/scala/zio/stream/SinkSpec.scala index fe425ad584df..8b6b65d37277 100644 --- a/streams-tests/jvm/src/test/scala/zio/stream/SinkSpec.scala +++ b/streams-tests/jvm/src/test/scala/zio/stream/SinkSpec.scala @@ -1041,9 +1041,7 @@ object SinkSpec extends ZIOBaseSpec { Stream[Long](1, 5, 2, 3) .aggregate( Sink - .foldWeightedM(List[Long]())((a: Long) => UIO.succeed(a * 2), 12)( - (acc, el) => UIO.succeed(el :: acc) - ) + .foldWeightedM(List[Long]())((a: Long) => UIO.succeed(a * 2), 12)((acc, el) => UIO.succeed(el :: acc)) .map(_.reverse) ) .runCollect diff --git a/streams-tests/jvm/src/test/scala/zio/stream/StreamPullSafetySpec.scala b/streams-tests/jvm/src/test/scala/zio/stream/StreamPullSafetySpec.scala index 318d9eaee187..8072c9906839 100644 --- a/streams-tests/jvm/src/test/scala/zio/stream/StreamPullSafetySpec.scala +++ b/streams-tests/jvm/src/test/scala/zio/stream/StreamPullSafetySpec.scala @@ -641,8 +641,8 @@ object StreamPullSafetySpec extends ZIOBaseSpec { ref <- Ref.make(false) pulls <- Stream .fromIteratorManaged(Managed.make(UIO.succeed(List(1, 2).iterator))(_ => ref.set(true))) - .flatMap( - n => Stream.succeed((n * 2).toString) ++ Stream.fail("Ouch") ++ Stream.succeed((n * 3).toString) + .flatMap(n => + Stream.succeed((n * 2).toString) ++ Stream.fail("Ouch") ++ Stream.succeed((n * 3).toString) ) .process .use(nPulls(_, 8)) diff --git a/streams-tests/jvm/src/test/scala/zio/stream/StreamSpec.scala b/streams-tests/jvm/src/test/scala/zio/stream/StreamSpec.scala index b15de8da0725..ebac289f69ac 100644 --- a/streams-tests/jvm/src/test/scala/zio/stream/StreamSpec.scala +++ b/streams-tests/jvm/src/test/scala/zio/stream/StreamSpec.scala @@ -535,17 +535,15 @@ object StreamSpec extends ZIOBaseSpec { val stream: ZStream[Any, Nothing, Either[Unit, Unit]] = ZStream.empty stream.distributedWithDynamic[Nothing, Either[Unit, Unit]](1, _ => UIO.succeed(_ => true)).use { add => - { - val subscribe = ZStream.unwrap(add.map { - case (_, queue) => - ZStream.fromQueue(queue).unTake - }) - Promise.make[Nothing, Unit].flatMap { onEnd => - subscribe.ensuring(onEnd.succeed(())).runDrain.fork *> - onEnd.await *> - subscribe.runDrain *> - ZIO.succeed(assertCompletes) - } + val subscribe = ZStream.unwrap(add.map { + case (_, queue) => + ZStream.fromQueue(queue).unTake + }) + Promise.make[Nothing, Unit].flatMap { onEnd => + subscribe.ensuring(onEnd.succeed(())).runDrain.fork *> + onEnd.await *> + subscribe.runDrain *> + ZIO.succeed(assertCompletes) } } } @@ -667,12 +665,11 @@ object StreamSpec extends ZIOBaseSpec { } yield assert(res1)(equalTo(res2)) }), testM("right identity")( - checkM(pureStreamOfInts)( - m => - for { - res1 <- m.flatMap(i => Stream(i)).runCollect - res2 <- m.runCollect - } yield assert(res1)(equalTo(res2)) + checkM(pureStreamOfInts)(m => + for { + res1 <- m.flatMap(i => Stream(i)).runCollect + res2 <- m.runCollect + } yield assert(res1)(equalTo(res2)) ) ), testM("associativity") { @@ -721,12 +718,11 @@ object StreamSpec extends ZIOBaseSpec { for { ref <- Ref.make(false) inner = Stream - .bracketExit(UIO.unit)( - (_, e) => - e match { - case Exit.Failure(_) => ref.set(true) - case Exit.Success(_) => UIO.unit - } + .bracketExit(UIO.unit)((_, e) => + e match { + case Exit.Failure(_) => ref.set(true) + case Exit.Success(_) => UIO.unit + } ) .flatMap(_ => Stream.fail("Ouch")) _ <- Stream.succeed(()).flatMap(_ => inner).runDrain.either.unit @@ -764,11 +760,10 @@ object StreamSpec extends ZIOBaseSpec { substreamCancelled <- Ref.make[Boolean](false) latch <- Promise.make[Nothing, Unit] fiber <- Stream(()) - .flatMapPar(1)( - _ => - Stream.fromEffect( - (latch.succeed(()) *> ZIO.never).onInterrupt(substreamCancelled.set(true)) - ) + .flatMapPar(1)(_ => + Stream.fromEffect( + (latch.succeed(()) *> ZIO.never).onInterrupt(substreamCancelled.set(true)) + ) ) .run(Sink.collectAll[Unit]) .fork @@ -847,9 +842,7 @@ object StreamSpec extends ZIOBaseSpec { inner = Stream .bracket(execution.update("InnerAcquire" :: _))(_ => execution.update("InnerRelease" :: _)) _ <- Stream - .bracket(execution.update("OuterAcquire" :: _).as(inner))( - _ => execution.update("OuterRelease" :: _) - ) + .bracket(execution.update("OuterAcquire" :: _).as(inner))(_ => execution.update("OuterRelease" :: _)) .flatMapPar(2)(identity) .runDrain results <- execution.get @@ -897,11 +890,10 @@ object StreamSpec extends ZIOBaseSpec { substreamCancelled <- Ref.make[Boolean](false) latch <- Promise.make[Nothing, Unit] fiber <- Stream(()) - .flatMapParSwitch(1)( - _ => - Stream.fromEffect( - (latch.succeed(()) *> UIO.never).onInterrupt(substreamCancelled.set(true)) - ) + .flatMapParSwitch(1)(_ => + Stream.fromEffect( + (latch.succeed(()) *> UIO.never).onInterrupt(substreamCancelled.set(true)) + ) ) .runCollect .fork @@ -975,13 +967,9 @@ object StreamSpec extends ZIOBaseSpec { testM("finalizer ordering") { for { execution <- Ref.make(List.empty[String]) - inner = Stream.bracket(execution.update("InnerAcquire" :: _))( - _ => execution.update("InnerRelease" :: _) - ) + inner = Stream.bracket(execution.update("InnerAcquire" :: _))(_ => execution.update("InnerRelease" :: _)) _ <- Stream - .bracket(execution.update("OuterAcquire" :: _).as(inner))( - _ => execution.update("OuterRelease" :: _) - ) + .bracket(execution.update("OuterAcquire" :: _).as(inner))(_ => execution.update("OuterRelease" :: _)) .flatMapParSwitch(2)(identity) .runDrain results <- execution.get @@ -999,13 +987,11 @@ object StreamSpec extends ZIOBaseSpec { testM("foreachWhile") { for { ref <- Ref.make(0) - _ <- Stream(1, 1, 1, 1, 1, 1).foreachWhile[Any, Nothing]( - a => - ref.modify( - sum => - if (sum >= 3) (false, sum) - else (true, sum + a) - ) + _ <- Stream(1, 1, 1, 1, 1, 1).foreachWhile[Any, Nothing](a => + ref.modify(sum => + if (sum >= 3) (false, sum) + else (true, sum + a) + ) ) sum <- ref.get } yield assert(sum)(equalTo(3)) @@ -1021,8 +1007,8 @@ object StreamSpec extends ZIOBaseSpec { testM("Stream.forever") { for { ref <- Ref.make(0) - _ <- Stream(1).forever.foreachWhile[Any, Nothing]( - _ => ref.modify(sum => (if (sum >= 9) false else true, sum + 1)) + _ <- Stream(1).forever.foreachWhile[Any, Nothing](_ => + ref.modify(sum => (if (sum >= 9) false else true, sum + 1)) ) sum <- ref.get } yield assert(sum)(equalTo(10)) @@ -1051,9 +1037,7 @@ object StreamSpec extends ZIOBaseSpec { _ <- queue.offerAll(c.toSeq) fiber <- Stream .fromQueue(queue) - .foldWhileM[Any, Nothing, Int, List[Int]](List[Int]())(_ => true)( - (acc, el) => IO.succeed(el :: acc) - ) + .foldWhileM[Any, Nothing, Int, List[Int]](List[Int]())(_ => true)((acc, el) => IO.succeed(el :: acc)) .map(_.reverse) .fork _ <- waitForSize(queue, -1) @@ -1205,7 +1189,8 @@ object StreamSpec extends ZIOBaseSpec { case _ => if (s2.isEmpty) List.empty else interleave(b.tail, List.empty, s2) - } else + } + else s2 match { case h :: t => h :: interleave(b.tail, s1, t) diff --git a/streams-tests/jvm/src/test/scala/zio/stream/StreamUtils.scala b/streams-tests/jvm/src/test/scala/zio/stream/StreamUtils.scala index cb97cc84ce5b..b5a72bb5b1d1 100644 --- a/streams-tests/jvm/src/test/scala/zio/stream/StreamUtils.scala +++ b/streams-tests/jvm/src/test/scala/zio/stream/StreamUtils.scala @@ -28,15 +28,14 @@ trait StreamUtils extends ChunkUtils with GenZIO { case _ => Gen .int(1, max) - .flatMap( - n => - for { - i <- Gen.int(0, n - 1) - it <- Gen.listOfN(n)(a) - } yield ZStream.unfoldM((i, it)) { - case (_, Nil) | (0, _) => IO.fail("fail-case") - case (n, head :: rest) => IO.succeed(Some((head, (n - 1, rest)))) - } + .flatMap(n => + for { + i <- Gen.int(0, n - 1) + it <- Gen.listOfN(n)(a) + } yield ZStream.unfoldM((i, it)) { + case (_, Nil) | (0, _) => IO.fail("fail-case") + case (n, head :: rest) => IO.succeed(Some((head, (n - 1, rest)))) + } ) } diff --git a/streams/shared/src/main/scala/zio/stream/StreamEffect.scala b/streams/shared/src/main/scala/zio/stream/StreamEffect.scala index 24313b943bbe..f974388ef0b5 100644 --- a/streams/shared/src/main/scala/zio/stream/StreamEffect.scala +++ b/streams/shared/src/main/scala/zio/stream/StreamEffect.scala @@ -40,15 +40,13 @@ private[stream] final class StreamEffect[-R, +E, +A](val processEffect: ZManaged StreamEffect { self.processEffect.flatMap { thunk => Managed.effectTotal { () => - { - var b = null.asInstanceOf[B] + var b = null.asInstanceOf[B] - while (b == null) { - b = pf.applyOrElse(thunk(), (_: A) => null.asInstanceOf[B]) - } - - b + while (b == null) { + b = pf.applyOrElse(thunk(), (_: A) => null.asInstanceOf[B]) } + + b } } } @@ -222,11 +220,9 @@ private[stream] final class StreamEffect[-R, +E, +A](val processEffect: ZManaged StreamEffect { self.processEffect.flatMap { thunk => Managed.effectTotal { () => - { - val a = thunk() - if (pred(a)) a - else StreamEffect.end - } + val a = thunk() + if (pred(a)) a + else StreamEffect.end } } } diff --git a/streams/shared/src/main/scala/zio/stream/ZSink.scala b/streams/shared/src/main/scala/zio/stream/ZSink.scala index 7c96d92635a8..48ee634772bf 100644 --- a/streams/shared/src/main/scala/zio/stream/ZSink.scala +++ b/streams/shared/src/main/scala/zio/stream/ZSink.scala @@ -395,12 +395,11 @@ trait ZSink[-R, +E, +A0, -A, +B] extends Serializable { self => case (b, leftover) => ((Left(b), leftover)) } - .catchAll( - _ => - that.extract(s2).map { - case (c, leftover) => - ((Right(c), leftover)) - } + .catchAll(_ => + that.extract(s2).map { + case (c, leftover) => + ((Right(c), leftover)) + } ) } @@ -536,12 +535,11 @@ trait ZSink[-R, +E, +A0, -A, +B] extends Serializable { self => case (b, leftover) => (Left(b), leftover) } - .catchAll( - _ => - that.extract(s2).map { - case (c, leftover) => - (Right(c), leftover) - } + .catchAll(_ => + that.extract(s2).map { + case (c, leftover) => + (Right(c), leftover) + } ) case (Side.State(_), Side.Value((c, leftover))) => UIO.succeed((Right(c), leftover)) case (Side.Value((b, leftover)), _) => UIO.succeed((Left(b), leftover)) @@ -865,7 +863,8 @@ object ZSink extends ZSinkPlatformSpecificConstructors with Serializable { if (state.dirty && state.n < i) sink.extract(state.s).map { case (b, leftover) => ((b :: state.bs).reverse, leftover ++ state.leftover) - } else UIO.succeed((state.bs.reverse, state.leftover)) + } + else UIO.succeed((state.bs.reverse, state.leftover)) def cont(state: State) = state.n >= i } @@ -1259,10 +1258,10 @@ object ZSink extends ZSinkPlatformSpecificConstructors with Serializable { * */ def collectAllToMap[K, A](key: A => K)(f: (A, A) => A): Sink[Nothing, Nothing, A, Map[K, A]] = - foldLeft[A, Map[K, A]](Map.empty)((curMap, a) => { + foldLeft[A, Map[K, A]](Map.empty) { (curMap, a) => val k = key(a) curMap.get(k).fold(curMap.updated(k, a))(v => curMap.updated(k, f(v, a))) - }) + } /** * Creates a sink accumulating incoming values into a map of maximum size `n`. diff --git a/streams/shared/src/main/scala/zio/stream/ZStream.scala b/streams/shared/src/main/scala/zio/stream/ZStream.scala index 6dc424deb067..f8dc52186262 100644 --- a/streams/shared/src/main/scala/zio/stream/ZStream.scala +++ b/streams/shared/src/main/scala/zio/stream/ZStream.scala @@ -481,12 +481,11 @@ class ZStream[-R, +E, +A] private[stream] (private[stream] val structure: ZStrea // When the schedule signals completion, we emit its result into the // stream and restart with the schedule's initial state case Left(None) => - schedule.initial.map( - init => - Some( - Chunk.single(Left(schedule.extract(unfoldState.lastBatch, unfoldState.scheduleState))) -> unfoldState - .copy(scheduleState = init) - ) + schedule.initial.map(init => + Some( + Chunk.single(Left(schedule.extract(unfoldState.lastBatch, unfoldState.scheduleState))) -> unfoldState + .copy(scheduleState = init) + ) ) // When the schedule has completed its wait before the // next bath we resume with the next schedule state. @@ -1726,7 +1725,8 @@ class ZStream[-R, +E, +A] private[stream] (private[stream] val structure: ZStrea case Take.End => if (leftDone) ZIO.succeed(((leftDone, rightDone, s), Take.End)) else loop(leftDone, true, s, left, right) - } else loop(leftDone, rightDone, s, left, right) + } + else loop(leftDone, rightDone, s, left, right) case Take.End => ZIO.succeed(((leftDone, rightDone, s), Take.End)) } @@ -3035,21 +3035,20 @@ object ZStream extends ZStreamPlatformSpecificConstructors with Serializable { for { output <- Queue.bounded[Pull[R, E, A]](outputBuffer).toManaged(_.shutdown) runtime <- ZIO.runtime[R].toManaged_ - _ <- register( - k => - try { - runtime.unsafeRun { - k.foldCauseM( - Cause - .sequenceCauseOption(_) - .fold(output.offer(Pull.end))(c => output.offer(Pull.halt(c))), - a => output.offer(Pull.emit(a)) - ) - } - () - } catch { - case FiberFailure(Cause.Interrupt(_)) => + _ <- register(k => + try { + runtime.unsafeRun { + k.foldCauseM( + Cause + .sequenceCauseOption(_) + .fold(output.offer(Pull.end))(c => output.offer(Pull.halt(c))), + a => output.offer(Pull.emit(a)) + ) } + () + } catch { + case FiberFailure(Cause.Interrupt(_)) => + } ).toManaged_ done <- Ref.make(false).toManaged_ } yield done.get.flatMap { @@ -3079,21 +3078,20 @@ object ZStream extends ZStreamPlatformSpecificConstructors with Serializable { output <- Queue.bounded[Pull[R, E, A]](outputBuffer).toManaged(_.shutdown) runtime <- ZIO.runtime[R].toManaged_ eitherStream <- ZManaged.effectTotal { - register( - k => - try { - runtime.unsafeRun { - k.foldCauseM( - Cause - .sequenceCauseOption(_) - .fold(output.offer(Pull.end))(c => output.offer(Pull.halt(c))), - a => output.offer(Pull.emit(a)) - ) - } - () - } catch { - case FiberFailure(Cause.Interrupt(_)) => + register(k => + try { + runtime.unsafeRun { + k.foldCauseM( + Cause + .sequenceCauseOption(_) + .fold(output.offer(Pull.end))(c => output.offer(Pull.halt(c))), + a => output.offer(Pull.emit(a)) + ) } + () + } catch { + case FiberFailure(Cause.Interrupt(_)) => + } ) } pull <- eitherStream match { @@ -3227,12 +3225,11 @@ object ZStream extends ZStreamPlatformSpecificConstructors with Serializable { def fromQueue[R, E, A](queue: ZQueue[Nothing, Any, R, E, Nothing, A]): ZStream[R, E, A] = ZStream { ZManaged.succeed { - queue.take.catchAllCause( - c => - queue.isShutdown.flatMap { down => - if (down && c.interrupted) Pull.end - else Pull.halt(c) - } + queue.take.catchAllCause(c => + queue.isShutdown.flatMap { down => + if (down && c.interrupted) Pull.end + else Pull.halt(c) + } ) } } diff --git a/test-sbt/js/src/main/scala/zio/test/sbt/ZTestRunner.scala b/test-sbt/js/src/main/scala/zio/test/sbt/ZTestRunner.scala index 1683640f09fa..fb6c378f8502 100644 --- a/test-sbt/js/src/main/scala/zio/test/sbt/ZTestRunner.scala +++ b/test-sbt/js/src/main/scala/zio/test/sbt/ZTestRunner.scala @@ -65,10 +65,10 @@ final class ZMasterTestRunner(args: Array[String], remoteArgs: Array[String], te extends ZTestRunner(args, remoteArgs, testClassLoader, "master") { //This implementation seems to be used when there's only single spec to run - override val sendSummary: SendSummary = SendSummary.fromSend(summary => { + override val sendSummary: SendSummary = SendSummary.fromSend { summary => summaries += summary () - }) + } } diff --git a/test-sbt/jvm/src/main/scala/zio/test/sbt/ZTestRunner.scala b/test-sbt/jvm/src/main/scala/zio/test/sbt/ZTestRunner.scala index 0e4a705e9e0a..e6b665a87708 100644 --- a/test-sbt/jvm/src/main/scala/zio/test/sbt/ZTestRunner.scala +++ b/test-sbt/jvm/src/main/scala/zio/test/sbt/ZTestRunner.scala @@ -27,12 +27,11 @@ final class ZTestRunner(val args: Array[String], val remoteArgs: Array[String], extends Runner { val summaries: AtomicReference[Vector[Summary]] = new AtomicReference(Vector.empty) - val sendSummary: SendSummary = SendSummary.fromSendM( - summary => - ZIO.effectTotal { - summaries.updateAndGet(_ :+ summary) - () - } + val sendSummary: SendSummary = SendSummary.fromSendM(summary => + ZIO.effectTotal { + summaries.updateAndGet(_ :+ summary) + () + } ) def done(): String = { diff --git a/test-sbt/jvm/src/test/scala/zio/test/sbt/ZTestFrameworkSpec.scala b/test-sbt/jvm/src/test/scala/zio/test/sbt/ZTestFrameworkSpec.scala index 3d3d5fedee80..727d3a8fdb33 100644 --- a/test-sbt/jvm/src/test/scala/zio/test/sbt/ZTestFrameworkSpec.scala +++ b/test-sbt/jvm/src/test/scala/zio/test/sbt/ZTestFrameworkSpec.scala @@ -122,7 +122,7 @@ object ZTestFrameworkSpec { val runner = new ZTestFramework().runner(Array(), Array(), getClass.getClassLoader) val task = runner .tasks(Array(taskDef)) - .map(task => { + .map { task => val zTestTask = task.asInstanceOf[BaseTestTask] new ZTestTask( zTestTask.taskDef, @@ -130,7 +130,7 @@ object ZTestFrameworkSpec { FunctionIO.succeed(Summary(1, 0, 0, "foo")) >>> zTestTask.sendSummary, TestArgs.empty ) - }) + } .head task.execute(_ => (), Array.empty) @@ -143,7 +143,7 @@ object ZTestFrameworkSpec { val runner = new ZTestFramework().runner(Array(), Array(), getClass.getClassLoader) val task = runner .tasks(Array(taskDef)) - .map(task => { + .map { task => val zTestTask = task.asInstanceOf[BaseTestTask] new ZTestTask( zTestTask.taskDef, @@ -151,7 +151,7 @@ object ZTestFrameworkSpec { FunctionIO.succeed(Summary(0, 0, 0, "foo")) >>> zTestTask.sendSummary, TestArgs.empty ) - }) + } .head task.execute(_ => (), Array.empty) diff --git a/test-tests/shared/src/test/scala/zio/test/FunSpec.scala b/test-tests/shared/src/test/scala/zio/test/FunSpec.scala index ccb0e6f9d1ea..1c075f236e8f 100644 --- a/test-tests/shared/src/test/scala/zio/test/FunSpec.scala +++ b/test-tests/shared/src/test/scala/zio/test/FunSpec.scala @@ -16,10 +16,8 @@ object FunSpec extends ZIOBaseSpec { }, testM("fun does not have race conditions") { for { - f <- Fun.make((_: Int) => random.nextInt(6)) - results <- ZIO.foreachPar(List.range(0, 1000))( - n => ZIO.effectTotal((n % 6, f(n % 6))) - ) + f <- Fun.make((_: Int) => random.nextInt(6)) + results <- ZIO.foreachPar(List.range(0, 1000))(n => ZIO.effectTotal((n % 6, f(n % 6)))) } yield assert(results.distinct.length)(equalTo(6)) }, testM("fun is showable") { diff --git a/test-tests/shared/src/test/scala/zio/test/GenSpec.scala b/test-tests/shared/src/test/scala/zio/test/GenSpec.scala index d8545215870b..f4fcc46ace5e 100644 --- a/test-tests/shared/src/test/scala/zio/test/GenSpec.scala +++ b/test-tests/shared/src/test/scala/zio/test/GenSpec.scala @@ -25,13 +25,13 @@ object GenSpec extends ZIOBaseSpec { if (p) assert(())(Assertion.anything) else assert(n)(Assertion.nothing) } - assertM(CheckN(100)(gen)(test).flatMap(result => { + assertM(CheckN(100)(gen)(test).flatMap { result => result.run.map(_.failures.fold(false) { case BoolAlgebra.Value(failureDetails) => failureDetails.assertion.head.value.toString == "1" case _ => false }) - }))(isTrue) + })(isTrue) }, testM("with bogus reverse property") { val gen = for { @@ -81,13 +81,13 @@ object GenSpec extends ZIOBaseSpec { def test(a: List[Int]): TestResult = assert(a)(Assertion.nothing) - assertM(CheckN(100)(gen)(test).flatMap(result => { + assertM(CheckN(100)(gen)(test).flatMap { result => result.run.map(_.failures.fold(false) { case BoolAlgebra.Value(failureDetails) => failureDetails.assertion.head.value.toString == "List(0)" case _ => false }) - }))(isTrue) + })(isTrue) } ), suite("monad laws")( diff --git a/test-tests/shared/src/test/scala/zio/test/environment/RandomSpec.scala b/test-tests/shared/src/test/scala/zio/test/environment/RandomSpec.scala index 60c5e711d2c2..1177a12a00f2 100644 --- a/test-tests/shared/src/test/scala/zio/test/environment/RandomSpec.scala +++ b/test-tests/shared/src/test/scala/zio/test/environment/RandomSpec.scala @@ -45,11 +45,11 @@ object RandomSpec extends ZIOBaseSpec { val test = TestRandom.makeTest(DefaultData) ZIO .runtime[Any] - .map(rt => { + .map { rt => val x = rt.unsafeRun(test.flatMap[Any, Nothing, Int](_.nextInt)) val y = rt.unsafeRun(test.flatMap[Any, Nothing, Int](_.nextInt)) assert(x)(equalTo(y)) - }) + } }, testM("check fed ints do not survive repeating tests") { for { diff --git a/test/shared/src/main/scala/zio/test/DefaultTestReporter.scala b/test/shared/src/main/scala/zio/test/DefaultTestReporter.scala index 37c19bbf7920..6b6e9bf46d8c 100644 --- a/test/shared/src/main/scala/zio/test/DefaultTestReporter.scala +++ b/test/shared/src/main/scala/zio/test/DefaultTestReporter.scala @@ -78,14 +78,12 @@ object DefaultTestReporter { case Right(TestSuccess.Ignored) => UIO.succeed(rendered(Test, label, Ignored, depth)) case Left(TestFailure.Assertion(result)) => - result.run.flatMap( - result => - result - .fold( - details => - renderFailure(label, depth, details) - .map(failures => rendered(Test, label, Failed, depth, failures: _*)) - )(_.zipWith(_)(_ && _), _.zipWith(_)(_ || _), _.map(!_)) + result.run.flatMap(result => + result + .fold(details => + renderFailure(label, depth, details) + .map(failures => rendered(Test, label, Failed, depth, failures: _*)) + )(_.zipWith(_)(_ && _), _.zipWith(_)(_ || _), _.map(!_)) ) case Left(TestFailure.Runtime(cause)) => renderCause(cause, depth).map { string => @@ -398,10 +396,9 @@ object FailureRenderer { def renderTestFailure(label: String, testResult: TestResult): UIO[Message] = testResult.run.flatMap( _.failures.fold(UIO.succeed(Message()))( - _.fold( - details => - renderFailure(label, 0, details) - .map(failures => rendered(Test, label, Failed, 0, failures.lines: _*)) + _.fold(details => + renderFailure(label, 0, details) + .map(failures => rendered(Test, label, Failed, 0, failures.lines: _*)) )(_.zipWith(_)(_ && _), _.zipWith(_)(_ || _), _.map(!_)) .map(_.rendered) .map(Message.apply) diff --git a/test/shared/src/main/scala/zio/test/Spec.scala b/test/shared/src/main/scala/zio/test/Spec.scala index b9d13b341c2b..e06677ab14e2 100644 --- a/test/shared/src/main/scala/zio/test/Spec.scala +++ b/test/shared/src/main/scala/zio/test/Spec.scala @@ -440,20 +440,18 @@ final case class Spec[-R, +E, +L, +T](caseValue: SpecCase[R, E, L, T, Spec[R, E, case SuiteCase(label, specs, exec) => Spec.suite( label, - b.flatMap( - b => - if (b) specs.asInstanceOf[ZIO[R1, E1, Vector[Spec[R1, E1, L, TestSuccess[S]]]]] - else ZIO.succeed(Vector.empty) + b.flatMap(b => + if (b) specs.asInstanceOf[ZIO[R1, E1, Vector[Spec[R1, E1, L, TestSuccess[S]]]]] + else ZIO.succeed(Vector.empty) ), exec ) case TestCase(label, test) => Spec.test( label, - b.flatMap( - b => - if (b) test.asInstanceOf[ZIO[R1, E1, TestSuccess[S]]] - else Annotations.annotate(TestAnnotation.ignored, 1).as(TestSuccess.Ignored) + b.flatMap(b => + if (b) test.asInstanceOf[ZIO[R1, E1, TestSuccess[S]]] + else Annotations.annotate(TestAnnotation.ignored, 1).as(TestSuccess.Ignored) ) ) } diff --git a/test/shared/src/main/scala/zio/test/environment/package.scala b/test/shared/src/main/scala/zio/test/environment/package.scala index 3a0fee98c699..70d35a5a01ec 100644 --- a/test/shared/src/main/scala/zio/test/environment/package.scala +++ b/test/shared/src/main/scala/zio/test/environment/package.scala @@ -626,10 +626,9 @@ package object environment extends PlatformSpecific { */ val getStrLn: ZIO[Any, IOException, String] = { for { - input <- consoleState.get.flatMap( - d => - IO.fromOption(d.input.headOption) - .mapError(_ => new EOFException("There is no more input left to read")) + input <- consoleState.get.flatMap(d => + IO.fromOption(d.input.headOption) + .mapError(_ => new EOFException("There is no more input left to read")) ) _ <- consoleState.update { data => Data(data.input.tail, data.output) diff --git a/test/shared/src/main/scala/zio/test/package.scala b/test/shared/src/main/scala/zio/test/package.scala index 23bac1832828..3dc4ca50b687 100644 --- a/test/shared/src/main/scala/zio/test/package.scala +++ b/test/shared/src/main/scala/zio/test/package.scala @@ -522,11 +522,10 @@ package object test extends CompileVariants { ): ZIO[R1, E, TestResult] = stream.zipWithIndex.mapM { case (initial, index) => - initial.traverse( - input => - test(input).traced - .map(_.map(_.copy(gen = Some(GenFailureDetails(initial.value, input, index))))) - .either + initial.traverse(input => + test(input).traced + .map(_.map(_.copy(gen = Some(GenFailureDetails(initial.value, input, index))))) + .either ) }.mapM(_.traverse(_.fold(e => ZIO.succeed(Left(e)), a => a.run.map(Right(_))))) .dropWhile(!_.value.fold(_ => true, _.isFailure)) // Drop until we get to a failure