Skip to content

Commit deb51ba

Browse files
committed
fix(interval): correct negative handling and validation
1 parent 41ef235 commit deb51ba

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

Sources/AsyncTimer/Interval.swift

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ public enum Interval: Sendable {
2525
case days(_: UInt64)
2626

2727
/// Nanoseconds presentation.
28+
///
29+
/// Note: Negative durations are treated as 0 to avoid accidental large UInt64 conversions.
2830
public var nanoseconds: UInt64 {
2931
switch self {
3032
case let .nanoseconds(value):
@@ -34,6 +36,7 @@ public enum Interval: Sendable {
3436
case let .milliseconds(value):
3537
return value * 1_000_000
3638
case let .seconds(value):
39+
if value <= 0 { return 0 }
3740
return UInt64(value * 1_000_000_000)
3841
case let .minutes(value):
3942
return value * 60 * 1_000_000_000
@@ -51,13 +54,38 @@ public enum Interval: Sendable {
5154
public static let infinite: Interval = .nanoseconds(UInt64.max)
5255

5356
/// Whether the interval is zero.
54-
public var isZero: Bool { nanoseconds == 0 }
57+
public var isZero: Bool {
58+
switch self {
59+
case let .nanoseconds(value): return value == 0
60+
case let .microseconds(value): return value == 0
61+
case let .milliseconds(value): return value == 0
62+
case let .seconds(value): return value == 0
63+
case let .minutes(value): return value == 0
64+
case let .hours(value): return value == 0
65+
case let .days(value): return value == 0
66+
}
67+
}
5568

5669
/// Whether the interval is positive.
57-
public var isPositive: Bool { nanoseconds > 0 }
70+
public var isPositive: Bool {
71+
switch self {
72+
case let .nanoseconds(value): return value > 0
73+
case let .microseconds(value): return value > 0
74+
case let .milliseconds(value): return value > 0
75+
case let .seconds(value): return value > 0
76+
case let .minutes(value): return value > 0
77+
case let .hours(value): return value > 0
78+
case let .days(value): return value > 0
79+
}
80+
}
5881

5982
/// Whether the interval is negative.
60-
public var isNegative: Bool { nanoseconds < 0 }
83+
public var isNegative: Bool {
84+
switch self {
85+
case let .seconds(value): return value < 0
86+
default: return false
87+
}
88+
}
6189

6290
/// Whether the interval is valid.
6391
public var isValid: Bool { !isNegative }

0 commit comments

Comments
 (0)