Add Int64(safeCast: …) for unsigned values

This commit is contained in:
Max Radermacher 2026-05-04 15:01:53 -05:00 committed by GitHub
parent 7e95b65681
commit 86c3861360
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 10 additions and 0 deletions

View File

@ -28,6 +28,12 @@ extension UInt64 {
// It's safe to cast a UInt64 from a UInt64, but we shouldn't.
}
extension Int64 {
public init(safeCast source: UInt8) { self = Int64(source) }
public init(safeCast source: UInt16) { self = Int64(source) }
public init(safeCast source: UInt32) { self = Int64(source) }
}
// MARK: -
public extension Int {

View File

@ -9,6 +9,10 @@ import Testing
struct IntTest {
@Test
func testSafeCast() {
_ = Int64(safeCast: UInt32.max)
_ = Int64(safeCast: UInt16.max)
_ = Int64(safeCast: UInt8.max)
// This is least safe of the safe casts, though it would require
// UInt.bitWidth to be larger than UInt64.bitWidth. That's not currently a
// thing, and it seems unlikely to change in the foreseeable future.