Skip to content

Commit 9ff5fdd

Browse files
clintonpiglbrntt
andauthored
Add convenience conformances to ByteCount (#2909)
Motivation: Several arithmetic and comparison operations are done with `ByteCount` using the `bytes` property. Operating on the `ByteCount` type directly will be more convenient. Modifications: - Add `AdditiveArithmetic` and `Comparable` conformances to `ByteCount`. Result: The `ByteCount` type can undergo arithmetic and comparison operations. --------- Co-authored-by: George Barnett <[email protected]>
1 parent b812b1b commit 9ff5fdd

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Sources/NIOFileSystem/ByteCount.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,22 @@ public struct ByteCount: Hashable, Sendable {
8080
}
8181
}
8282

83+
extension ByteCount: AdditiveArithmetic {
84+
public static var zero: ByteCount { ByteCount(bytes: 0) }
85+
86+
public static func + (lhs: ByteCount, rhs: ByteCount) -> ByteCount {
87+
ByteCount(bytes: lhs.bytes + rhs.bytes)
88+
}
89+
90+
public static func - (lhs: ByteCount, rhs: ByteCount) -> ByteCount {
91+
ByteCount(bytes: lhs.bytes - rhs.bytes)
92+
}
93+
}
94+
95+
extension ByteCount: Comparable {
96+
public static func < (lhs: ByteCount, rhs: ByteCount) -> Bool {
97+
lhs.bytes < rhs.bytes
98+
}
99+
}
100+
83101
#endif

Tests/NIOFileSystemTests/ByteCountTests.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,5 +58,31 @@ class ByteCountTests: XCTestCase {
5858
XCTAssertEqual(byteCount1, byteCount1)
5959
XCTAssertNotEqual(byteCount1, byteCount2)
6060
}
61+
62+
func testByteCountZero() {
63+
let byteCount = ByteCount.zero
64+
XCTAssertEqual(byteCount.bytes, 0)
65+
}
66+
67+
func testByteCountAddition() {
68+
let byteCount1 = ByteCount.bytes(10)
69+
let byteCount2 = ByteCount.bytes(20)
70+
let sum = byteCount1 + byteCount2
71+
XCTAssertEqual(sum.bytes, 30)
72+
}
73+
74+
func testByteCountSubtraction() {
75+
let byteCount1 = ByteCount.bytes(30)
76+
let byteCount2 = ByteCount.bytes(20)
77+
let difference = byteCount1 - byteCount2
78+
XCTAssertEqual(difference.bytes, 10)
79+
}
80+
81+
func testByteCountComparison() {
82+
let byteCount1 = ByteCount.bytes(10)
83+
let byteCount2 = ByteCount.bytes(20)
84+
XCTAssertLessThan(byteCount1, byteCount2)
85+
XCTAssertGreaterThan(byteCount2, byteCount1)
86+
}
6187
}
6288
#endif

0 commit comments

Comments
 (0)