Skip to content

Conform TimeAmount to AdditiveArithmetic #1691

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Nov 17, 2020
15 changes: 14 additions & 1 deletion Sources/NIO/EventLoop.swift
Original file line number Diff line number Diff line change
Expand Up @@ -349,14 +349,27 @@ extension TimeAmount: Comparable {
}
}

extension TimeAmount {
extension TimeAmount: AdditiveArithmetic {
/// The zero value for `TimeAmount`.
public static var zero: TimeAmount {
return TimeAmount.nanoseconds(0)
}

public static func + (lhs: TimeAmount, rhs: TimeAmount) -> TimeAmount {
return TimeAmount(lhs.nanoseconds + rhs.nanoseconds)
}

public static func +=(lhs: inout TimeAmount, rhs: TimeAmount) {
lhs = lhs + rhs
}

public static func - (lhs: TimeAmount, rhs: TimeAmount) -> TimeAmount {
return TimeAmount(lhs.nanoseconds - rhs.nanoseconds)
}

public static func -=(lhs: inout TimeAmount, rhs: TimeAmount) {
lhs = lhs - rhs
}

public static func * <T: BinaryInteger>(lhs: T, rhs: TimeAmount) -> TimeAmount {
return TimeAmount(Int64(lhs) * rhs.nanoseconds)
Expand Down
2 changes: 2 additions & 0 deletions Tests/NIOTests/TimeAmountTests+XCTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ extension TimeAmountTests {
return [
("testTimeAmountConversion", testTimeAmountConversion),
("testTimeAmountIsHashable", testTimeAmountIsHashable),
("testTimeAmountDoesAddTime", testTimeAmountDoesAddTime),
("testTimeAmountDoesSubtractTime", testTimeAmountDoesSubtractTime),
]
}
}
Expand Down
15 changes: 15 additions & 0 deletions Tests/NIOTests/TimeAmountTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,25 @@ class TimeAmountTests: XCTestCase {
XCTAssertEqual(TimeAmount.seconds(9), .nanoseconds(9_000_000_000))
XCTAssertEqual(TimeAmount.minutes(2), .nanoseconds(120_000_000_000))
XCTAssertEqual(TimeAmount.hours(6), .nanoseconds(21_600_000_000_000))
XCTAssertEqual(TimeAmount.zero, .nanoseconds(0))
}

func testTimeAmountIsHashable() {
let amounts: Set<TimeAmount> = [.seconds(1), .milliseconds(4), .seconds(1)]
XCTAssertEqual(amounts, [.seconds(1), .milliseconds(4)])
}

func testTimeAmountDoesAddTime() {
var lhs = TimeAmount.nanoseconds(0)
let rhs = TimeAmount.nanoseconds(5)
lhs += rhs
XCTAssertEqual(lhs, .nanoseconds(5))
}

func testTimeAmountDoesSubtractTime() {
var lhs = TimeAmount.nanoseconds(5)
let rhs = TimeAmount.nanoseconds(5)
lhs -= rhs
XCTAssertEqual(lhs, .nanoseconds(0))
}
}