Skip to content

Commit

Permalink
Fix an issue that led to a crash, if an empty array was decoded (#52)
Browse files Browse the repository at this point in the history
Thanks @calebkleveter for reporting this
  • Loading branch information
fabianfett authored Jul 8, 2020
1 parent d6497c0 commit 5dc8ec1
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ struct JSONUnkeyedDecodingContainer: UnkeyedDecodingContainer {
let array: [JSONValue]

let count: Int? // protocol requirement to be optional
var isAtEnd = false
var isAtEnd: Bool
var currentIndex = 0

init(impl: JSONDecoderImpl, codingPath: [CodingKey], array: [JSONValue]) {
self.impl = impl
self.codingPath = codingPath
self.array = array

isAtEnd = array.count == 0
count = array.count
}

Expand Down
28 changes: 28 additions & 0 deletions Tests/PureSwiftJSONTests/Decoding/JSONDecoderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,32 @@ class JSONDecoderTests: XCTestCase {
XCTAssertNotNil(context.underlyingError)
}
}

func testDecodeEmptyArray() {
let json = """
{
"array": []
}
"""
struct Foo: Decodable {
let array: [String]
}
let decoder = PSJSONDecoder()

var result: Foo?
XCTAssertNoThrow(result = try decoder.decode(Foo.self, from: json.utf8))
XCTAssertEqual(result?.array, [])
}

func testIfUserInfoIsHandedDown() {
let json = "{}"
struct Foo: Decodable {
init(decoder: Decoder) {
XCTAssertEqual(decoder.userInfo as? [CodingUserInfoKey: String], [CodingUserInfoKey(rawValue: "foo")!: "bar"])
}
}
var decoder = PSJSONDecoder()
decoder.userInfo[CodingUserInfoKey(rawValue: "foo")!] = "bar"
XCTAssertNoThrow(_ = try decoder.decode(Foo.self, from: json.utf8))
}
}
11 changes: 11 additions & 0 deletions Tests/PureSwiftJSONTests/Encoding/JSONEncoderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,15 @@ class JSONEncoderTests: XCTestCase {
XCTAssertNoThrow(parsed = try JSONParser().parse(bytes: XCTUnwrap(result)))
XCTAssertEqual(parsed, .object(["sub": .object(["key": .string("sub"), "value": .number("12")])]))
}

func testIfUserInfoIsHandedDown() {
struct Foo: Encodable {
func encode(to encoder: Encoder) throws {
XCTAssertEqual(encoder.userInfo as? [CodingUserInfoKey: String], [CodingUserInfoKey(rawValue: "foo")!: "bar"])
}
}
var encoder = PSJSONEncoder()
encoder.userInfo[CodingUserInfoKey(rawValue: "foo")!] = "bar"
XCTAssertNoThrow(_ = try encoder.encode(Foo()))
}
}

0 comments on commit 5dc8ec1

Please sign in to comment.