Skip to content

JSONDecoder: Check that a parsed float does not return infinity. #2989

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 1 commit into from
Mar 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/Foundation/JSONDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ extension JSONDecoderImpl: Decoder {
as type: T.Type) throws -> T
{
if case .number(let number) = value {
guard let floatingPoint = T(number) else {
guard let floatingPoint = T(number), floatingPoint.isFinite else {
var path = self.codingPath
if let additionalKey = additionalKey {
path.append(additionalKey)
Expand Down
9 changes: 9 additions & 0 deletions Tests/Foundation/Tests/TestJSONEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -601,14 +601,23 @@ class TestJSONEncoder : XCTestCase {

func test_codingOfFloat() {
test_codingOf(value: Float(1.5), toAndFrom: "1.5")

// Check value too large fails to decode.
XCTAssertThrowsError(try JSONDecoder().decode(Float.self, from: "1e100".data(using: .utf8)!))
}

func test_codingOfDouble() {
test_codingOf(value: Double(1.5), toAndFrom: "1.5")

// Check value too large fails to decode.
XCTAssertThrowsError(try JSONDecoder().decode(Double.self, from: "100e323".data(using: .utf8)!))
}

func test_codingOfDecimal() {
test_codingOf(value: Decimal.pi, toAndFrom: "3.14159265358979323846264338327950288419")

// Check value too large fails to decode.
XCTAssertThrowsError(try JSONDecoder().decode(Decimal.self, from: "100e200".data(using: .utf8)!))
}

func test_codingOfString() {
Expand Down