Skip to content

Commit

Permalink
Decode doubles as Int if exactly represented
Browse files Browse the repository at this point in the history
  • Loading branch information
swhitty committed Jun 26, 2024
1 parent 91665a2 commit 4f93797
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
10 changes: 9 additions & 1 deletion Sources/KeyValueDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,15 @@ private extension KeyValueDecoder {
throw DecodingError.typeMismatch(type, context)
}
return val
} else {
} else if let double = (value as? NSNumber)?.getDoubleValue() {
let val = T(double)
guard Double(val) == double else {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "\(valueDescription) at \(codingPath.makeKeyPath()), cannot be exactly represented by \(type)")
throw DecodingError.typeMismatch(type, context)
}
return val
}
else {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Expected BinaryInteger at \(codingPath.makeKeyPath()), found \(valueDescription)")
if decodeNil() {
throw DecodingError.valueNotFound(type, context)
Expand Down
24 changes: 20 additions & 4 deletions Tests/KeyValueDecoderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@ final class KeyValueDecoderTests: XCTestCase {
try KeyValueDecoder.decode(Int16.self, from: NSNumber(10)),
10
)
XCTAssertEqual(
try KeyValueDecoder.decode(Int16.self, from: 10.0),
10
)
XCTAssertEqual(
try KeyValueDecoder.decode(Int16.self, from: NSNumber(10.0)),
10
)
XCTAssertThrowsError(
try KeyValueDecoder.decode(Int8.self, from: Int16.max)
)
Expand All @@ -129,6 +137,14 @@ final class KeyValueDecoderTests: XCTestCase {
try KeyValueDecoder.decode(UInt8.self, from: NSNumber(10)),
10
)
XCTAssertEqual(
try KeyValueDecoder.decode(UInt8.self, from: 10.0),
10
)
XCTAssertEqual(
try KeyValueDecoder.decode(UInt8.self, from: NSNumber(10.0)),
10
)
XCTAssertThrowsError(
try KeyValueDecoder.decode(UInt8.self, from: UInt16.max)
)
Expand Down Expand Up @@ -480,8 +496,8 @@ final class KeyValueDecoderTests: XCTestCase {

func testDecodes_UnkeyedInts() {
XCTAssertEqual(
try KeyValueDecoder.decode([Int].self, from: [-10, 20, 30]),
[-10, 20, 30]
try KeyValueDecoder.decode([Int].self, from: [-10, 20, 30, 40.0, -50.0]),
[-10, 20, 30, 40, -50]
)
XCTAssertEqual(
try KeyValueDecoder.decode([Int8].self, from: [10, -20, 30]),
Expand Down Expand Up @@ -610,8 +626,8 @@ final class KeyValueDecoderTests: XCTestCase {

func testDecodes_UnkeyedUInts() {
XCTAssertEqual(
try KeyValueDecoder.decode([UInt].self, from: [10, 20, 30]),
[10, 20, 30]
try KeyValueDecoder.decode([UInt].self, from: [10, 20, 30, 40.0]),
[10, 20, 30, 40]
)
XCTAssertEqual(
try KeyValueDecoder.decode([UInt8].self, from: [10, 20, 30]),
Expand Down

0 comments on commit 4f93797

Please sign in to comment.