Skip to content

Commit f9d69e3

Browse files
Add two more Duration extensions. (#145)
1 parent d5b1ca6 commit f9d69e3

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/main/kotlin/org/jitsi/utils/Duration.kt

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,15 +141,15 @@ fun durationOfDoubleSeconds(duration: Double): Duration {
141141
val secs = floor(duration)
142142
val ns = round((duration - secs) * 1e9)
143143
require(secs >= Long.MIN_VALUE.toDouble() && secs <= Long.MAX_VALUE.toDouble())
144-
/* For reasons I don't understand, the basic Duration(secs, ns) constructor is private. */
145-
return Duration.ofSeconds(secs.toLong()).plusNanos(ns.toLong())
144+
return Duration.ofSeconds(secs.toLong(), ns.toLong())
146145
}
147146

148147
val MIN_DURATION: Duration = Duration.ofSeconds(Long.MIN_VALUE, 0)
149148

150149
val MAX_DURATION: Duration = Duration.ofSeconds(Long.MAX_VALUE, 999_999_999)
151150

152151
fun Duration.isFinite() = this != MIN_DURATION && this != MAX_DURATION
152+
fun Duration.isInfinite() = !isFinite()
153153

154154
operator fun Duration.times(other: Double): Duration = durationOfDoubleSeconds((toDouble() * other))
155155
operator fun Double.times(other: Duration): Duration = durationOfDoubleSeconds(other.toDouble() * this)
@@ -160,6 +160,8 @@ operator fun Duration.div(other: Long): Duration = this.dividedBy(other)
160160

161161
operator fun Duration.unaryMinus(): Duration = this.negated()
162162

163+
fun abs(duration: Duration) = if (duration >= Duration.ZERO) duration else -duration
164+
163165
fun <T> Iterable<T>.sumOf(selector: (T) -> Duration): Duration {
164166
var sum: Duration = Duration.ZERO
165167
for (element in this) {

src/test/kotlin/org/jitsi/utils/DurationTest.kt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,11 @@ class DurationTest : ShouldSpec() {
7373
2200.micros.toDoubleMillis() shouldBe (2.2 plusOrMinus 1e-9)
7474
(-(2200.micros)).toDoubleMillis() shouldBe (-2.2 plusOrMinus 1e-9)
7575

76+
abs(2200.micros) shouldBe 2200.micros
77+
abs(-(2200.micros)) shouldBe 2200.micros
78+
abs((-2200).micros) shouldBe 2200.micros
79+
abs(Duration.ZERO) shouldBe Duration.ZERO
80+
7681
durationOfDoubleSeconds(2.2) shouldBe 2200.ms
7782

7883
durationOfDoubleSeconds(Long.MAX_VALUE.toDouble()).seconds shouldBe Long.MAX_VALUE
@@ -86,6 +91,10 @@ class DurationTest : ShouldSpec() {
8691
MAX_DURATION.isFinite() shouldBe false
8792
MIN_DURATION.isFinite() shouldBe false
8893

94+
2200.micros.isInfinite() shouldBe false
95+
MAX_DURATION.isInfinite() shouldBe true
96+
MIN_DURATION.isInfinite() shouldBe true
97+
8998
max(2200.ms, 3000.ms) shouldBe 3000.ms
9099
max(2200.ms, MAX_DURATION) shouldBe MAX_DURATION
91100
max(2200.ms, MIN_DURATION) shouldBe 2200.ms

0 commit comments

Comments
 (0)