Files
swift-mirror/test/stdlib/Duration.swift
Stephen Canon db0a7287a5 Rework the .seconds, .milliseconds, and .microseconds constructors to preserve exact values (#66111)
When constructing a Duration from Double, we should do it in such a way that exact integer inputs are preserved exactly, so long as they are represented as a Duration. This was not previously the case. Now it is.
2023-05-24 23:07:17 -04:00

47 lines
1.7 KiB
Swift

// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
var suite = TestSuite("StringIndexTests")
defer { runAllTests() }
if #available(SwiftStdlib 5.7, *) {
suite.test("seconds from Double") {
for _ in 0 ..< 100 {
let integerValue = Double(Int64.random(in: 0 ... 0x7fff_ffff_ffff_fc00))
let (sec, attosec) = Duration.seconds(integerValue).components
expectEqual(sec, Int64(integerValue))
expectEqual(attosec, 0)
}
// Value that overflows conversion from Double -> Int64, but should be
// representable as a number of seconds:
let huge: Double = 1.7e20
let duration = Duration.seconds(huge)
// Divide by 1000 to get back to a duration with representable components:
let smallerDuration = duration / 1000
expectEqual(smallerDuration.components, (170_000_000_000_000_000, 0))
// Now check that the components of the original value trap:
expectCrashLater()
let _ = duration.components
}
suite.test("milliseconds from Double") {
for _ in 0 ..< 100 {
let integerValue = Double(Int64.random(in: 0 ... 0x7fff_ffff_ffff_fc00))
let (sec, attosec) = Duration.milliseconds(integerValue).components
expectEqual(sec, Int64(integerValue) / 1000)
expectEqual(attosec, Int64(integerValue) % 1000 * 1_000_000_000_000_000)
}
}
suite.test("microseconds from Double") {
for _ in 0 ..< 100 {
let integerValue = Double(Int64.random(in: 0 ... 0x7fff_ffff_ffff_fc00))
let (sec, attosec) = Duration.microseconds(integerValue).components
expectEqual(sec, Int64(integerValue) / 1_000_000)
expectEqual(attosec, Int64(integerValue) % 1_000_000 * 1_000_000_000_000)
}
}
}