Skip to content

Commit

Permalink
Add convenience conformances to ByteCount (#2909)
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
clintonpi and glbrntt authored Oct 9, 2024
1 parent b812b1b commit 9ff5fdd
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Sources/NIOFileSystem/ByteCount.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,22 @@ public struct ByteCount: Hashable, Sendable {
}
}

extension ByteCount: AdditiveArithmetic {
public static var zero: ByteCount { ByteCount(bytes: 0) }

public static func + (lhs: ByteCount, rhs: ByteCount) -> ByteCount {
ByteCount(bytes: lhs.bytes + rhs.bytes)
}

public static func - (lhs: ByteCount, rhs: ByteCount) -> ByteCount {
ByteCount(bytes: lhs.bytes - rhs.bytes)
}
}

extension ByteCount: Comparable {
public static func < (lhs: ByteCount, rhs: ByteCount) -> Bool {
lhs.bytes < rhs.bytes
}
}

#endif
26 changes: 26 additions & 0 deletions Tests/NIOFileSystemTests/ByteCountTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,31 @@ class ByteCountTests: XCTestCase {
XCTAssertEqual(byteCount1, byteCount1)
XCTAssertNotEqual(byteCount1, byteCount2)
}

func testByteCountZero() {
let byteCount = ByteCount.zero
XCTAssertEqual(byteCount.bytes, 0)
}

func testByteCountAddition() {
let byteCount1 = ByteCount.bytes(10)
let byteCount2 = ByteCount.bytes(20)
let sum = byteCount1 + byteCount2
XCTAssertEqual(sum.bytes, 30)
}

func testByteCountSubtraction() {
let byteCount1 = ByteCount.bytes(30)
let byteCount2 = ByteCount.bytes(20)
let difference = byteCount1 - byteCount2
XCTAssertEqual(difference.bytes, 10)
}

func testByteCountComparison() {
let byteCount1 = ByteCount.bytes(10)
let byteCount2 = ByteCount.bytes(20)
XCTAssertLessThan(byteCount1, byteCount2)
XCTAssertGreaterThan(byteCount2, byteCount1)
}
}
#endif

0 comments on commit 9ff5fdd

Please sign in to comment.