Skip to content

Commit 5dc8ec1

Browse files
authored
Fix an issue that led to a crash, if an empty array was decoded (#52)
Thanks @calebkleveter for reporting this
1 parent d6497c0 commit 5dc8ec1

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

Sources/PureSwiftJSON/Decoding/JSONUnkeyedDecodingContainer.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@ struct JSONUnkeyedDecodingContainer: UnkeyedDecodingContainer {
55
let array: [JSONValue]
66

77
let count: Int? // protocol requirement to be optional
8-
var isAtEnd = false
8+
var isAtEnd: Bool
99
var currentIndex = 0
1010

1111
init(impl: JSONDecoderImpl, codingPath: [CodingKey], array: [JSONValue]) {
1212
self.impl = impl
1313
self.codingPath = codingPath
1414
self.array = array
15+
16+
isAtEnd = array.count == 0
1517
count = array.count
1618
}
1719

Tests/PureSwiftJSONTests/Decoding/JSONDecoderTests.swift

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,32 @@ class JSONDecoderTests: XCTestCase {
111111
XCTAssertNotNil(context.underlyingError)
112112
}
113113
}
114+
115+
func testDecodeEmptyArray() {
116+
let json = """
117+
{
118+
"array": []
119+
}
120+
"""
121+
struct Foo: Decodable {
122+
let array: [String]
123+
}
124+
let decoder = PSJSONDecoder()
125+
126+
var result: Foo?
127+
XCTAssertNoThrow(result = try decoder.decode(Foo.self, from: json.utf8))
128+
XCTAssertEqual(result?.array, [])
129+
}
130+
131+
func testIfUserInfoIsHandedDown() {
132+
let json = "{}"
133+
struct Foo: Decodable {
134+
init(decoder: Decoder) {
135+
XCTAssertEqual(decoder.userInfo as? [CodingUserInfoKey: String], [CodingUserInfoKey(rawValue: "foo")!: "bar"])
136+
}
137+
}
138+
var decoder = PSJSONDecoder()
139+
decoder.userInfo[CodingUserInfoKey(rawValue: "foo")!] = "bar"
140+
XCTAssertNoThrow(_ = try decoder.decode(Foo.self, from: json.utf8))
141+
}
114142
}

Tests/PureSwiftJSONTests/Encoding/JSONEncoderTests.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,4 +132,15 @@ class JSONEncoderTests: XCTestCase {
132132
XCTAssertNoThrow(parsed = try JSONParser().parse(bytes: XCTUnwrap(result)))
133133
XCTAssertEqual(parsed, .object(["sub": .object(["key": .string("sub"), "value": .number("12")])]))
134134
}
135+
136+
func testIfUserInfoIsHandedDown() {
137+
struct Foo: Encodable {
138+
func encode(to encoder: Encoder) throws {
139+
XCTAssertEqual(encoder.userInfo as? [CodingUserInfoKey: String], [CodingUserInfoKey(rawValue: "foo")!: "bar"])
140+
}
141+
}
142+
var encoder = PSJSONEncoder()
143+
encoder.userInfo[CodingUserInfoKey(rawValue: "foo")!] = "bar"
144+
XCTAssertNoThrow(_ = try encoder.encode(Foo()))
145+
}
135146
}

0 commit comments

Comments
 (0)