Merge pull request #15156 from ktoso/tes-pretty-duration-inf
=tes #15155 prettyduration should work with infinity
This commit is contained in:
commit
641a1ce0fa
2 changed files with 30 additions and 13 deletions
|
|
@ -7,19 +7,25 @@ import scala.concurrent.duration._
|
|||
|
||||
object PrettyDuration {
|
||||
|
||||
implicit class PrettyPrintableDuration(val d: Duration) extends AnyVal {
|
||||
implicit class PrettyPrintableDuration(val duration: Duration) extends AnyVal {
|
||||
|
||||
def pretty: String = pretty(includeNanos = false)
|
||||
|
||||
/** Selects most apropriate TimeUnit for given duration and formats it accordingly */
|
||||
def pretty(includeNanos: Boolean, precision: Int = 2): String = {
|
||||
def pretty(includeNanos: Boolean, precision: Int = 4): String = {
|
||||
require(precision > 0, "precision must be > 0")
|
||||
|
||||
val nanos = d.toNanos
|
||||
val unit = chooseUnit(nanos)
|
||||
val value = nanos.toDouble / NANOSECONDS.convert(1, unit)
|
||||
duration match {
|
||||
case d: FiniteDuration ⇒
|
||||
val nanos = d.toNanos
|
||||
val unit = chooseUnit(nanos)
|
||||
val value = nanos.toDouble / NANOSECONDS.convert(1, unit)
|
||||
|
||||
s"%.${precision}g %s%s".format(value, abbreviate(unit), if (includeNanos) s" ($nanos ns)" else "")
|
||||
s"%.${precision}g %s%s".format(value, abbreviate(unit), if (includeNanos) s" ($nanos ns)" else "")
|
||||
|
||||
case d: Duration.Infinite if d == Duration.MinusInf ⇒ s" -∞ (minus infinity)"
|
||||
case d ⇒ s"∞ (infinity)"
|
||||
}
|
||||
}
|
||||
|
||||
def chooseUnit(nanos: Long): TimeUnit = {
|
||||
|
|
|
|||
|
|
@ -13,13 +13,16 @@ class PrettyDurationSpec extends FlatSpec with Matchers {
|
|||
import PrettyDuration._
|
||||
|
||||
val cases =
|
||||
95.nanos -> "95 ns" ::
|
||||
9500.nanos -> "9.5 μs" ::
|
||||
9500.micros -> "9.5 ms" ::
|
||||
9500.millis -> "9.5 s" ::
|
||||
95.seconds -> "1.6 min" ::
|
||||
95.minutes -> "1.6 h" ::
|
||||
95.hours -> "4.0 d" ::
|
||||
9.nanos -> "9.000 ns" ::
|
||||
95.nanos -> "95.00 ns" ::
|
||||
999.nanos -> "999.0 ns" ::
|
||||
1000.nanos -> "1.000 μs" ::
|
||||
9500.nanos -> "9.500 μs" ::
|
||||
9500.micros -> "9.500 ms" ::
|
||||
9500.millis -> "9.500 s" ::
|
||||
95.seconds -> "1.583 min" ::
|
||||
95.minutes -> "1.583 h" ::
|
||||
95.hours -> "3.958 d" ::
|
||||
Nil
|
||||
|
||||
cases foreach {
|
||||
|
|
@ -28,4 +31,12 @@ class PrettyDurationSpec extends FlatSpec with Matchers {
|
|||
d.pretty should equal(prettyString)
|
||||
}
|
||||
}
|
||||
|
||||
it should "work with infinity" in {
|
||||
Duration.Inf.pretty should include("infinity")
|
||||
}
|
||||
|
||||
it should "work with -infinity" in {
|
||||
Duration.MinusInf.pretty should include("minus infinity")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue