From 09936591d48929bc24926e564223f536475f7334 Mon Sep 17 00:00:00 2001 From: Felix Bruckmeier Date: Mon, 24 May 2021 22:33:58 +0200 Subject: [PATCH 1/7] WIP dependencies --- build.sbt | 78 ++++++++++++++++++++++++++++----------------- project/plugins.sbt | 2 +- 2 files changed, 49 insertions(+), 31 deletions(-) diff --git a/build.sbt b/build.sbt index b35c9723ed..6cb1b03caa 100644 --- a/build.sbt +++ b/build.sbt @@ -82,20 +82,28 @@ def jdk11GcJavaOptions: Seq[String] = { val defaultProjectSettings = Seq( scalaVersion := "2.13.6", - crossScalaVersions := Seq("2.12.12", "2.13.6") + crossScalaVersions := Seq("2.12.12", "2.13.6", "3.0.0") ) +def isScala3(scalaBinaryVersion: String): Boolean = + scalaBinaryVersion == "3" + val baseSettings = Seq( version := releaseVersion, organization := "com.twitter", // Workaround for a scaladoc bug which causes it to choke on empty classpaths. Compile / unmanagedClasspath += Attributed.blank(new java.io.File("doesnotexist")), libraryDependencies ++= Seq( - "org.scala-lang.modules" %% "scala-collection-compat" % "2.1.2", + "org.scala-lang.modules" %% "scala-collection-compat" % "2.4.4", // See https://www.scala-sbt.org/0.13/docs/Testing.html#JUnit "com.novocode" % "junit-interface" % "0.11" % "test", - "org.scalatest" %% "scalatest" % "3.1.2" % "test", - "org.scalatestplus" %% "junit-4-12" % "3.1.2.0" % "test" + ( + if (isScala3(scalaBinaryVersion.value)) + "org.scalatest" %% "scalatest" % "3.2.9" % "test" + else + "org.scalatest" %% "scalatest" % "3.1.2" % "test" + ), + ("org.scalatestplus" %% "junit-4-12" % "3.1.2.0" % "test").cross(CrossVersion.for3Use2_13) ), Test / fork := true, // We have to fork to get the JavaOptions // Workaround for cross building HealthyQueue.scala, which is not compatible between @@ -120,7 +128,9 @@ val baseSettings = Seq( // Needs -missing-interpolator due to https://issues.scala-lang.org/browse/SI-8761 "-Xlint:-missing-interpolator", "-Yrangepos" - ), + ) ++ Seq( + "-source:3.0-migration" + ).filter(_ => isScala3(scalaBinaryVersion.value)), // Note: Use -Xlint rather than -Xlint:unchecked when TestThriftStructure // warnings are resolved javacOptions ++= Seq("-Xlint:unchecked", "-source", "1.8", "-target", "1.8"), @@ -232,7 +242,7 @@ lazy val utilApp = Project( name := "util-app", libraryDependencies ++= Seq( "org.mockito" % "mockito-core" % mockitoVersion % "test", - "org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test" + ("org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test").cross(CrossVersion.for3Use2_13) ) ).dependsOn(utilAppLifecycle, utilCore, utilRegistry) @@ -275,7 +285,7 @@ lazy val utilCache = Project( caffeineLib, jsr305Lib, "org.mockito" % "mockito-core" % mockitoVersion % "test", - "org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test" + ("org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test").cross(CrossVersion.for3Use2_13) ) ).dependsOn(utilCore) @@ -318,14 +328,14 @@ lazy val utilCore = Project( // so that util-core would work better for Pants projects in IntelliJ. Compile / unmanagedSourceDirectories += baseDirectory.value / "concurrent-extra", libraryDependencies ++= Seq( + "org.scala-lang.modules" %% "scala-parser-combinators" % "2.0.0", caffeineLib % "test", - scalacheckLib, - "org.scala-lang" % "scala-reflect" % scalaVersion.value, - "org.scala-lang.modules" %% "scala-parser-combinators" % "1.1.2", "org.mockito" % "mockito-core" % mockitoVersion % "test", + ) ++ Seq( + scalacheckLib, "org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test", "org.scalatestplus" %% "scalacheck-1-14" % "3.1.2.0" % "test" - ), + ).map(_.cross(CrossVersion.for3Use2_13)), Compile / resourceGenerators += Def.task { val projectName = name.value val file = resourceManaged.value / "com" / "twitter" / projectName / "build.properties" @@ -371,7 +381,10 @@ lazy val utilReflect = Project( ).settings( sharedSettings ).settings( - name := "util-reflect" + name := "util-reflect", + libraryDependencies ++= Seq( + "org.scala-lang" % "scala-reflect" % scalaVersion.value + ) ).dependsOn(utilCore) lazy val utilHashing = Project( @@ -384,7 +397,7 @@ lazy val utilHashing = Project( libraryDependencies ++= Seq( scalacheckLib, "org.scalatestplus" %% "scalacheck-1-14" % "3.1.2.0" % "test" - ) + ).map(_.cross(CrossVersion.for3Use2_13)) ).dependsOn(utilCore % "test") lazy val utilJacksonAnnotations = Project( @@ -427,7 +440,7 @@ lazy val utilJvm = Project( name := "util-jvm", libraryDependencies ++= Seq( "org.mockito" % "mockito-core" % mockitoVersion % "test", - "org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test" + ("org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test").cross(CrossVersion.for3Use2_13) ) ).dependsOn(utilApp, utilCore, utilStats) @@ -460,7 +473,7 @@ lazy val utilMock = Project( // only depend on mockito-scala; it will pull in the correct corresponding version of mockito. "org.mockito" %% "mockito-scala" % mockitoScalaVersion, "org.mockito" %% "mockito-scala-scalatest" % mockitoScalaVersion % "test" - ) + ).map(_.cross(CrossVersion.for3Use2_13)) ).dependsOn(utilCore % "test") lazy val utilRegistry = Project( @@ -472,7 +485,7 @@ lazy val utilRegistry = Project( name := "util-registry", libraryDependencies ++= Seq( "org.mockito" % "mockito-core" % mockitoVersion % "test", - "org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test" + ("org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test").cross(CrossVersion.for3Use2_13) ) ).dependsOn(utilCore) @@ -494,7 +507,7 @@ lazy val utilSlf4jApi = Project( name := "util-slf4j-api", libraryDependencies ++= Seq( slf4jApi, - "org.mockito" %% "mockito-scala" % mockitoScalaVersion % "test", + ("org.mockito" %% "mockito-scala" % mockitoScalaVersion % "test").cross(CrossVersion.for3Use2_13), "org.slf4j" % "slf4j-simple" % slf4jVersion % "test" ) ).dependsOn(utilCore % "test", utilMock % "test") @@ -519,7 +532,7 @@ lazy val utilSecurity = Project( libraryDependencies ++= Seq( scalacheckLib, "org.scalatestplus" %% "scalacheck-1-14" % "3.1.2.0" % "test" - ) + ).map(_.cross(CrossVersion.for3Use2_13)) ).dependsOn(utilCore, utilLogging, utilSecurityTestCerts % "test") lazy val utilSecurityTestCerts = Project( @@ -541,14 +554,15 @@ lazy val utilStats = Project( libraryDependencies ++= Seq( caffeineLib, jsr305Lib, - scalacheckLib, "com.fasterxml.jackson.core" % "jackson-core" % jacksonVersion, "com.fasterxml.jackson.core" % "jackson-databind" % jacksonVersion, - "com.fasterxml.jackson.module" %% "jackson-module-scala" % jacksonVersion exclude ("com.google.guava", "guava"), "org.mockito" % "mockito-core" % mockitoVersion % "test", + ) ++ Seq( + scalacheckLib, + "com.fasterxml.jackson.module" %% "jackson-module-scala" % jacksonVersion exclude ("com.google.guava", "guava"), "org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test", "org.scalatestplus" %% "scalacheck-1-14" % "3.1.2.0" % "test" - ) ++ { + ).map(_.cross(CrossVersion.for3Use2_13)) ++ { CrossVersion.partialVersion(scalaVersion.value) match { case Some((2, major)) if major >= 13 => Seq("org.scala-lang.modules" %% "scala-parallel-collections" % "0.2.0" % "test") @@ -567,9 +581,12 @@ lazy val utilTest = Project( name := "util-test", libraryDependencies ++= Seq( "org.mockito" % "mockito-all" % "1.10.19", - "org.scalatest" %% "scalatest" % "3.1.2", - "org.scalatestplus" %% "junit-4-12" % "3.1.2.0", - "org.scalatestplus" %% "mockito-1-10" % "3.1.0.0" + (if (isScala3(scalaBinaryVersion.value)) + "org.scalatest" %% "scalatest" % "3.2.9" + else + "org.scalatest" %% "scalatest" % "3.1.2"), + ("org.scalatestplus" %% "junit-4-12" % "3.1.2.0").cross(CrossVersion.for3Use2_13), + ("org.scalatestplus" %% "mockito-1-10" % "3.1.0.0").cross(CrossVersion.for3Use2_13) ) ).dependsOn(utilCore, utilLogging) @@ -598,7 +615,7 @@ lazy val utilTunable = Project( libraryDependencies ++= Seq( "com.fasterxml.jackson.core" % "jackson-core" % jacksonVersion, "com.fasterxml.jackson.core" % "jackson-databind" % jacksonVersion, - "com.fasterxml.jackson.module" %% "jackson-module-scala" % jacksonVersion exclude ("com.google.guava", "guava") + ("com.fasterxml.jackson.module" %% "jackson-module-scala" % jacksonVersion exclude ("com.google.guava", "guava")).cross(CrossVersion.for3Use2_13) ) ).dependsOn(utilApp, utilCore) @@ -611,15 +628,16 @@ lazy val utilValidator = Project( name := "util-validator", libraryDependencies ++= Seq( caffeineLib, - scalacheckLib, "jakarta.validation" % "jakarta.validation-api" % "3.0.0", "org.hibernate.validator" % "hibernate-validator" % "7.0.1.Final", "org.glassfish" % "jakarta.el" % "4.0.0", - "org.json4s" %% "json4s-core" % "3.6.7", "com.fasterxml.jackson.core" % "jackson-annotations" % jacksonVersion % "test", - "org.scalatestplus" %% "scalacheck-1-14" % "3.1.2.0" % "test", "org.slf4j" % "slf4j-simple" % slf4jVersion % "test" - ) + ) ++ Seq( + "org.json4s" %% "json4s-core" % "3.6.7", + scalacheckLib, + "org.scalatestplus" %% "scalacheck-1-14" % "3.1.2.0" % "test", + ).map(_.cross(CrossVersion.for3Use2_13)) ).dependsOn(utilCore, utilReflect, utilSlf4jApi) lazy val utilZk = Project( @@ -632,7 +650,7 @@ lazy val utilZk = Project( libraryDependencies ++= Seq( zkDependency, "org.mockito" % "mockito-core" % mockitoVersion % "test", - "org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test" + ("org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test").cross(CrossVersion.for3Use2_13) ) ).dependsOn(utilCore, utilLogging) diff --git a/project/plugins.sbt b/project/plugins.sbt index e2cefb38da..bafd93d81a 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -2,5 +2,5 @@ resolvers += Classpaths.sbtPluginReleases resolvers += Resolver.sonatypeRepo("snapshots") addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "1.3.0") -addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1") +addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.8.1") addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.0") From 54474be3a52c75b16bee7f35164087c5b02cd60c Mon Sep 17 00:00:00 2001 From: Felix Bruckmeier Date: Sat, 29 May 2021 14:52:01 +0200 Subject: [PATCH 2/7] WIP Make tests run --- build.sbt | 48 ++++++++++++++----- .../src/main/java/com/twitter/util/Vars.java | 2 +- .../com/twitter/concurrent/AsyncMeter.scala | 2 +- .../scala/com/twitter/concurrent/Broker.scala | 2 - .../com/twitter/concurrent/Serialized.scala | 4 +- .../scala/com/twitter/concurrent/Spool.scala | 12 +++-- .../src/main/scala/com/twitter/io/Buf.scala | 12 ++--- .../src/main/scala/com/twitter/io/Pipe.scala | 28 +++++------ .../scala/com/twitter/io/TempFolder.scala | 4 +- .../scala/com/twitter/util/Awaitable.scala | 4 +- .../scala/com/twitter/util/Disposable.scala | 2 +- .../scala/com/twitter/util/Duration.scala | 17 +++---- .../main/scala/com/twitter/util/Promise.scala | 10 ++-- .../main/scala/com/twitter/util/Signal.scala | 2 +- .../main/scala/com/twitter/util/Time.scala | 11 +++-- .../src/main/scala/com/twitter/util/Var.scala | 2 +- .../concurrent/AsyncMeterCompilationTest.java | 2 +- .../OfferAndBrokerCompilationTest.java | 2 +- .../concurrent/SpoolCompilationTest.java | 1 + .../util/AwaitableCompilationTest.java | 2 + .../util/ClosableOnceCompilationTest.java | 5 ++ .../twitter/util/DurationCompilationTest.java | 34 ++++++------- .../twitter/util/FutureCompilationTest.java | 4 +- .../com/twitter/util/TimeCompilationTest.java | 44 ++++++++--------- .../twitter/util/TimerCompilationTest.java | 16 +++---- .../util/TokenBucketCompilationTest.java | 2 +- .../twitter/concurrent/AsyncStreamTest.scala | 8 ++-- .../twitter/conversions/StringOpsTest.scala | 28 +++++------ .../com/twitter/conversions/U64OpsTest.scala | 4 +- .../com/twitter/io/BufByteWriterTest.scala | 36 +++++++------- .../scala/com/twitter/io/BufReaderTest.scala | 6 +-- .../test/scala/com/twitter/io/BufTest.scala | 2 +- .../scala/com/twitter/io/ByteReaderTest.scala | 48 +++++++++---------- .../com/twitter/io/IteratorReaderTest.scala | 4 +- .../scala/com/twitter/io/ReaderTest.scala | 24 +++++----- .../scala/com/twitter/util/ActivityTest.scala | 12 ++--- .../com/twitter/util/Base64LongTest.scala | 4 +- .../com/twitter/util/CancellableTest.scala | 12 ++--- .../scala/com/twitter/util/ClosableTest.scala | 2 +- .../scala/com/twitter/util/DurationTest.scala | 2 +- .../scala/com/twitter/util/FutureTest.scala | 4 +- .../twitter/util/LastWriteWinsQueueTest.scala | 2 +- .../scala/com/twitter/util/MemoizeTest.scala | 4 +- .../com/twitter/util/StorageUnitTest.scala | 12 ++--- .../scala/com/twitter/util/TimeTest.scala | 11 ++--- .../test/scala/com/twitter/util/VarTest.scala | 4 +- 46 files changed, 269 insertions(+), 234 deletions(-) diff --git a/build.sbt b/build.sbt index 6cb1b03caa..8deef1a478 100644 --- a/build.sbt +++ b/build.sbt @@ -26,6 +26,30 @@ val jsr305Lib = "com.google.code.findbugs" % "jsr305" % "2.0.1" val scalacheckLib = "org.scalacheck" %% "scalacheck" % "1.15.4" % "test" val slf4jApi = "org.slf4j" % "slf4j-api" % slf4jVersion +def scalatestLib(scalaBinaryVersion: String) = + if (isScala3(scalaBinaryVersion)) + "org.scalatest" %% "scalatest" % "3.2.9" % "test" + else + "org.scalatest" %% "scalatest" % "3.1.2" % "test" + +def scalatestplusScalacheckLib(scalaBinaryVersion: String) = + if (isScala3(scalaBinaryVersion)) + "org.scalatestplus" %% "scalacheck-1-15" % "3.2.9.0" % "test" + else + "org.scalatestplus" %% "scalacheck-1-14" % "3.1.2.0" % "test" + +def scalatestplusJUnitLib(scalaBinaryVersion: String) = + if (isScala3(scalaBinaryVersion)) + "org.scalatestplus" %% "junit-4-13" % "3.2.9.0" % "test" + else + "org.scalatestplus" %% "junit-4-12" % "3.1.2.0" % "test" + +def scalatestplusMockitoLib(scalaBinaryVersion: String) = + if (isScala3(scalaBinaryVersion)) + "org.scalatestplus" %% "mockito-3-4" % "3.2.9.0" % "test" + else + "org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test" + def travisTestJavaOptions: Seq[String] = { // We have some custom configuration for the Travis environment // https://docs.travis-ci.com/user/environment-variables/#default-environment-variables @@ -97,13 +121,8 @@ val baseSettings = Seq( "org.scala-lang.modules" %% "scala-collection-compat" % "2.4.4", // See https://www.scala-sbt.org/0.13/docs/Testing.html#JUnit "com.novocode" % "junit-interface" % "0.11" % "test", - ( - if (isScala3(scalaBinaryVersion.value)) - "org.scalatest" %% "scalatest" % "3.2.9" % "test" - else - "org.scalatest" %% "scalatest" % "3.1.2" % "test" - ), - ("org.scalatestplus" %% "junit-4-12" % "3.1.2.0" % "test").cross(CrossVersion.for3Use2_13) + scalatestLib(scalaBinaryVersion.value), + scalatestplusJUnitLib(scalaBinaryVersion.value), ), Test / fork := true, // We have to fork to get the JavaOptions // Workaround for cross building HealthyQueue.scala, which is not compatible between @@ -111,6 +130,7 @@ val baseSettings = Seq( Compile / unmanagedSourceDirectories += { val sourceDir = (Compile / sourceDirectory).value CrossVersion.partialVersion(scalaVersion.value) match { + case Some((3, _)) => sourceDir / "scala-2.13+" case Some((2, n)) if n >= 13 => sourceDir / "scala-2.13+" case _ => sourceDir / "scala-2.12-" } @@ -129,7 +149,10 @@ val baseSettings = Seq( "-Xlint:-missing-interpolator", "-Yrangepos" ) ++ Seq( - "-source:3.0-migration" + "-source:3.0-migration", + "-rewrite", + "-explain", + "-explain-types", ).filter(_ => isScala3(scalaBinaryVersion.value)), // Note: Use -Xlint rather than -Xlint:unchecked when TestThriftStructure // warnings are resolved @@ -330,12 +353,11 @@ lazy val utilCore = Project( libraryDependencies ++= Seq( "org.scala-lang.modules" %% "scala-parser-combinators" % "2.0.0", caffeineLib % "test", - "org.mockito" % "mockito-core" % mockitoVersion % "test", - ) ++ Seq( scalacheckLib, - "org.scalatestplus" %% "mockito-3-3" % "3.1.2.0" % "test", - "org.scalatestplus" %% "scalacheck-1-14" % "3.1.2.0" % "test" - ).map(_.cross(CrossVersion.for3Use2_13)), + "org.mockito" % "mockito-core" % mockitoVersion % "test", + scalatestplusScalacheckLib(scalaBinaryVersion.value), + scalatestplusMockitoLib(scalaBinaryVersion.value), + ), Compile / resourceGenerators += Def.task { val projectName = name.value val file = resourceManaged.value / "com" / "twitter" / projectName / "build.properties" diff --git a/util-core/src/main/java/com/twitter/util/Vars.java b/util-core/src/main/java/com/twitter/util/Vars.java index 928c18d1b9..e428aee78f 100644 --- a/util-core/src/main/java/com/twitter/util/Vars.java +++ b/util-core/src/main/java/com/twitter/util/Vars.java @@ -35,7 +35,7 @@ public static Var newVar(T init, Event event) { * @see com.twitter.util.Var$#value(Object) */ public static Var newConstVar(T constant) { - return Var$.MODULE$.value(constant); + return (Var) Var$.MODULE$.value(constant); } /** diff --git a/util-core/src/main/scala/com/twitter/concurrent/AsyncMeter.scala b/util-core/src/main/scala/com/twitter/concurrent/AsyncMeter.scala index 24b46d63ff..59e61c4d24 100644 --- a/util-core/src/main/scala/com/twitter/concurrent/AsyncMeter.scala +++ b/util-core/src/main/scala/com/twitter/concurrent/AsyncMeter.scala @@ -138,7 +138,7 @@ object AsyncMeter { val seqWithoutLast: Seq[Future[Unit]] = (0 until num).map(_ => meter.await(meter.burstSize)) val seq = if (last == 0) seqWithoutLast else seqWithoutLast :+ meter.await(last) val result = Future.join(seq) - result.onFailure { exc => seq.foreach { f: Future[Unit] => f.raise(exc) } } + result.onFailure { exc => seq.foreach { (f: Future[Unit]) => f.raise(exc) } } result } else meter.await(permits) } diff --git a/util-core/src/main/scala/com/twitter/concurrent/Broker.scala b/util-core/src/main/scala/com/twitter/concurrent/Broker.scala index 937c416c41..b89c2d3647 100644 --- a/util-core/src/main/scala/com/twitter/concurrent/Broker.scala +++ b/util-core/src/main/scala/com/twitter/concurrent/Broker.scala @@ -82,7 +82,6 @@ class Broker[T] { val nextState = s match { case Quiet => Sending(Queue(elem)) case Sending(q) => Sending(q enqueue elem) - case Receiving(_) => throw new IllegalStateException() } if (state.compareAndSet(s, nextState)) p else prepare() @@ -111,7 +110,6 @@ class Broker[T] { val nextState = s match { case Quiet => Receiving(Queue(p)) case Receiving(q) => Receiving(q enqueue p) - case Sending(_) => throw new IllegalStateException() } if (state.compareAndSet(s, nextState)) p else prepare() diff --git a/util-core/src/main/scala/com/twitter/concurrent/Serialized.scala b/util-core/src/main/scala/com/twitter/concurrent/Serialized.scala index 4849e9b987..55caf37059 100644 --- a/util-core/src/main/scala/com/twitter/concurrent/Serialized.scala +++ b/util-core/src/main/scala/com/twitter/concurrent/Serialized.scala @@ -28,9 +28,9 @@ trait Serialized { serializedQueue add { Job(result, () => f) } if (nwaiters.getAndIncrement() == 0) { - do { + while ({ { Try { serializedQueue.remove()() } - } while (nwaiters.decrementAndGet() > 0) + } ; nwaiters.decrementAndGet() > 0}) () } result diff --git a/util-core/src/main/scala/com/twitter/concurrent/Spool.scala b/util-core/src/main/scala/com/twitter/concurrent/Spool.scala index c56a55c71e..0fdb10f0a6 100644 --- a/util-core/src/main/scala/com/twitter/concurrent/Spool.scala +++ b/util-core/src/main/scala/com/twitter/concurrent/Spool.scala @@ -78,12 +78,12 @@ sealed trait Spool[+A] { Future { f(Some(head)) } flatMap { _ => tail transform { case Return(s) => s.foreachElem(f) - case Throw(_: EOFException) => Future { f(None) } + case Throw(_: EOFException) => Future { f(None); () } case Throw(cause) => Future.exception(cause) } } } else { - Future { f(None) } + Future { f(None); () } } } @@ -273,8 +273,14 @@ sealed trait Spool[+A] { /** * Abstract `Spool` class for Java compatibility. + * + * The overrides for `++` are needed otherwise the java-compiler complains about two methods having the same erasure. */ -abstract class AbstractSpool[A] extends Spool[A] +abstract class AbstractSpool[A] extends Spool[A] { + override def ++[B >: A](that: => Spool[B]): Spool[B] = super.++(that) + + override def ++[B >: A](that: => Future[Spool[B]]): Future[Spool[B]] = super.++(that) +} /** * Note: [[Spool]] is no longer the recommended asynchronous stream abstraction. diff --git a/util-core/src/main/scala/com/twitter/io/Buf.scala b/util-core/src/main/scala/com/twitter/io/Buf.scala index cc54e985f1..eee08d65cd 100644 --- a/util-core/src/main/scala/com/twitter/io/Buf.scala +++ b/util-core/src/main/scala/com/twitter/io/Buf.scala @@ -429,7 +429,7 @@ object Buf { def slice(from: Int, until: Int): Buf = { checkSliceArgs(from, until) - if (isSliceEmpty(from, until)) return Buf.Empty + if (this.isSliceEmpty(from, until)) return Buf.Empty else if (isSliceIdentity(from, until)) return this var begin = from @@ -503,7 +503,7 @@ object Buf { def process(from: Int, until: Int, processor: Processor): Int = { checkSliceArgs(from, until) - if (isSliceEmpty(from, until)) return -1 + if (this.isSliceEmpty(from, until)) return -1 var i = 0 var bufIdx = 0 var continue = true @@ -620,7 +620,7 @@ object Buf { def process(from: Int, until: Int, processor: Processor): Int = { checkSliceArgs(from, until) - if (isSliceEmpty(from, until)) return -1 + if (this.isSliceEmpty(from, until)) return -1 var i = from var continue = true val endAt = math.min(until, length) @@ -647,7 +647,7 @@ object Buf { def slice(from: Int, until: Int): Buf = { checkSliceArgs(from, until) - if (isSliceEmpty(from, until)) Buf.Empty + if (this.isSliceEmpty(from, until)) Buf.Empty else if (isSliceIdentity(from, until)) this else { val cap = math.min(until, length) @@ -826,7 +826,7 @@ object Buf { def process(from: Int, until: Int, processor: Processor): Int = { checkSliceArgs(from, until) - if (isSliceEmpty(from, until)) return -1 + if (this.isSliceEmpty(from, until)) return -1 val pos = underlying.position() var i = from var continue = true @@ -856,7 +856,7 @@ object Buf { def slice(from: Int, until: Int): Buf = { checkSliceArgs(from, until) - if (isSliceEmpty(from, until)) Buf.Empty + if (this.isSliceEmpty(from, until)) Buf.Empty else if (isSliceIdentity(from, until)) this else { val dup = underlying.duplicate() diff --git a/util-core/src/main/scala/com/twitter/io/Pipe.scala b/util-core/src/main/scala/com/twitter/io/Pipe.scala index 7f257775b6..a1c53656d7 100644 --- a/util-core/src/main/scala/com/twitter/io/Pipe.scala +++ b/util-core/src/main/scala/com/twitter/io/Pipe.scala @@ -145,36 +145,36 @@ final class Pipe[A](timer: Timer) extends Reader[A] with Writer[A] { } def write(buf: A): Future[Unit] = { - val (waiter, value, result) = synchronized { + val result = synchronized { state match { case State.Failed(exc) => - (null, null, Future.exception(exc)) + Right(Future.exception(exc)) case State.Closed | State.Closing(_, _) => - (null, null, Future.exception(new IllegalStateException("write() while closed"))) + Right(Future.exception(new IllegalStateException("write() while closed"))) case State.Idle => val p = new Promise[Unit] state = State.Writing(buf, p) - (null, null, p) + Right(p) - case State.Reading(p) => + case State.Reading(p: Promise[Option[A]]) => // pending reader has enough space for the full write state = State.Idle - (p, Some(buf), Future.Done) + Left(() => p.setValue(Some(buf))) case State.Writing(_, _) => - ( - null, - null, - Future.exception(new IllegalStateException("write() while write is pending")) - ) + Right(Future.exception(new IllegalStateException("write() while write is pending"))) } } - // The waiter and the value are mutually inclusive so just checking against waiter is adequate. - if (waiter != null) waiter.setValue(value) - result + result.fold( + { l => + l() + Future.Done + }, + r => r + ) } def fail(cause: Throwable): Unit = fail(cause, discard = false) diff --git a/util-core/src/main/scala/com/twitter/io/TempFolder.scala b/util-core/src/main/scala/com/twitter/io/TempFolder.scala index 25b1fd492c..8579904602 100644 --- a/util-core/src/main/scala/com/twitter/io/TempFolder.scala +++ b/util-core/src/main/scala/com/twitter/io/TempFolder.scala @@ -39,9 +39,9 @@ trait TempFolder { // Note: If we were willing to have a dependency on Guava in util-core // we could just use `com.google.common.io.Files.createTempDir()` var folder: File = null - do { + while ({ { folder = new File(tempFolder, "scala-test-" + System.currentTimeMillis) - } while (!folder.mkdir()) + } ; !folder.mkdir()}) () _folderName.set(folder) try { diff --git a/util-core/src/main/scala/com/twitter/util/Awaitable.scala b/util-core/src/main/scala/com/twitter/util/Awaitable.scala index 0f5e44b595..1b6ac0bd58 100644 --- a/util-core/src/main/scala/com/twitter/util/Awaitable.scala +++ b/util-core/src/main/scala/com/twitter/util/Awaitable.scala @@ -225,7 +225,7 @@ private[util] trait CloseAwaitably0[U <: Unit] extends Awaitable[U] { } // See https://stackoverflow.com/questions/26643045/java-interoperability-woes-with-scala-generics-and-boxing -private[util] trait CloseOnceAwaitably0[U <: Unit] extends Awaitable[U] { self: CloseOnce => +private[util] trait CloseOnceAwaitably0[U <: Unit] extends Awaitable[U] { self: CloseOnce with com.twitter.util.Closable => def ready(timeout: Duration)(implicit permit: Awaitable.CanAwait): this.type = { closeFuture.ready(timeout) @@ -251,7 +251,7 @@ private[util] trait CloseOnceAwaitably0[U <: Unit] extends Awaitable[U] { self: * } * }}} */ -trait CloseOnceAwaitably extends CloseOnceAwaitably0[Unit] { self: CloseOnce => } +trait CloseOnceAwaitably extends CloseOnceAwaitably0[Unit] { self: CloseOnce with com.twitter.util.Closable => } /** * A mixin to make an [[com.twitter.util.Awaitable]] out diff --git a/util-core/src/main/scala/com/twitter/util/Disposable.scala b/util-core/src/main/scala/com/twitter/util/Disposable.scala index d2b502a0f0..78d29bae7f 100644 --- a/util-core/src/main/scala/com/twitter/util/Disposable.scala +++ b/util-core/src/main/scala/com/twitter/util/Disposable.scala @@ -112,7 +112,7 @@ trait Managed[+T] { selfT => u.dispose(deadline) transform { case Return(_) => t.dispose(deadline) case Throw(outer) => - t.dispose transform { + t.dispose() transform { case Throw(inner) => Future.exception(new DoubleTrouble(outer, inner)) case Return(_) => Future.exception(outer) } diff --git a/util-core/src/main/scala/com/twitter/util/Duration.scala b/util-core/src/main/scala/com/twitter/util/Duration.scala index 3125fa086b..3f8eded9e3 100644 --- a/util-core/src/main/scala/com/twitter/util/Duration.scala +++ b/util-core/src/main/scala/com/twitter/util/Duration.scala @@ -4,19 +4,20 @@ import java.io.Serializable import java.util.concurrent.TimeUnit object Duration extends TimeLikeOps[Duration] { - def fromNanoseconds(nanoseconds: Long): Duration = + override def fromNanoseconds(nanoseconds: Long): Duration = if (nanoseconds == 0L) Zero else new Duration(nanoseconds) + // FIXME figure out why the overrides cause issues in Scala 3.0 // This is needed for Java compatibility. - override def fromFractionalSeconds(seconds: Double): Duration = + def fromFractionalSecondsJ(seconds: Double): Duration = super.fromFractionalSeconds(seconds) - override def fromSeconds(seconds: Int): Duration = super.fromSeconds(seconds) - override def fromMinutes(minutes: Int): Duration = super.fromMinutes(minutes) - override def fromMilliseconds(millis: Long): Duration = super.fromMilliseconds(millis) - override def fromMicroseconds(micros: Long): Duration = super.fromMicroseconds(micros) - override def fromHours(hours: Int): Duration = super.fromHours(hours) - override def fromDays(days: Int): Duration = super.fromDays(days) + def fromSecondsJ(seconds: Int): Duration = super.fromSeconds(seconds) + def fromMinutesJ(minutes: Int): Duration = super.fromMinutes(minutes) + def fromMillisecondsJ(millis: Long): Duration = super.fromMilliseconds(millis) + def fromMicrosecondsJ(micros: Long): Duration = super.fromMicroseconds(micros) + def fromHoursJ(hours: Int): Duration = super.fromHours(hours) + def fromDaysJ(days: Int): Duration = super.fromDays(days) val NanosPerMicrosecond: Long = 1000L val NanosPerMillisecond: Long = NanosPerMicrosecond * 1000L diff --git a/util-core/src/main/scala/com/twitter/util/Promise.scala b/util-core/src/main/scala/com/twitter/util/Promise.scala index 054306811b..7d776fa7c5 100644 --- a/util-core/src/main/scala/com/twitter/util/Promise.scala +++ b/util-core/src/main/scala/com/twitter/util/Promise.scala @@ -144,7 +144,7 @@ object Promise { * A template trait for [[com.twitter.util.Promise Promises]] that are derived * and capable of being detached from other Promises. */ - trait Detachable { _: Promise[_] => + trait Detachable { self: Promise[_] => /** * Returns true if successfully detached, will return true at most once. @@ -470,17 +470,17 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ @volatile private[this] var state: Any = WaitQueue.empty[A] private def theState(): Any = state - private[util] def this(forwardInterrupts: Future[_]) { + private[util] def this(forwardInterrupts: Future[_]) = { this() this.state = new Transforming[A](WaitQueue.empty, forwardInterrupts) } - def this(handleInterrupt: PartialFunction[Throwable, Unit]) { + def this(handleInterrupt: PartialFunction[Throwable, Unit]) = { this() this.state = new Interruptible[A](WaitQueue.empty, handleInterrupt, Local.save()) } - def this(result: Try[A]) { + def this(result: Try[A]) = { this() this.state = result } @@ -571,7 +571,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ } } - @tailrec final def raise(intr: Throwable): Unit = state match { + final def raise(intr: Throwable): Unit = state match { case waitq: WaitQueue[A] => if (!cas(waitq, new Interrupted(waitq, intr))) raise(intr) diff --git a/util-core/src/main/scala/com/twitter/util/Signal.scala b/util-core/src/main/scala/com/twitter/util/Signal.scala index 333af1588d..2a945361c1 100644 --- a/util-core/src/main/scala/com/twitter/util/Signal.scala +++ b/util-core/src/main/scala/com/twitter/util/Signal.scala @@ -23,7 +23,7 @@ import scala.collection.{Map, Set, mutable} object SignalHandlerFactory { def apply(): Option[SunSignalHandler] = { // only one actual implementation for now - SunSignalHandler.instantiate + SunSignalHandler.instantiate() } } diff --git a/util-core/src/main/scala/com/twitter/util/Time.scala b/util-core/src/main/scala/com/twitter/util/Time.scala index dcf80ad0d0..042c37bb63 100644 --- a/util-core/src/main/scala/com/twitter/util/Time.scala +++ b/util-core/src/main/scala/com/twitter/util/Time.scala @@ -293,12 +293,13 @@ private[util] object TimeBox { object Time extends TimeLikeOps[Time] { def fromNanoseconds(nanoseconds: Long): Time = new Time(nanoseconds) + // FIXME figure out why the overrides cause issues in Scala 3.0 // This is needed for Java compatibility. - override def fromFractionalSeconds(seconds: Double): Time = super.fromFractionalSeconds(seconds) - override def fromSeconds(seconds: Int): Time = super.fromSeconds(seconds) - override def fromMinutes(minutes: Int): Time = super.fromMinutes(minutes) - override def fromMilliseconds(millis: Long): Time = super.fromMilliseconds(millis) - override def fromMicroseconds(micros: Long): Time = super.fromMicroseconds(micros) + def fromFractionalSecondsJ(seconds: Double): Time = super.fromFractionalSeconds(seconds) + def fromSecondsJ(seconds: Int): Time = super.fromSeconds(seconds) + def fromMinutesJ(minutes: Int): Time = super.fromMinutes(minutes) + def fromMillisecondsJ(millis: Long): Time = super.fromMilliseconds(millis) + def fromMicrosecondsJ(micros: Long): Time = super.fromMicroseconds(micros) private[this] val SystemClock = Clock.systemUTC() diff --git a/util-core/src/main/scala/com/twitter/util/Var.scala b/util-core/src/main/scala/com/twitter/util/Var.scala index 0dd17eb98e..9af4c33c07 100644 --- a/util-core/src/main/scala/com/twitter/util/Var.scala +++ b/util-core/src/main/scala/com/twitter/util/Var.scala @@ -271,7 +271,7 @@ object Var { // In order to support unsubscribing from diffs when v is no longer referenced // we must avoid diffs keeping a strong reference to v. - val witness = Witness.weakReference { diff: Diff[CC, T] => + val witness = Witness.weakReference { (diff: Diff[CC, T]) => synchronized { v.update(diff.patch(v())) } diff --git a/util-core/src/test/java/com/twitter/concurrent/AsyncMeterCompilationTest.java b/util-core/src/test/java/com/twitter/concurrent/AsyncMeterCompilationTest.java index 60e25e4b0b..22f6507d91 100644 --- a/util-core/src/test/java/com/twitter/concurrent/AsyncMeterCompilationTest.java +++ b/util-core/src/test/java/com/twitter/concurrent/AsyncMeterCompilationTest.java @@ -16,7 +16,7 @@ public void testCreatePerSecond() { @Test public void testCreateNewMeter() { MockTimer timer = new MockTimer(); - AsyncMeter meter = AsyncMeter.newMeter(5, Duration.fromMilliseconds(5), 5, timer); + AsyncMeter meter = AsyncMeter.newMeter(5, Duration.fromMillisecondsJ(5), 5, timer); } @Test diff --git a/util-core/src/test/java/com/twitter/concurrent/OfferAndBrokerCompilationTest.java b/util-core/src/test/java/com/twitter/concurrent/OfferAndBrokerCompilationTest.java index 846cf7f65e..3560ce0609 100644 --- a/util-core/src/test/java/com/twitter/concurrent/OfferAndBrokerCompilationTest.java +++ b/util-core/src/test/java/com/twitter/concurrent/OfferAndBrokerCompilationTest.java @@ -37,7 +37,7 @@ public String apply() { return "33"; } }); - Offer d = Offers.newTimeoutOffer(Duration.fromMicroseconds(1), new NullTimer()); + Offer d = Offers.newTimeoutOffer(Duration.fromMicrosecondsJ(1), new NullTimer()); Assert.assertNotNull(a); Assert.assertNotNull(b); diff --git a/util-core/src/test/java/com/twitter/concurrent/SpoolCompilationTest.java b/util-core/src/test/java/com/twitter/concurrent/SpoolCompilationTest.java index 2b89e1b9d6..d083e6d95b 100644 --- a/util-core/src/test/java/com/twitter/concurrent/SpoolCompilationTest.java +++ b/util-core/src/test/java/com/twitter/concurrent/SpoolCompilationTest.java @@ -4,6 +4,7 @@ import com.twitter.util.Future; import org.junit.Assert; import org.junit.Test; +import scala.Function0; import scala.collection.JavaConverters; import java.util.Arrays; diff --git a/util-core/src/test/java/com/twitter/util/AwaitableCompilationTest.java b/util-core/src/test/java/com/twitter/util/AwaitableCompilationTest.java index 3fdae8ea17..6e3e6d4e71 100644 --- a/util-core/src/test/java/com/twitter/util/AwaitableCompilationTest.java +++ b/util-core/src/test/java/com/twitter/util/AwaitableCompilationTest.java @@ -8,6 +8,8 @@ import java.util.Arrays; import java.util.Collection; +import com.twitter.util.Awaitable.CanAwait; + public class AwaitableCompilationTest { public static class MockAwaitable implements Awaitable { diff --git a/util-core/src/test/java/com/twitter/util/ClosableOnceCompilationTest.java b/util-core/src/test/java/com/twitter/util/ClosableOnceCompilationTest.java index 99b4932dee..ae3fd4b685 100644 --- a/util-core/src/test/java/com/twitter/util/ClosableOnceCompilationTest.java +++ b/util-core/src/test/java/com/twitter/util/ClosableOnceCompilationTest.java @@ -15,6 +15,11 @@ public Future closeOnce(Time deadline) { closeCount++; return Future.Done(); } + + @Override + public Future close(Time deadline) { + return Future.Done(); + } } @Test diff --git a/util-core/src/test/java/com/twitter/util/DurationCompilationTest.java b/util-core/src/test/java/com/twitter/util/DurationCompilationTest.java index 039b387512..e90653105f 100644 --- a/util-core/src/test/java/com/twitter/util/DurationCompilationTest.java +++ b/util-core/src/test/java/com/twitter/util/DurationCompilationTest.java @@ -20,9 +20,9 @@ public void testTopAndBottom() { @Test public void testFrom() { Duration a = Duration.fromTimeUnit(1, TimeUnit.MINUTES); - Duration b = Duration.fromSeconds(60); - Duration c = Duration.fromMilliseconds(60000); - Duration d = Duration.fromMicroseconds(60000000); + Duration b = Duration.fromSecondsJ(60); + Duration c = Duration.fromMillisecondsJ(60000); + Duration d = Duration.fromMicrosecondsJ(60000000); Duration e = Duration.fromNanoseconds(60000000000l); Assert.assertEquals(a, b); @@ -40,9 +40,9 @@ public void testConstructor() { @Test public void testPlusAndMinus() { - Duration a = Duration.fromSeconds(1); - Duration b = a.plus(Duration.fromMilliseconds(1000)); - Duration c = b.minus(Duration.fromMilliseconds(500)); + Duration a = Duration.fromSecondsJ(1); + Duration b = a.plus(Duration.fromMillisecondsJ(1000)); + Duration c = b.minus(Duration.fromMillisecondsJ(500)); Assert.assertEquals(a, a.minus(Duration.Zero())); Assert.assertEquals(a, a.plus(Duration.Zero())); @@ -54,8 +54,8 @@ public void testPlusAndMinus() { @Test public void testMinMax() { - Duration a = Duration.fromSeconds(4); - Duration b = Duration.fromMicroseconds(4); + Duration a = Duration.fromSecondsJ(4); + Duration b = Duration.fromMicrosecondsJ(4); Assert.assertEquals(a, a.max(Duration.Zero())); Assert.assertEquals(a, a.max(b)); @@ -76,7 +76,7 @@ public void testNeg() { @Test public void testAbs() { - Duration a = Duration.fromMicroseconds(-9999); + Duration a = Duration.fromMicrosecondsJ(-9999); Duration b = a.abs(); Duration c = b.abs(); @@ -86,7 +86,7 @@ public void testAbs() { @Test public void testMulAndDiv() { - Duration a = Duration.fromSeconds(2); + Duration a = Duration.fromSecondsJ(2); Duration b = a.div(10); Duration c = b.mul(10); @@ -96,7 +96,7 @@ public void testMulAndDiv() { @Test public void testMulAndDivDouble() { - Duration a = Duration.fromSeconds(9); + Duration a = Duration.fromSecondsJ(9); Duration b = a.div(4.5); Duration c = b.mul(4.5); @@ -106,8 +106,8 @@ public void testMulAndDivDouble() { @Test public void testRem() { - Duration a = Duration.fromSeconds(5); - Duration b = a.rem(Duration.fromSeconds(2)); + Duration a = Duration.fromSecondsJ(5); + Duration b = a.rem(Duration.fromSecondsJ(2)); Assert.assertEquals(1000, b.inMilliseconds()); } @@ -122,16 +122,16 @@ public void testDiff() { @Test public void testFloor() { - Duration a = Duration.fromMilliseconds(2222); - Duration b = a.floor(Duration.fromSeconds(1)); + Duration a = Duration.fromMillisecondsJ(2222); + Duration b = a.floor(Duration.fromSecondsJ(1)); Assert.assertEquals(2, b.inSeconds()); } @Test public void testCeil() { - Duration a = Duration.fromMilliseconds(3333); - Duration b = a.ceil(Duration.fromSeconds(1)); + Duration a = Duration.fromMillisecondsJ(3333); + Duration b = a.ceil(Duration.fromSecondsJ(1)); Assert.assertEquals(4, b.inSeconds()); } diff --git a/util-core/src/test/java/com/twitter/util/FutureCompilationTest.java b/util-core/src/test/java/com/twitter/util/FutureCompilationTest.java index 48cfe19075..8c490de8ba 100644 --- a/util-core/src/test/java/com/twitter/util/FutureCompilationTest.java +++ b/util-core/src/test/java/com/twitter/util/FutureCompilationTest.java @@ -14,14 +14,14 @@ public class FutureCompilationTest { @Test public void testBy() throws Exception { Future a = Future.value("23"); - Future b = a.by(new MockTimer(), Duration.fromSeconds(5).fromNow()); + Future b = a.by(new MockTimer(), Duration.fromSecondsJ(5).fromNow()); Assert.assertEquals(Await.result(a), Await.result(b)); } @Test public void testWithin() throws Exception { Future a = Future.value("23"); - Future b = a.within(new MockTimer(), Duration.fromSeconds(5)); + Future b = a.within(new MockTimer(), Duration.fromSecondsJ(5)); Assert.assertEquals(Await.result(a), Await.result(b)); } diff --git a/util-core/src/test/java/com/twitter/util/TimeCompilationTest.java b/util-core/src/test/java/com/twitter/util/TimeCompilationTest.java index 810e568407..009d96332b 100644 --- a/util-core/src/test/java/com/twitter/util/TimeCompilationTest.java +++ b/util-core/src/test/java/com/twitter/util/TimeCompilationTest.java @@ -23,8 +23,8 @@ public void testTopAndBottom() { @Test public void testUndefined() { Time a = Time.Undefined(); - Time b = Time.fromSeconds(99); - Time c = Time.fromSeconds(9999); + Time b = Time.fromSecondsJ(99); + Time c = Time.fromSecondsJ(9999); Assert.assertEquals(a, b.max(a)); Assert.assertEquals(c, c.min(a)); @@ -33,11 +33,11 @@ public void testUndefined() { @Test public void testFrom() { - Time a = Time.fromSeconds(1); - Time b = Time.fromMilliseconds(1000); - Time c = Time.fromMicroseconds(1000000); + Time a = Time.fromSecondsJ(1); + Time b = Time.fromMillisecondsJ(1000); + Time c = Time.fromMicrosecondsJ(1000000); Time d = Time.fromNanoseconds(1000000000); - Time e = Time.fromFractionalSeconds(1.0); + Time e = Time.fromFractionalSecondsJ(1.0); Assert.assertEquals(e, a); Assert.assertEquals(a, b); @@ -47,7 +47,7 @@ public void testFrom() { @Test public void testMinAndMax() { - Time a = Time.fromSeconds(9); + Time a = Time.fromSecondsJ(9); Time b = Time.fromNanoseconds(9); Assert.assertEquals(a, a.max(Time.Bottom())); @@ -58,9 +58,9 @@ public void testMinAndMax() { @Test public void testPlusAndMinus() { - Time a = Time.fromMilliseconds(3333); - Time b = a.plus(Duration.fromMilliseconds(2222)); - Time c = b.minus(Duration.fromMilliseconds(3333)); + Time a = Time.fromMillisecondsJ(3333); + Time b = a.plus(Duration.fromMillisecondsJ(2222)); + Time c = b.minus(Duration.fromMillisecondsJ(3333)); Assert.assertEquals(a, a.plus(Duration.Zero())); Assert.assertEquals(a, a.minus(Duration.Zero())); @@ -70,8 +70,8 @@ public void testPlusAndMinus() { @Test public void testDiff() { - Time a = Time.fromSeconds(6); - Time b = Time.fromMilliseconds(2000); + Time a = Time.fromSecondsJ(6); + Time b = Time.fromMillisecondsJ(2000); Assert.assertEquals(4000, a.diff(b).inMilliseconds()); } @@ -79,7 +79,7 @@ public void testDiff() { @Test public void testFloor() { Time a = Time.fromNanoseconds(8888); - Time b = a.floor(Duration.fromMicroseconds(1)); + Time b = a.floor(Duration.fromMicrosecondsJ(1)); Assert.assertEquals(8, b.inMicroseconds()); } @@ -87,16 +87,16 @@ public void testFloor() { @Test public void testCeil() { Time a = Time.fromNanoseconds(6666); - Time b = a.ceil(Duration.fromMicroseconds(1)); + Time b = a.ceil(Duration.fromMicrosecondsJ(1)); Assert.assertEquals(7, b.inMicroseconds()); } @Test public void testSince() { - Time a = Time.now().plus(Duration.fromSeconds(10)); - Time b = Time.epoch().plus(Duration.fromSeconds(10)); - Time c = Time.fromMilliseconds(0); + Time a = Time.now().plus(Duration.fromSecondsJ(10)); + Time b = Time.epoch().plus(Duration.fromSecondsJ(10)); + Time c = Time.fromMillisecondsJ(0); Assert.assertTrue(a.sinceNow().inSeconds() <= 10); Assert.assertTrue(b.sinceEpoch().inSeconds() <= 10); @@ -105,8 +105,8 @@ public void testSince() { @Test public void testUntil() { - Time a = Time.now().minus(Duration.fromMilliseconds(10)); - Time b = Time.epoch().minus(Duration.fromMilliseconds(10)); + Time a = Time.now().minus(Duration.fromMillisecondsJ(10)); + Time b = Time.epoch().minus(Duration.fromMillisecondsJ(10)); Time c = Time.fromNanoseconds(0); Assert.assertTrue(a.untilNow().inSeconds() <= 10); @@ -116,14 +116,14 @@ public void testUntil() { @Test public void testWithTimeAt() { - Time time = Time.fromMilliseconds(123456L); + Time time = Time.fromMillisecondsJ(123456L); Time.withTimeAt(time, func(timeControl -> { Assert.assertEquals(Time.now(), time); // you can control time via the `TimeControl` instance. - timeControl.advance(Duration.fromSeconds(2)); + timeControl.advance(Duration.fromSecondsJ(2)); FuturePools.unboundedPool().apply(func0(() -> { - assert(Time.now().equals(time.plus(Duration.fromSeconds(2)))); + assert(Time.now().equals(time.plus(Duration.fromSecondsJ(2)))); return BoxedUnit.UNIT; })); return null; diff --git a/util-core/src/test/java/com/twitter/util/TimerCompilationTest.java b/util-core/src/test/java/com/twitter/util/TimerCompilationTest.java index d560877759..0f50fd9e27 100644 --- a/util-core/src/test/java/com/twitter/util/TimerCompilationTest.java +++ b/util-core/src/test/java/com/twitter/util/TimerCompilationTest.java @@ -21,11 +21,11 @@ public String call() { public void testDoAt() { Time.withCurrentTimeFrozen(exfunc(timeControl -> { MockTimer timer = new MockTimer(); - Time at = Time.now().plus(Duration.fromMilliseconds(1)); + Time at = Time.now().plus(Duration.fromMillisecondsJ(1)); Future f = timer.doAt(at, Function.ofCallable(boom)); Assert.assertFalse(f.isDefined()); - timeControl.advance(Duration.fromMilliseconds(2)); + timeControl.advance(Duration.fromMillisecondsJ(2)); timer.tick(); Assert.assertTrue(f.isDefined()); Assert.assertEquals("boom", Await.result(f)); @@ -37,11 +37,11 @@ public void testDoAt() { public void testDoLater() throws Exception { Time.withCurrentTimeFrozen(exfunc(timeControl -> { MockTimer timer = new MockTimer(); - Future f = timer.doLater(Duration.fromMilliseconds(1), + Future f = timer.doLater(Duration.fromMillisecondsJ(1), Function.ofCallable(boom)); Assert.assertFalse(f.isDefined()); - timeControl.advance(Duration.fromMilliseconds(2)); + timeControl.advance(Duration.fromMillisecondsJ(2)); timer.tick(); Assert.assertTrue(f.isDefined()); Assert.assertEquals("boom", Await.result(f)); @@ -71,10 +71,10 @@ public void testScheduleWhen() { Time.withCurrentTimeFrozen(exfunc(timeControl -> { MockCounter counter = new MockCounter(); MockTimer timer = new MockTimer(); - Time when = Time.now().plus(Duration.fromMilliseconds(1)); + Time when = Time.now().plus(Duration.fromMillisecondsJ(1)); timer.schedule(when, Function.ofRunnable(counter.incrementer())); - timeControl.advance(Duration.fromMilliseconds(2)); + timeControl.advance(Duration.fromMillisecondsJ(2)); timer.tick(); Assert.assertEquals(1, counter.get()); return null; @@ -86,12 +86,12 @@ public void testCancelScheduleWhen() { Time.withCurrentTimeFrozen(exfunc(timeControl -> { MockCounter counter = new MockCounter(); MockTimer timer = new MockTimer(); - Time when = Time.now().plus(Duration.fromMilliseconds(1)); + Time when = Time.now().plus(Duration.fromMillisecondsJ(1)); TimerTask task = timer.schedule(when, Function.ofRunnable(counter.incrementer())); task.cancel(); - timeControl.advance(Duration.fromMilliseconds(2)); + timeControl.advance(Duration.fromMillisecondsJ(2)); timer.tick(); Assert.assertEquals(0, counter.get()); return null; diff --git a/util-core/src/test/java/com/twitter/util/TokenBucketCompilationTest.java b/util-core/src/test/java/com/twitter/util/TokenBucketCompilationTest.java index c60d48574c..c28bfb72c2 100644 --- a/util-core/src/test/java/com/twitter/util/TokenBucketCompilationTest.java +++ b/util-core/src/test/java/com/twitter/util/TokenBucketCompilationTest.java @@ -15,7 +15,7 @@ public void testBoundedBucket() throws Exception { @Test public void testLeakyBucket() throws Exception { - TokenBucket bucket = TokenBucket.newLeakyBucket(Duration.fromSeconds(3), 3); + TokenBucket bucket = TokenBucket.newLeakyBucket(Duration.fromSecondsJ(3), 3); bucket.put(3); bucket.tryGet(4); // don't check the value so we don't have to manipulate time bucket.count(); // don't check the value diff --git a/util-core/src/test/scala/com/twitter/concurrent/AsyncStreamTest.scala b/util-core/src/test/scala/com/twitter/concurrent/AsyncStreamTest.scala index 60b394610b..d46da25cb3 100644 --- a/util-core/src/test/scala/com/twitter/concurrent/AsyncStreamTest.scala +++ b/util-core/src/test/scala/com/twitter/concurrent/AsyncStreamTest.scala @@ -631,15 +631,15 @@ class AsyncStreamTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { } test(s"$impl: sum") { - forAll { xs: List[Int] => assert(xs.sum == await(fromSeq(xs).sum)) } + forAll { (xs: List[Int]) => assert(xs.sum == await(fromSeq(xs).sum)) } } test(s"$impl: size") { - forAll { xs: List[Int] => assert(xs.size == await(fromSeq(xs).size)) } + forAll { (xs: List[Int]) => assert(xs.size == await(fromSeq(xs).size)) } } test(s"$impl: force") { - forAll { xs: List[Int] => + forAll { (xs: List[Int]) => val p = new Promise[Unit] // The promise will be defined iff the tail is forced. val s = fromSeq(xs) ++ { p.setDone(); AsyncStream.empty } @@ -745,7 +745,7 @@ class AsyncStreamTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { val stream = tailRecM(0) { i => AsyncStream.of(if (i < n) Left(i + 1) else Right(i)) } - assert(Await.result(stream.toSeq) == Seq(n)) + assert(Await.result(stream.toSeq()) == Seq(n)) } } diff --git a/util-core/src/test/scala/com/twitter/conversions/StringOpsTest.scala b/util-core/src/test/scala/com/twitter/conversions/StringOpsTest.scala index f00df0459d..01aa321732 100644 --- a/util-core/src/test/scala/com/twitter/conversions/StringOpsTest.scala +++ b/util-core/src/test/scala/com/twitter/conversions/StringOpsTest.scala @@ -22,23 +22,23 @@ import org.scalatest.funsuite.AnyFunSuite class StringOpsTest extends AnyFunSuite { test("string#quoteC") { - assert("nothing".quoteC == "nothing") + assert("nothing".quoteC() == "nothing") assert( - "name\tvalue\t\u20acb\u00fcllet?\u20ac".quoteC == "name\\tvalue\\t\\u20acb\\xfcllet?\\u20ac" + "name\tvalue\t\u20acb\u00fcllet?\u20ac".quoteC() == "name\\tvalue\\t\\u20acb\\xfcllet?\\u20ac" ) - assert("she said \"hello\"".quoteC == "she said \\\"hello\\\"") - assert("\\backslash".quoteC == "\\\\backslash") + assert("she said \"hello\"".quoteC() == "she said \\\"hello\\\"") + assert("\\backslash".quoteC() == "\\\\backslash") } test("string#unquoteC") { - assert("nothing".unquoteC == "nothing") + assert("nothing".unquoteC() == "nothing") assert( - "name\\tvalue\\t\\u20acb\\xfcllet?\\u20ac".unquoteC == "name\tvalue\t\u20acb\u00fcllet?\u20ac" + "name\\tvalue\\t\\u20acb\\xfcllet?\\u20ac".unquoteC() == "name\tvalue\t\u20acb\u00fcllet?\u20ac" ) - assert("she said \\\"hello\\\"".unquoteC == "she said \"hello\"") - assert("\\\\backslash".unquoteC == "\\backslash") - assert("real\\$dollar".unquoteC == "real\\$dollar") - assert("silly\\/quote".unquoteC == "silly/quote") + assert("she said \\\"hello\\\"".unquoteC() == "she said \"hello\"") + assert("\\\\backslash".unquoteC() == "\\backslash") + assert("real\\$dollar".unquoteC() == "real\\$dollar") + assert("silly\\/quote".unquoteC() == "silly/quote") } test("string#hexlify") { @@ -47,10 +47,10 @@ class StringOpsTest extends AnyFunSuite { } test("string#unhexlify") { - assert("656c6c".unhexlify.toList == "hello".getBytes.slice(1, 4).toList) - assert("68656c6c6f".unhexlify.toList == "hello".getBytes.toList) - "5".unhexlify - assert("5".unhexlify.hexlify.toInt == 5) + assert("656c6c".unhexlify().toList == "hello".getBytes.slice(1, 4).toList) + assert("68656c6c6f".unhexlify().toList == "hello".getBytes.toList) + "5".unhexlify() + assert("5".unhexlify().hexlify.toInt == 5) } test("string#toCamelCase") { diff --git a/util-core/src/test/scala/com/twitter/conversions/U64OpsTest.scala b/util-core/src/test/scala/com/twitter/conversions/U64OpsTest.scala index a25f4cf076..942c41bb8c 100644 --- a/util-core/src/test/scala/com/twitter/conversions/U64OpsTest.scala +++ b/util-core/src/test/scala/com/twitter/conversions/U64OpsTest.scala @@ -7,11 +7,11 @@ class U64OpsTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { import com.twitter.conversions.U64Ops._ test("toU64HextString") { - forAll { l: Long => assert(l.toU64HexString == "%016x".format(l)) } + forAll { (l: Long) => assert(l.toU64HexString == "%016x".format(l)) } } test("toU64Long") { - forAll { l: Long => + forAll { (l: Long) => val s = "%016x".format(l) assert(s.toU64Long == java.lang.Long.parseUnsignedLong(s, 16)) } diff --git a/util-core/src/test/scala/com/twitter/io/BufByteWriterTest.scala b/util-core/src/test/scala/com/twitter/io/BufByteWriterTest.scala index c6bc755597..7b835ba818 100644 --- a/util-core/src/test/scala/com/twitter/io/BufByteWriterTest.scala +++ b/util-core/src/test/scala/com/twitter/io/BufByteWriterTest.scala @@ -33,7 +33,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC } def testWriteByte(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit = - test(s"$name: writeByte")(forAll { byte: Byte => + test(s"$name: writeByte")(forAll { (byte: Byte) => val bw = bwFactory() val buf = bw.writeByte(byte).owned() @@ -43,7 +43,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC }) def testWriteShort(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit = - test(s"$name: writeShort{BE,LE}")(forAll { s: Short => + test(s"$name: writeShort{BE,LE}")(forAll { (s: Short) => val be = bwFactory().writeShortBE(s) val le = bwFactory().writeShortLE(s) @@ -64,7 +64,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC }) def testWriteMedium(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit = - test(s"$name: writeMedium{BE,LE}")(forAll { m: Int => + test(s"$name: writeMedium{BE,LE}")(forAll { (m: Int) => val be = bwFactory().writeMediumBE(m) val le = bwFactory().writeMediumLE(m) @@ -86,7 +86,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC }) def testWriteInt(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit = - test(s"$name: writeInt{BE,LE}")(forAll { i: Int => + test(s"$name: writeInt{BE,LE}")(forAll { (i: Int) => val be = bwFactory().writeIntBE(i) val le = bwFactory().writeIntLE(i) @@ -109,7 +109,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC }) def testWriteLong(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit = - test(s"$name: writeLong{BE,LE}")(forAll { l: Long => + test(s"$name: writeLong{BE,LE}")(forAll { (l: Long) => val be = bwFactory().writeLongBE(l) val le = bwFactory().writeLongLE(l) @@ -136,7 +136,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC }) def testWriteFloat(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit = - test(s"$name: writeFloat{BE,LE}")(forAll { f: Float => + test(s"$name: writeFloat{BE,LE}")(forAll { (f: Float) => val be = bwFactory().writeFloatBE(f) val le = bwFactory().writeFloatLE(f) @@ -161,7 +161,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC }) def testWriteDouble(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit = - test(s"$name: writeDouble{BE,LE}")(forAll { d: Double => + test(s"$name: writeDouble{BE,LE}")(forAll { (d: Double) => val be = bwFactory().writeDoubleBE(d) val le = bwFactory().writeDoubleLE(d) @@ -195,9 +195,9 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC } test("trims unwritten bytes") { - assert(BufByteWriter.fixed(5).owned.length == 0) - assert(BufByteWriter.fixed(5).writeIntBE(1).owned.length == 4) - assert(BufByteWriter.fixed(4).writeIntBE(1).owned.length == 4) + assert(BufByteWriter.fixed(5).owned().length == 0) + assert(BufByteWriter.fixed(5).writeIntBE(1).owned().length == 4) + assert(BufByteWriter.fixed(4).writeIntBE(1).owned().length == 4) } testWriteString("fixed", size => BufByteWriter.fixed(size), overflowOK = false) @@ -209,7 +209,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC testWriteFloat("fixed", () => BufByteWriter.fixed(4), overflowOK = false) testWriteDouble("fixed", () => BufByteWriter.fixed(8), overflowOK = false) - test("fixed: writeBytes(Array[Byte])")(forAll { bytes: Array[Byte] => + test("fixed: writeBytes(Array[Byte])")(forAll { (bytes: Array[Byte]) => val bw = BufByteWriter.fixed(bytes.length) val buf = bw.writeBytes(bytes).owned() intercept[OverflowException] { bw.writeByte(0xff) } @@ -217,7 +217,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC assertIndex(bw, bytes.length) }) - test("fixed: writeBytes(Array[Byte]) 2 times")(forAll { bytes: Array[Byte] => + test("fixed: writeBytes(Array[Byte]) 2 times")(forAll { (bytes: Array[Byte]) => val bw = BufByteWriter.fixed(bytes.length * 2) val buf = bw.writeBytes(bytes).writeBytes(bytes).owned() intercept[OverflowException] { bw.writeByte(0xff) } @@ -226,7 +226,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC assertIndex(bw, bytes.length * 2) }) - test("fixed: writeBytes(Buf)")(forAll { arr: Array[Byte] => + test("fixed: writeBytes(Buf)")(forAll { (arr: Array[Byte]) => val bytes = Buf.ByteArray.Owned(arr) val bw = BufByteWriter.fixed(bytes.length) val buf = bw.writeBytes(bytes).owned() @@ -235,7 +235,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC assertIndex(bw, bytes.length) }) - test("fixed: writeBytes(Buf) 2 times")(forAll { arr: Array[Byte] => + test("fixed: writeBytes(Buf) 2 times")(forAll { (arr: Array[Byte]) => val bytes = Buf.ByteArray.Owned(arr) val bw = BufByteWriter.fixed(bytes.length * 2) val buf = bw.writeBytes(bytes).writeBytes(bytes).owned() @@ -263,20 +263,20 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC overflowOK = true ) - test("dynamic: writeBytes(Array[Byte])")(forAll { bytes: Array[Byte] => + test("dynamic: writeBytes(Array[Byte])")(forAll { (bytes: Array[Byte]) => val bw = BufByteWriter.dynamic() val buf = bw.writeBytes(bytes).owned() assert(buf == Buf.ByteArray.Owned(bytes)) }) - test("dynamic: writeBytes(Buf)")(forAll { arr: Array[Byte] => + test("dynamic: writeBytes(Buf)")(forAll { (arr: Array[Byte]) => val bytes = Buf.ByteArray.Owned(arr) val bw = BufByteWriter.dynamic() val buf = bw.writeBytes(bytes).owned() assert(buf == bytes) }) - test("dynamic: writeBytes(Array[Byte]) 3 times")(forAll { bytes: Array[Byte] => + test("dynamic: writeBytes(Array[Byte]) 3 times")(forAll { (bytes: Array[Byte]) => val bw = BufByteWriter.dynamic() val buf = bw .writeBytes(bytes) @@ -286,7 +286,7 @@ final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyC assert(buf == Buf.ByteArray.Owned(bytes ++ bytes ++ bytes)) }) - test("dynamic: writeBytes(Buf) 3 times")(forAll { arr: Array[Byte] => + test("dynamic: writeBytes(Buf) 3 times")(forAll { (arr: Array[Byte]) => val bytes = Buf.ByteArray.Owned(arr) val bw = BufByteWriter.dynamic() val buf = bw diff --git a/util-core/src/test/scala/com/twitter/io/BufReaderTest.scala b/util-core/src/test/scala/com/twitter/io/BufReaderTest.scala index c7bb9a4393..ccdca2b0aa 100644 --- a/util-core/src/test/scala/com/twitter/io/BufReaderTest.scala +++ b/util-core/src/test/scala/com/twitter/io/BufReaderTest.scala @@ -13,7 +13,7 @@ class BufReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { private def await[A](f: Future[A]): A = Await.result(f, 5.seconds) test("BufReader - apply(buf)") { - forAll { bytes: String => + forAll { (bytes: String) => val buf = Buf.Utf8(bytes) val r = BufReader(buf) assert(await(BufReader.readAll(r)) == buf) @@ -35,7 +35,7 @@ class BufReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { } test("BufReader - readAll") { - forAll { bytes: String => + forAll { (bytes: String) => val r = Reader.fromBuf(Buf.Utf8(bytes)) assert(await(BufReader.readAll(r)) == Buf.Utf8(bytes)) } @@ -85,7 +85,7 @@ class BufReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { } yield Buf.ByteArray.Owned(bytes) ) - forAll(getByteArrays) { buffers: Seq[Buf] => + forAll(getByteArrays) { (buffers: Seq[Buf]) => val buffersWithLength = buffers.map(buf => Buf.U32BE(buf.length).concat(buf)) val r = BufReader.framed(BufReader(Buf(buffersWithLength)), new BufReaderTest.U32BEFramer()) diff --git a/util-core/src/test/scala/com/twitter/io/BufTest.scala b/util-core/src/test/scala/com/twitter/io/BufTest.scala index c5156a3e3e..948c3b1293 100644 --- a/util-core/src/test/scala/com/twitter/io/BufTest.scala +++ b/util-core/src/test/scala/com/twitter/io/BufTest.scala @@ -1035,7 +1035,7 @@ class BufTest buf <- arbBuf.arbitrary } yield Buf(Seq.fill(n)(buf)) - forAll(Gen.listOf(bufGen)) { bufs: List[Buf] => + forAll(Gen.listOf(bufGen)) { (bufs: List[Buf]) => val concatLeft = bufs.foldLeft(Buf.Empty) { (l, r) => l.concat(r) } val concatRight = bufs.foldRight(Buf.Empty) { (l, r) => l.concat(r) } val constructor = Buf(bufs) diff --git a/util-core/src/test/scala/com/twitter/io/ByteReaderTest.scala b/util-core/src/test/scala/com/twitter/io/ByteReaderTest.scala index 1239a160df..9b0618fcc2 100644 --- a/util-core/src/test/scala/com/twitter/io/ByteReaderTest.scala +++ b/util-core/src/test/scala/com/twitter/io/ByteReaderTest.scala @@ -33,13 +33,13 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readByte")(forAll { byte: Byte => + test("readByte")(forAll { (byte: Byte) => val br = readerWith(byte) assert(br.readByte() == byte) intercept[UnderflowException] { br.readByte() } }) - test("readShortBE")(forAll { s: Short => + test("readShortBE")(forAll { (s: Short) => val br = readerWith( ((s >> 8) & 0xff).toByte, ((s) & 0xff).toByte @@ -50,7 +50,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readShortLE")(forAll { s: Short => + test("readShortLE")(forAll { (s: Short) => val br = readerWith( ((s) & 0xff).toByte, ((s >> 8) & 0xff).toByte @@ -62,7 +62,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readUnsignedMediumBE")(forAll { m: Int => + test("readUnsignedMediumBE")(forAll { (m: Int) => val br = readerWith( ((m >> 16) & 0xff).toByte, ((m >> 8) & 0xff).toByte, @@ -72,7 +72,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readUnsignedMediumLE")(forAll { m: Int => + test("readUnsignedMediumLE")(forAll { (m: Int) => val br = readerWith( ((m) & 0xff).toByte, ((m >> 8) & 0xff).toByte, @@ -82,7 +82,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readIntBE")(forAll { i: Int => + test("readIntBE")(forAll { (i: Int) => val br = readerWith( ((i >> 24) & 0xff).toByte, ((i >> 16) & 0xff).toByte, @@ -93,7 +93,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readIntLE")(forAll { i: Int => + test("readIntLE")(forAll { (i: Int) => val br = readerWith( ((i) & 0xff).toByte, ((i >> 8) & 0xff).toByte, @@ -104,7 +104,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readLongBE")(forAll { l: Long => + test("readLongBE")(forAll { (l: Long) => val br = readerWith( ((l >> 56) & 0xff).toByte, ((l >> 48) & 0xff).toByte, @@ -119,7 +119,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readLongLE")(forAll { l: Long => + test("readLongLE")(forAll { (l: Long) => val br = readerWith( ((l) & 0xff).toByte, ((l >> 8) & 0xff).toByte, @@ -134,41 +134,41 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readUnsignedByte")(forAll { b: Byte => + test("readUnsignedByte")(forAll { (b: Byte) => val br = new ByteReaderImpl(Buf.Empty) { override def readByte() = b } assert(br.readUnsignedByte() == (b & 0xff)) }) - test("readUnsignedShortBE")(forAll { s: Short => + test("readUnsignedShortBE")(forAll { (s: Short) => val br = new ByteReaderImpl(Buf.Empty) { override def readShortBE() = s } assert(br.readUnsignedShortBE() == (s & 0xffff)) }) - test("readUnsignedShortLE")(forAll { s: Short => + test("readUnsignedShortLE")(forAll { (s: Short) => val br = new ByteReaderImpl(Buf.Empty) { override def readShortLE() = s } assert(br.readUnsignedShortLE() == (s & 0xffff)) }) - test("readMediumBE")(forAll { i: Int => + test("readMediumBE")(forAll { (i: Int) => val m = maskMedium(i) val br = new ByteReaderImpl(Buf.Empty) { override def readUnsignedMediumBE() = m } val expected = if (m > SignedMediumMax) m | 0xff000000 else m assert(br.readMediumBE() == expected) }) - test("readMediumLE")(forAll { i: Int => + test("readMediumLE")(forAll { (i: Int) => val m = maskMedium(i) val br = new ByteReaderImpl(Buf.Empty) { override def readUnsignedMediumLE() = m } val expected = if (m > SignedMediumMax) m | 0xff000000 else m assert(br.readMediumLE() == expected) }) - test("readUnsignedIntBE")(forAll { i: Int => + test("readUnsignedIntBE")(forAll { (i: Int) => val br = new ByteReaderImpl(Buf.Empty) { override def readIntBE() = i } assert(br.readUnsignedIntBE() == (i & 0xffffffffL)) }) - test("readUnsignedIntLE")(forAll { i: Int => + test("readUnsignedIntLE")(forAll { (i: Int) => val br = new ByteReaderImpl(Buf.Empty) { override def readIntLE() = i } assert(br.readUnsignedIntLE() == (i & 0xffffffffL)) }) @@ -177,7 +177,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { .chooseNum(Long.MinValue, Long.MaxValue) .map(x => BigInt(x) + BigInt(2).pow(63)) - test("readUnsignedLongBE")(forAll(uInt64s) { bi: BigInt => + test("readUnsignedLongBE")(forAll(uInt64s) { (bi: BigInt) => val br = readerWith( ((bi >> 56) & 0xff).toByte, ((bi >> 48) & 0xff).toByte, @@ -192,7 +192,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { intercept[UnderflowException] { br.readByte() } }) - test("readUnsignedLongLE")(forAll(uInt64s) { bi1: BigInt => + test("readUnsignedLongLE")(forAll(uInt64s) { (bi1: BigInt) => val bi = bi1.abs val br = readerWith( ((bi) & 0xff).toByte, @@ -209,27 +209,27 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { }) // .equals is required to handle NaN - test("readFloatBE")(forAll { i: Int => + test("readFloatBE")(forAll { (i: Int) => val br = new ByteReaderImpl(Buf.Empty) { override def readIntBE() = i } assert(br.readFloatBE().equals(JFloat.intBitsToFloat(i))) }) - test("readFloatLE")(forAll { i: Int => + test("readFloatLE")(forAll { (i: Int) => val br = new ByteReaderImpl(Buf.Empty) { override def readIntLE() = i } assert(br.readFloatLE().equals(JFloat.intBitsToFloat(i))) }) - test("readDoubleBE")(forAll { l: Long => + test("readDoubleBE")(forAll { (l: Long) => val br = new ByteReaderImpl(Buf.Empty) { override def readLongBE() = l } assert(br.readDoubleBE().equals(JDouble.longBitsToDouble(l))) }) - test("readDoubleLE")(forAll { l: Long => + test("readDoubleLE")(forAll { (l: Long) => val br = new ByteReaderImpl(Buf.Empty) { override def readLongLE() = l } assert(br.readDoubleLE().equals(JDouble.longBitsToDouble(l))) }) - test("readBytes")(forAll { bytes: Array[Byte] => + test("readBytes")(forAll { (bytes: Array[Byte]) => val buf = Buf.ByteArray.Owned(bytes ++ bytes) val br = ByteReader(buf) intercept[IllegalArgumentException] { br.readBytes(-1) } @@ -238,7 +238,7 @@ class ByteReaderTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { assert(br.readBytes(1) == Buf.Empty) }) - test("readAll")(forAll { bytes: Array[Byte] => + test("readAll")(forAll { (bytes: Array[Byte]) => val buf = Buf.ByteArray.Owned(bytes ++ bytes) val br = ByteReader(buf) assert(br.readAll() == Buf.ByteArray.Owned(bytes ++ bytes)) diff --git a/util-core/src/test/scala/com/twitter/io/IteratorReaderTest.scala b/util-core/src/test/scala/com/twitter/io/IteratorReaderTest.scala index c40715fbc4..2f059a27d5 100644 --- a/util-core/src/test/scala/com/twitter/io/IteratorReaderTest.scala +++ b/util-core/src/test/scala/com/twitter/io/IteratorReaderTest.scala @@ -10,14 +10,14 @@ class IteratorReaderTest extends AnyFunSuite with Checkers { private def await[A](f: Future[A]): A = Await.result(f, 5.seconds) test("IteratorReader") { - check { list: List[String] => + check { (list: List[String]) => val r = Reader.fromIterator(list.iterator) await(Reader.readAllItems(r)).mkString == list.mkString } } test("IteratorReader - discard") { - check { list: List[String] => + check { (list: List[String]) => val r = Reader.fromIterator(list.iterator) r.discard() diff --git a/util-core/src/test/scala/com/twitter/io/ReaderTest.scala b/util-core/src/test/scala/com/twitter/io/ReaderTest.scala index 1773df41cd..f5ad20e460 100644 --- a/util-core/src/test/scala/com/twitter/io/ReaderTest.scala +++ b/util-core/src/test/scala/com/twitter/io/ReaderTest.scala @@ -62,7 +62,7 @@ class ReaderTest } test("Reader.concat collection of readers") { - forAll { ss: List[String] => + forAll { (ss: List[String]) => val readers: List[Reader[String]] = ss.map(s => Reader.value(s)) val concatedReaders = Reader.concat(readers) val values = Reader.readAllItems(concatedReaders) @@ -71,7 +71,7 @@ class ReaderTest } test("Reader.concat from a collection won't force the stream") { - forAll { ss: List[String] => + forAll { (ss: List[String]) => val readers: List[Reader[String]] = ss.map(s => Reader.value(s)) val head = Reader.value("hmm") Reader.concat(head +: readers) @@ -80,7 +80,7 @@ class ReaderTest } test("Reader.concat from a stream of readers") { - forAll { ss: List[String] => + forAll { (ss: List[String]) => val readers: List[Reader[String]] = ss.map(s => Reader.value(s)) val concatedReaders = Reader.concat(AsyncStream.fromSeq(readers)) val values = Reader.readAllItems(concatedReaders) @@ -89,7 +89,7 @@ class ReaderTest } test("Reader.concat from a stream of readers forces the stream") { - forAll { ss: List[String] => + forAll { (ss: List[String]) => val readers: List[Reader[String]] = ss.map(s => Reader.value(s)) val head = Reader.value("hmm") Reader.concat(AsyncStream.fromSeq(head +: readers)) @@ -154,7 +154,7 @@ class ReaderTest } test("Reader.flatten") { - forAll { ss: List[String] => + forAll { (ss: List[String]) => val readers: List[Reader[String]] = ss.map(s => Reader.value(s)) val value = Reader.readAllItems(Reader.flatten(Reader.fromSeq(readers))) assert(await(value) == ss) @@ -162,7 +162,7 @@ class ReaderTest } test("Reader#flatten") { - forAll { ss: List[String] => + forAll { (ss: List[String]) => val readers: List[Reader[String]] = ss.map(s => Reader.value(s)) val buf = Reader.readAllItems((Reader.fromSeq(readers).flatten)) assert(await(buf) == ss) @@ -249,7 +249,7 @@ class ReaderTest val r1 = Reader.value(1) val p2 = new Promise - val i2 = p2.interruptible + val i2 = p2.interruptible() val r2 = Reader.fromFuture(i2) def rStreams: Stream[Reader[Any]] = r1 #:: r2 #:: rStreams @@ -331,7 +331,7 @@ class ReaderTest } test("Reader.toAsyncStream") { - forAll { l: List[Byte] => + forAll { (l: List[Byte]) => val buf = Buf.ByteArray.Owned(l.toArray) val as = Reader.toAsyncStream(Reader.fromBuf(buf, 1)) @@ -340,7 +340,7 @@ class ReaderTest } test("Reader.flatMap") { - forAll { s: String => + forAll { (s: String) => val reader1 = Reader.fromBuf(Buf.Utf8(s), 8) val reader2 = reader1.flatMap { buf => val pipe = new Pipe[Buf] @@ -429,7 +429,7 @@ class ReaderTest } test("Reader.value") { - forAll { a: AnyVal => + forAll { (a: AnyVal) => val r = Reader.value(a) assert(await(r.read()) == Some(a)) assert(r.onClose.isDefined == false) @@ -439,7 +439,7 @@ class ReaderTest } test("Reader.exception") { - forAll { ex: Exception => + forAll { (ex: Exception) => val r = Reader.exception(ex) val exr = intercept[Exception] { await(r.read()) @@ -467,7 +467,7 @@ class ReaderTest } test("Reader.map") { - forAll { l: List[Int] => + forAll { (l: List[Int]) => val pipe = new Pipe[Int] writeLoop(l, pipe) val reader2 = pipe.map(_.toString) diff --git a/util-core/src/test/scala/com/twitter/util/ActivityTest.scala b/util-core/src/test/scala/com/twitter/util/ActivityTest.scala index 44693c17ac..d0d6a05713 100644 --- a/util-core/src/test/scala/com/twitter/util/ActivityTest.scala +++ b/util-core/src/test/scala/com/twitter/util/ActivityTest.scala @@ -85,24 +85,24 @@ class ActivityTest extends AnyFunSuite { } test("Activity.future: produce an initially-pending Activity") { - assert(Activity.future(Future.never).run.sample == Activity.Pending) + assert(Activity.future(Future.never).run.sample() == Activity.Pending) } test("Activity.future: produce an Activity that completes on success of the original Future") { val p = new Promise[Int] val act = Activity.future(p) - assert(act.run.sample == Activity.Pending) + assert(act.run.sample() == Activity.Pending) p.setValue(4) - assert(act.run.sample == Activity.Ok(4)) + assert(act.run.sample() == Activity.Ok(4)) } test("Activity.future: produce an Activity that fails on failure of the original Future") { val p = new Promise[Unit] val e = new Exception("gooby pls") val act = Activity.future(p) - assert(act.run.sample == Activity.Pending) + assert(act.run.sample() == Activity.Pending) p.setException(e) - assert(act.run.sample == Activity.Failed(e)) + assert(act.run.sample() == Activity.Failed(e)) } test( @@ -326,7 +326,7 @@ class ActivityTest extends AnyFunSuite { def register(witness: Witness[Activity.State[Int]]): Closable = { count += 1 w = witness - Closable.make { deadline: Time => + Closable.make { (deadline: Time) => count -= 1 w = null Future.Done diff --git a/util-core/src/test/scala/com/twitter/util/Base64LongTest.scala b/util-core/src/test/scala/com/twitter/util/Base64LongTest.scala index e90007845a..a8c3422153 100644 --- a/util-core/src/test/scala/com/twitter/util/Base64LongTest.scala +++ b/util-core/src/test/scala/com/twitter/util/Base64LongTest.scala @@ -65,7 +65,7 @@ class Base64LongTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { assert(toBase64(0) == "A") val b = new StringBuilder - forAll { a: Alphabet => + forAll { (a: Alphabet) => b.setLength(0) toBase64(b, 0, a) assert(b.result == a(0).toString) @@ -77,7 +77,7 @@ class Base64LongTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { } test("toBase64 uses the expected number of digits") { - BoundaryValues.foreach { n: Long => assert(toBase64(n).length == expectedLength(n)) } + BoundaryValues.foreach { (n: Long) => assert(toBase64(n).length == expectedLength(n)) } forAll((n: Long) => assert(toBase64(n).length == expectedLength(n))) val b = new StringBuilder diff --git a/util-core/src/test/scala/com/twitter/util/CancellableTest.scala b/util-core/src/test/scala/com/twitter/util/CancellableTest.scala index 14d150218d..8b23f172f9 100644 --- a/util-core/src/test/scala/com/twitter/util/CancellableTest.scala +++ b/util-core/src/test/scala/com/twitter/util/CancellableTest.scala @@ -21,7 +21,7 @@ class CancellableTest extends AnyFunSuite { test("CancellableSink cancel normal case") { var count = 2 def square(): Unit = count *= count - val s = new CancellableSink(square) + val s = new CancellableSink(square()) assert(count == 2) s.cancel() assert(count == 4) @@ -30,7 +30,7 @@ class CancellableTest extends AnyFunSuite { test("CancellableSink cancel once") { var count = 0 def increment(): Unit = count += 1 - val s = new CancellableSink(increment) + val s = new CancellableSink(increment()) s.cancel() assert(count == 1) s.cancel() @@ -40,7 +40,7 @@ class CancellableTest extends AnyFunSuite { test("CancellableSink has not cancelled") { var count = 0 def increment(): Unit = count += 1 - val s = new CancellableSink(increment) + val s = new CancellableSink(increment()) assert(!s.isCancelled) assert(count == 0) } @@ -48,7 +48,7 @@ class CancellableTest extends AnyFunSuite { test("CancellableSink confirm cancelled") { var count = 0 def increment(): Unit = count += 1 - val s = new CancellableSink(increment) + val s = new CancellableSink(increment()) s.cancel() assert(s.isCancelled) assert(count == 1) @@ -57,8 +57,8 @@ class CancellableTest extends AnyFunSuite { test("CancellableSink not support linking") { var count = 1 def multiply(): Unit = count *= 2 - val s1 = new CancellableSink(multiply) - val s2 = new CancellableSink(multiply) + val s1 = new CancellableSink(multiply()) + val s2 = new CancellableSink(multiply()) assertThrows[Exception] { s1.linkTo(s2) } diff --git a/util-core/src/test/scala/com/twitter/util/ClosableTest.scala b/util-core/src/test/scala/com/twitter/util/ClosableTest.scala index a485a75941..af40791e9a 100644 --- a/util-core/src/test/scala/com/twitter/util/ClosableTest.scala +++ b/util-core/src/test/scala/com/twitter/util/ClosableTest.scala @@ -78,7 +78,7 @@ class ClosableTest extends AnyFunSuite with Eventually with IntegrationPatience test("Closable.all with exceptions") { val throwing = Closable.make(_ => sys.error("lolz")) - val tracking = new Closable { + val tracking: Closable { def calledClose: Boolean } = new Closable { @volatile var calledClose = false override def close(deadline: Time): Future[Unit] = { diff --git a/util-core/src/test/scala/com/twitter/util/DurationTest.scala b/util-core/src/test/scala/com/twitter/util/DurationTest.scala index 3342621b79..a49ac0c91e 100644 --- a/util-core/src/test/scala/com/twitter/util/DurationTest.scala +++ b/util-core/src/test/scala/com/twitter/util/DurationTest.scala @@ -19,7 +19,7 @@ package com.twitter.util import com.twitter.conversions.DurationOps._ import java.util.concurrent.TimeUnit -class DurationTest extends { val ops: Duration.type = Duration } with TimeLikeSpec[Duration] { +class DurationTest extends TimeLikeSpec[Duration](ops = Duration) { "Duration" should { "*" in { diff --git a/util-core/src/test/scala/com/twitter/util/FutureTest.scala b/util-core/src/test/scala/com/twitter/util/FutureTest.scala index 954ee649d1..f981eb7722 100644 --- a/util-core/src/test/scala/com/twitter/util/FutureTest.scala +++ b/util-core/src/test/scala/com/twitter/util/FutureTest.scala @@ -901,8 +901,8 @@ class FutureTest extends AnyWordSpec with MockitoSugar with ScalaCheckDrivenProp } } - testJavaFuture("toJavaFuture", { f: Future[Int] => f.toJavaFuture }) - testJavaFuture("toCompletableFuture", { f: Future[Int] => f.toCompletableFuture }) + testJavaFuture("toJavaFuture", { (f: Future[Int]) => f.toJavaFuture }) + testJavaFuture("toCompletableFuture", { (f: Future[Int]) => f.toCompletableFuture }) "monitored" should { trait MonitoredHelper { diff --git a/util-core/src/test/scala/com/twitter/util/LastWriteWinsQueueTest.scala b/util-core/src/test/scala/com/twitter/util/LastWriteWinsQueueTest.scala index 73fab075e8..2d61bbe02d 100644 --- a/util-core/src/test/scala/com/twitter/util/LastWriteWinsQueueTest.scala +++ b/util-core/src/test/scala/com/twitter/util/LastWriteWinsQueueTest.scala @@ -10,7 +10,7 @@ class LastWriteWinsQueueTest extends AnyWordSpec { assert(queue.size == 0) queue.add("1") assert(queue.size == 1) - assert(queue.remove() == "1") + assert(queue.remove == "1") assert(queue.size == 0) } diff --git a/util-core/src/test/scala/com/twitter/util/MemoizeTest.scala b/util-core/src/test/scala/com/twitter/util/MemoizeTest.scala index 2294a8fbab..c84ca34614 100644 --- a/util-core/src/test/scala/com/twitter/util/MemoizeTest.scala +++ b/util-core/src/test/scala/com/twitter/util/MemoizeTest.scala @@ -47,7 +47,7 @@ class MemoizeTest extends AnyFunSuite { val callCount = new AtomicInteger(0) val startUpLatch = new JavaCountDownLatch(1) - val memoizer = Memoize { i: Int => + val memoizer = Memoize { (i: Int) => // Wait for all of the threads to be started before // continuing. This gives races a chance to happen. startUpLatch.await() @@ -85,7 +85,7 @@ class MemoizeTest extends AnyFunSuite { // A computation that should fail the first time, and then // succeed for all subsequent attempts. - val memo = Memoize { i: Int => + val memo = Memoize { (i: Int) => // Ensure that all of the callers have been started startUpLatch.await(200, TimeUnit.MILLISECONDS) // This effect should happen once per exception plus once for diff --git a/util-core/src/test/scala/com/twitter/util/StorageUnitTest.scala b/util-core/src/test/scala/com/twitter/util/StorageUnitTest.scala index 3a42c01e27..a057a6ae1d 100644 --- a/util-core/src/test/scala/com/twitter/util/StorageUnitTest.scala +++ b/util-core/src/test/scala/com/twitter/util/StorageUnitTest.scala @@ -22,11 +22,11 @@ class StorageUnitTest extends AnyFunSuite { } test("StorageUnit: should confer an essential humanity") { - assert(900.bytes.toHuman == "900 B") - assert(1.kilobyte.toHuman == "1024 B") - assert(2.kilobytes.toHuman == "2.0 KiB") - assert(Int.MaxValue.bytes.toHuman == "2.0 GiB") - assert(Long.MaxValue.bytes.toHuman == "8.0 EiB") + assert(900.bytes.toHuman() == "900 B") + assert(1.kilobyte.toHuman() == "1024 B") + assert(2.kilobytes.toHuman() == "2.0 KiB") + assert(Int.MaxValue.bytes.toHuman() == "2.0 GiB") + assert(Long.MaxValue.bytes.toHuman() == "8.0 EiB") } test("StorageUnit: should handle Long value") { @@ -51,7 +51,7 @@ class StorageUnitTest extends AnyFunSuite { test("StorageUnit: should deal with negative values") { assert(-123.bytes.inBytes == -123) - assert(-2.kilobytes.toHuman == "-2.0 KiB") + assert(-2.kilobytes.toHuman() == "-2.0 KiB") } test("StorageUnit: should min properly") { diff --git a/util-core/src/test/scala/com/twitter/util/TimeTest.scala b/util-core/src/test/scala/com/twitter/util/TimeTest.scala index 62a3d3a237..815006c042 100644 --- a/util-core/src/test/scala/com/twitter/util/TimeTest.scala +++ b/util-core/src/test/scala/com/twitter/util/TimeTest.scala @@ -10,8 +10,7 @@ import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import com.twitter.conversions.DurationOps._ import org.scalatest.wordspec.AnyWordSpec -trait TimeLikeSpec[T <: TimeLike[T]] extends AnyWordSpec with ScalaCheckDrivenPropertyChecks { - val ops: TimeLikeOps[T] +class TimeLikeSpec[T <: TimeLike[T]](val ops: TimeLikeOps[T]) extends AnyWordSpec with ScalaCheckDrivenPropertyChecks { import ops._ "Top, Bottom, Undefined, Nanoseconds(_), Finite(_)" should { @@ -395,7 +394,7 @@ class TimeFormatTest extends AnyWordSpec { } } -class TimeTest extends { val ops: Time.type = Time } with TimeLikeSpec[Time] with Eventually +class TimeTest extends TimeLikeSpec[Time](ops = Time) with Eventually with IntegrationPatience { "Time" should { @@ -600,13 +599,13 @@ with IntegrationPatience { "fromFractionalSeconds" in { val tolerance = 2.microseconds // we permit 1us slop - forAll { i: Int => + forAll { (i: Int) => assert( Time.fromSeconds(i).moreOrLessEquals(Time.fromFractionalSeconds(i.toDouble), tolerance) ) } - forAll { d: Double => + forAll { (d: Double) => val magic = 9223372036854775L // cribbed from Time.fromMicroseconds val microseconds = d * 1.second.inMicroseconds whenever(microseconds > -magic && microseconds < magic) { @@ -618,7 +617,7 @@ with IntegrationPatience { } } - forAll { l: Long => + forAll { (l: Long) => val seconds: Double = l.toDouble / 1.second.inNanoseconds assert( Time.fromFractionalSeconds(seconds).moreOrLessEquals(Time.fromNanoseconds(l), tolerance) diff --git a/util-core/src/test/scala/com/twitter/util/VarTest.scala b/util-core/src/test/scala/com/twitter/util/VarTest.scala index d3eb6b8dd9..040d33907d 100644 --- a/util-core/src/test/scala/com/twitter/util/VarTest.scala +++ b/util-core/src/test/scala/com/twitter/util/VarTest.scala @@ -225,7 +225,7 @@ class VarTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { } test("Var.collect: empty") { - assert(Var.collect(List.empty[Var[Int]]).sample == Nil) + assert(Var.collect(List.empty[Var[Int]]).sample() == Nil) } test("Var.collect[Seq]") { @@ -451,7 +451,7 @@ class VarTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks { // in order to avoid extremely long runtimes, we limit the max size // of the generated Seqs and Sets. A limit of 50 keeps runtime below // 1 second on my crufty old laptop. - implicit val generatorDrivenConfig = PropertyCheckConfiguration(sizeRange = 50) + implicit val generatorDrivenConfig: PropertyCheckConfiguration = PropertyCheckConfiguration(sizeRange = 50) forAll(arbitrary[Seq[Set[Int]]].suchThat(_.nonEmpty)) { sets => val v = Var(sets.head) From 8e91b84e6f25e0f5fed7ef2ac550567ba35ba46d Mon Sep 17 00:00:00 2001 From: Felix Bruckmeier Date: Sat, 29 May 2021 15:30:12 +0200 Subject: [PATCH 3/7] WIP Make util-core tests pass --- .../scala/com/twitter/util/CloseOnce.scala | 2 +- .../main/scala/com/twitter/util/Promise.scala | 56 +++++++++---------- .../scala/com/twitter/util/TimerTest.scala | 2 +- 3 files changed, 27 insertions(+), 33 deletions(-) diff --git a/util-core/src/main/scala/com/twitter/util/CloseOnce.scala b/util-core/src/main/scala/com/twitter/util/CloseOnce.scala index f27ea6aca6..f36e261b72 100644 --- a/util-core/src/main/scala/com/twitter/util/CloseOnce.scala +++ b/util-core/src/main/scala/com/twitter/util/CloseOnce.scala @@ -55,7 +55,7 @@ trait CloseOnce { self: Closable => */ final def isClosed: Boolean = closed - override final def close(deadline: Time): Future[Unit] = { + override def close(deadline: Time): Future[Unit] = { // only call `closeOnce()` and assign `closePromise` if this is the first `close()` invocation if (firstCloseInvoked()) { try { diff --git a/util-core/src/main/scala/com/twitter/util/Promise.scala b/util-core/src/main/scala/com/twitter/util/Promise.scala index 7d776fa7c5..f05217a495 100644 --- a/util-core/src/main/scala/com/twitter/util/Promise.scala +++ b/util-core/src/main/scala/com/twitter/util/Promise.scala @@ -1,6 +1,8 @@ package com.twitter.util import com.twitter.concurrent.Scheduler + +import java.util.concurrent.atomic.{AtomicInteger, AtomicReference} import scala.annotation.tailrec import scala.runtime.NonLocalReturnControl import scala.util.control.NonFatal @@ -184,11 +186,10 @@ object Promise { with (Try[A] => Unit) { // 0 represents not yet detached, 1 represents detached. - @volatile - private[this] var alreadyDetached: Int = 0 + private[this] val alreadyDetached: AtomicInteger = new AtomicInteger(0) def detach(): Boolean = - unsafe.compareAndSwapInt(this, detachedFutureOffset, 0, 1) + alreadyDetached.compareAndSet(0, 1) def apply(result: Try[A]): Unit = if (detach()) update(result) @@ -306,13 +307,6 @@ object Promise { */ private class Interrupted[A](val waitq: WaitQueue[A], val signal: Throwable) - private val unsafe: sun.misc.Unsafe = Unsafe() - private val stateOff: Long = - unsafe.objectFieldOffset(classOf[Promise[_]].getDeclaredField("state")) - - private val detachedFutureOffset: Long = - unsafe.objectFieldOffset(classOf[DetachableFuture[_]].getDeclaredField("alreadyDetached")) - private val AlwaysUnit: Any => Unit = _ => () sealed trait Responder[A] { this: Future[A] => @@ -467,26 +461,26 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ // - Transforming // - Try[A] (Done) // - Promise[A] - @volatile private[this] var state: Any = WaitQueue.empty[A] - private def theState(): Any = state + private[this] val state: AtomicReference[Any] = new AtomicReference[Any](WaitQueue.empty[A]) + private def theState(): Any = state.get() private[util] def this(forwardInterrupts: Future[_]) = { this() - this.state = new Transforming[A](WaitQueue.empty, forwardInterrupts) + this.state.set(new Transforming[A](WaitQueue.empty, forwardInterrupts)) } def this(handleInterrupt: PartialFunction[Throwable, Unit]) = { this() - this.state = new Interruptible[A](WaitQueue.empty, handleInterrupt, Local.save()) + this.state.set(new Interruptible[A](WaitQueue.empty, handleInterrupt, Local.save())) } def this(result: Try[A]) = { this() - this.state = result + this.state.set(result) } override def toString: String = { - val theState = state match { + val theState = state.get() match { case waitq: WaitQueue[A] => s"Waiting($waitq)" case s: Interruptible[A] => s"Interruptible(${s.waitq},${s.handler})" case s: Transforming[A] => s"Transforming(${s.waitq},${s.other})" @@ -498,7 +492,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ } @inline private[this] def cas(oldState: Any, newState: Any): Boolean = - unsafe.compareAndSwapObject(this, stateOff, oldState, newState) + state.compareAndSet(oldState, newState) /** * (Re)sets the interrupt handler. There is only @@ -507,7 +501,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ * @param f the new interrupt handler */ @tailrec - final def setInterruptHandler(f: PartialFunction[Throwable, Unit]): Unit = state match { + final def setInterruptHandler(f: PartialFunction[Throwable, Unit]): Unit = state.get() match { case waitq: WaitQueue[A] => if (!cas(waitq, new Interruptible(waitq, f, Local.save()))) setInterruptHandler(f) @@ -529,7 +523,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ } // Useful for debugging waitq. - private[util] def waitqLength: Int = state match { + private[util] def waitqLength: Int = state.get() match { case waitq: WaitQueue[A] => waitq.size case s: Interruptible[A] => s.waitq.size case s: Transforming[A] => s.waitq.size @@ -549,7 +543,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ @tailrec final def forwardInterruptsTo(other: Future[_]): Unit = { // This reduces allocations in the common case. if (other.isDefined) return - state match { + state.get() match { case waitq: WaitQueue[A] => if (!cas(waitq, new Transforming(waitq, other))) forwardInterruptsTo(other) @@ -571,7 +565,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ } } - final def raise(intr: Throwable): Unit = state match { + final def raise(intr: Throwable): Unit = state.get() match { case waitq: WaitQueue[A] => if (!cas(waitq, new Interrupted(waitq, intr))) raise(intr) @@ -601,7 +595,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ case p: Promise[A] /* Linked */ => p.raise(intr) } - @tailrec protected[Promise] final def detach(k: K[A]): Boolean = state match { + @tailrec protected[Promise] final def detach(k: K[A]): Boolean = state.get() match { case waitq: WaitQueue[A] => if (!cas(waitq, waitq.remove(k))) detach(k) @@ -634,7 +628,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ // Awaitable @throws(classOf[TimeoutException]) @throws(classOf[InterruptedException]) - def ready(timeout: Duration)(implicit permit: Awaitable.CanAwait): this.type = state match { + def ready(timeout: Duration)(implicit permit: Awaitable.CanAwait): this.type = state.get() match { case _: WaitQueue[A] | _: Interruptible[A] | _: Interrupted[A] | _: Transforming[A] => val condition = new ReleaseOnApplyCDL[A] respond(condition) @@ -668,7 +662,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ /** * Returns this promise's interrupt if it is interrupted. */ - def isInterrupted: Option[Throwable] = state match { + def isInterrupted: Option[Throwable] = state.get() match { case _: WaitQueue[A] | _: Interruptible[A] | _: Transforming[A] => None case s: Interrupted[A] => Some(s.signal) case _: Try[A] /* Done */ => None @@ -779,7 +773,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ * @return true only if the result is updated, false if it was already set. */ @tailrec - final def updateIfEmpty(result: Try[A]): Boolean = state match { + final def updateIfEmpty(result: Try[A]): Boolean = state.get() match { case waitq: WaitQueue[A] => if (!cas(waitq, result)) updateIfEmpty(result) else { @@ -812,7 +806,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ } @tailrec - protected final def continue(k: K[A]): Unit = state match { + protected final def continue(k: K[A]): Unit = state.get() match { case waitq: WaitQueue[A] => if (!cas(waitq, WaitQueue(k, waitq))) continue(k) @@ -833,12 +827,12 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ * Should only be called when this Promise has already been fulfilled * or it is becoming another Future via `become`. */ - protected final def compress(): Promise[A] = state match { + protected final def compress(): Promise[A] = state.get() match { case p: Promise[A] /* Linked */ => val target = p.compress() // due to the assumptions stated above regarding when this can be called, // there should never be a `cas` fail. - state = target + state.set(target) target case _ => this @@ -848,7 +842,7 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ protected final def link(target: Promise[A]): Unit = { if (this eq target) return - state match { + state.get() match { case waitq: WaitQueue[A] => if (!cas(waitq, target)) link(target) else target.continueAll(waitq) @@ -885,13 +879,13 @@ class Promise[A] extends Future[A] with Promise.Responder[A] with Updatable[Try[ } } - def poll: Option[Try[A]] = state match { + def poll: Option[Try[A]] = state.get() match { case res: Try[A] /* Done */ => Some(res) case p: Promise[A] /* Linked */ => p.poll case _ /* WaitQueue, Interruptible, Interrupted, or Transforming */ => None } - override def isDefined: Boolean = state match { + override def isDefined: Boolean = state.get() match { // Note: the basic implementation is the same as `poll()`, but we want to avoid doing // object allocations for `Some`s when the caller does not need the result. case _: Try[A] /* Done */ => true diff --git a/util-core/src/test/scala/com/twitter/util/TimerTest.scala b/util-core/src/test/scala/com/twitter/util/TimerTest.scala index aeb97c0026..ed4c4b6ee8 100644 --- a/util-core/src/test/scala/com/twitter/util/TimerTest.scala +++ b/util-core/src/test/scala/com/twitter/util/TimerTest.scala @@ -353,7 +353,7 @@ class TimerTest extends AnyFunSuite with MockitoSugar with Eventually with Integ assert(mockTimerLocalPropagation(timer, 99) == 99) } - private class SomeEx extends Exception + private case class SomeEx() extends Exception private def testTimerUsesLocalMonitor(timer: Timer): Unit = { val seen = new AtomicInteger(0) From 4fb258f0e8ddbf9c07dd1ee40c6fcfd1892f4c72 Mon Sep 17 00:00:00 2001 From: Felix Bruckmeier Date: Sat, 29 May 2021 15:40:50 +0200 Subject: [PATCH 4/7] WIP 2.13.6 green; 3.0.0 migration where possible --- util-app/src/main/scala/com/twitter/app/ClassPath.scala | 2 +- util-app/src/main/scala/com/twitter/app/Flaggable.scala | 8 ++++---- util-app/src/test/java/com/twitter/app/JavaFlagTest.java | 2 +- .../main/scala/com/twitter/cache/guava/GuavaCache.scala | 2 +- .../main/scala/com/twitter/cache/ConcurrentMapCache.scala | 2 +- .../src/main/scala/com/twitter/cache/FutureCache.scala | 2 +- .../scala/com/twitter/cache/caffeine/CaffeineCache.scala | 2 +- .../src/test/java/com/twitter/cache/JavaRefreshTest.java | 2 +- .../test/scala/com/twitter/cache/EvictingCacheTest.scala | 8 ++++---- .../scala/com/twitter/cache/KeyEncodingCacheTest.scala | 2 +- .../src/main/scala/com/twitter/hashing/Hashable.scala | 2 +- .../hashing/ConsistentHashingDistributorTest.scala | 8 ++++---- .../src/test/scala/com/twitter/hashing/HashableTest.scala | 2 +- .../src/main/scala/com/twitter/logging/FileHandler.scala | 4 ++-- .../src/main/scala/com/twitter/logging/Logger.scala | 4 ++-- .../com/twitter/util/routing/RouterBuilderTest.scala | 8 ++++---- .../util/security/X509CertificateDeserializer.scala | 2 +- .../src/main/scala/com/twitter/zk/NativeConnector.scala | 2 +- util-zk/src/main/scala/com/twitter/zk/ZNode.scala | 4 ++-- .../com/twitter/zk/coordination/ShardCoordinator.scala | 2 +- 20 files changed, 35 insertions(+), 35 deletions(-) diff --git a/util-app/src/main/scala/com/twitter/app/ClassPath.scala b/util-app/src/main/scala/com/twitter/app/ClassPath.scala index 261cfd4129..eb28fb15aa 100644 --- a/util-app/src/main/scala/com/twitter/app/ClassPath.scala +++ b/util-app/src/main/scala/com/twitter/app/ClassPath.scala @@ -71,7 +71,7 @@ private[app] sealed abstract class ClassPath[CpInfo <: ClassPath.Info] { // TODO - add suppport for the ModulePath after dropping JDK 8 support. private[this] def urlsFromClasspath(): Array[URL] = { val classpath: String = System.getProperty("java.class.path") - classpath.split(File.pathSeparator).map { pathEntry: String => + classpath.split(File.pathSeparator).map { (pathEntry: String) => Paths.get(pathEntry).toAbsolutePath().toUri().toURL } } diff --git a/util-app/src/main/scala/com/twitter/app/Flaggable.scala b/util-app/src/main/scala/com/twitter/app/Flaggable.scala index 43646031fd..d84696c59c 100644 --- a/util-app/src/main/scala/com/twitter/app/Flaggable.scala +++ b/util-app/src/main/scala/com/twitter/app/Flaggable.scala @@ -132,19 +132,19 @@ object Flaggable { implicit val ofInt: Flaggable[Int] = mandatory(_.toInt) implicit val ofJavaInteger: Flaggable[JInteger] = - mandatory { s: String => JInteger.valueOf(s.toInt) } + mandatory { (s: String) => JInteger.valueOf(s.toInt) } implicit val ofLong: Flaggable[Long] = mandatory(_.toLong) implicit val ofJavaLong: Flaggable[JLong] = - mandatory { s: String => JLong.valueOf(s.toLong) } + mandatory { (s: String) => JLong.valueOf(s.toLong) } implicit val ofFloat: Flaggable[Float] = mandatory(_.toFloat) implicit val ofJavaFloat: Flaggable[JFloat] = - mandatory { s: String => JFloat.valueOf(s.toFloat) } + mandatory { (s: String) => JFloat.valueOf(s.toFloat) } implicit val ofDouble: Flaggable[Double] = mandatory(_.toDouble) implicit val ofJavaDouble: Flaggable[JDouble] = - mandatory { s: String => JDouble.valueOf(s.toDouble) } + mandatory { (s: String) => JDouble.valueOf(s.toDouble) } // Conversions for common non-primitive types and collections. implicit val ofDuration: Flaggable[Duration] = mandatory(Duration.parse(_)) diff --git a/util-app/src/test/java/com/twitter/app/JavaFlagTest.java b/util-app/src/test/java/com/twitter/app/JavaFlagTest.java index 38d8fe5ac4..fe1ed8d813 100644 --- a/util-app/src/test/java/com/twitter/app/JavaFlagTest.java +++ b/util-app/src/test/java/com/twitter/app/JavaFlagTest.java @@ -60,7 +60,7 @@ public void testJavaFlags() { Flag floatFlag = flag.create("float", 1.0f, "", Flaggable.ofJavaFloat()); Flag doubleFlag = flag.create("double", 1.0d, "", Flaggable.ofJavaDouble()); Flag durationFlag = - flag.create("duration", Duration.fromSeconds(1), "", Flaggable.ofDuration()); + flag.create("duration", Duration.fromSecondsJ(1), "", Flaggable.ofDuration()); Flag StorageUnitFlag = flag.create("storage unit", StorageUnit.zero(), "", Flaggable.ofStorageUnit()); Flag