summaryrefslogtreecommitdiff
path: root/src/library
diff options
context:
space:
mode:
authorAdriaan Moors <adriaan.moors@typesafe.com>2013-06-18 10:41:49 -0700
committerAdriaan Moors <adriaan.moors@typesafe.com>2013-06-18 10:41:49 -0700
commit97271ef9f75296d6b3b5ef10ec361c70591a6a27 (patch)
treed7fc44bc085f60dc7fdffa30a90de2ffcb39c782 /src/library
parent9736f97a9765dade23fef7131fa9b34229b5feef (diff)
parente3d3e1665d150869be4be40b9ce42690e9e9d247 (diff)
downloadscala-97271ef9f75296d6b3b5ef10ec361c70591a6a27.tar.gz
scala-97271ef9f75296d6b3b5ef10ec361c70591a6a27.tar.bz2
scala-97271ef9f75296d6b3b5ef10ec361c70591a6a27.zip
Merge pull request #2602 from t3hnar/Duration.toCoarsest
Add Duration.toCoarsest method
Diffstat (limited to 'src/library')
-rw-r--r--src/library/scala/concurrent/duration/Duration.scala36
1 files changed, 36 insertions, 0 deletions
diff --git a/src/library/scala/concurrent/duration/Duration.scala b/src/library/scala/concurrent/duration/Duration.scala
index a24266bf19..9a8844b489 100644
--- a/src/library/scala/concurrent/duration/Duration.scala
+++ b/src/library/scala/concurrent/duration/Duration.scala
@@ -221,6 +221,8 @@ object Duration {
final def toMinutes: Long = fail("toMinutes")
final def toHours: Long = fail("toHours")
final def toDays: Long = fail("toDays")
+
+ final def toCoarsest: Duration = this
}
/**
@@ -520,6 +522,18 @@ sealed abstract class Duration extends Serializable with Ordered[Duration] {
* $ovf
*/
def plus(other: Duration) = this + other
+ /**
+ * Return duration which is equal to this duration but with a coarsest Unit, or self in case it is already the coarsest Unit
+ * <p/>
+ * Examples:
+ * {{{
+ * Duration(60, MINUTES).toCoarsest // Duration(1, HOURS)
+ * Duration(1000, MILLISECONDS).toCoarsest // Duration(1, SECONDS)
+ * Duration(48, HOURS).toCoarsest // Duration(2, DAYS)
+ * Duration(5, SECONDS).toCoarsest // Duration(5, SECONDS)
+ * }}}
+ */
+ def toCoarsest: Duration
}
object FiniteDuration {
@@ -691,6 +705,28 @@ final class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duratio
final def isFinite() = true
+ final def toCoarsest: Duration = {
+ def loop(length: Long, unit: TimeUnit): FiniteDuration = {
+ def coarserOrThis(coarser: TimeUnit, divider: Int) =
+ if (length % divider == 0) loop(length / divider, coarser)
+ else if (unit == this.unit) this
+ else FiniteDuration(length, unit)
+
+ unit match {
+ case DAYS => FiniteDuration(length, unit)
+ case HOURS => coarserOrThis(DAYS, 24)
+ case MINUTES => coarserOrThis(HOURS, 60)
+ case SECONDS => coarserOrThis(MINUTES, 60)
+ case MILLISECONDS => coarserOrThis(SECONDS, 1000)
+ case MICROSECONDS => coarserOrThis(MILLISECONDS, 1000)
+ case NANOSECONDS => coarserOrThis(MICROSECONDS, 1000)
+ }
+ }
+
+ if (unit == DAYS || length == 0) this
+ else loop(length, unit)
+ }
+
override def equals(other: Any) = other match {
case x: FiniteDuration => toNanos == x.toNanos
case _ => super.equals(other)