Skip to content

Commit

Permalink
Add TimeSource toClock converter
Browse files Browse the repository at this point in the history
  • Loading branch information
hfhbd committed Dec 15, 2021
1 parent 4895b49 commit b544b69
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
14 changes: 14 additions & 0 deletions core/common/src/Clock.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,17 @@ private class InstantTimeMark(private val instant: Instant, private val clock: C

override fun minus(duration: Duration): TimeMark = InstantTimeMark(instant - duration, clock)
}

/**
* Returns the [Clock] by storing an initial [TimeMark] using [TimeSource.markNow] and [returns][Clock.now] the elapsed
* time using [TimeMark.elapsedNow] plus the provided [offset].
*
* This clock stores the initial [TimeMark], so repeatedly creating [Clock]s from the same [TimeSource] results
* into different [Instant]s iff the time of the [TimeSource] was increased. To sync different [Clock]s, use the [offset]
* parameter.
*/
@ExperimentalTime
public fun TimeSource.toClock(offset: Instant = Instant.fromEpochSeconds(0)): Clock = object : Clock {
private val startMark: TimeMark = markNow()
override fun now() = offset + startMark.elapsedNow()
}
51 changes: 51 additions & 0 deletions core/common/test/ClockTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2019-2021 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/

package kotlinx.datetime.test

import kotlinx.datetime.*
import kotlin.test.*
import kotlin.time.*
import kotlin.time.Duration.Companion.seconds

@ExperimentalTime
class ClockTest {
@Test
fun timeSourceToClock() {
val timeSource = TestTimeSource()
val clock = timeSource.toClock()

assertEquals(Instant.fromEpochSeconds(0), clock.now())
assertEquals(Instant.fromEpochSeconds(0), clock.now())

timeSource += 1.seconds
assertEquals(Instant.fromEpochSeconds(1), clock.now())
assertEquals(Instant.fromEpochSeconds(1), clock.now())
}

@Test
fun syncMultipleClocksFromTimeSource() {
val timeSource = TestTimeSource()
val clock1 = timeSource.toClock()

assertEquals(0, clock1.now().epochSeconds)

timeSource += 1.seconds
assertEquals(1, clock1.now().epochSeconds)

val clock2 = timeSource.toClock(offset = Instant.fromEpochSeconds(1))
assertEquals(clock1.now(), clock2.now())

timeSource += 1.seconds
assertEquals(2, clock1.now().epochSeconds)
assertEquals(clock1.now(), clock2.now())

val clock3 = timeSource.toClock(offset = clock2.now())
timeSource += 1.seconds
assertEquals(3, clock3.now().epochSeconds)
assertEquals(clock1.now(), clock2.now())
assertEquals(clock1.now(), clock3.now())
}
}

0 comments on commit b544b69

Please sign in to comment.