Skip to content

Commit be0f333

Browse files
JoannisCopilot
andauthored
Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent e6de18d commit be0f333

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

Sources/_NIOJSON/Core/JSONDescription.swift

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -942,7 +942,9 @@ extension JSONDescriptionProtocol {
942942
// Quick length check first - most common rejection path
943943
// For object keys with hash, use hash comparison to skip mismatches
944944
if keyType == .objectKey || keyType == .objectKeyWithEscaping {
945-
let storedHash: UInt32 = self.getInteger(at: offset + Constants.objectKeyHashOffset) ?? 0
945+
guard let storedHash: UInt32 = self.getInteger(at: offset + Constants.objectKeyHashOffset) else {
946+
fatalError("JSONDescription index structure corrupted: missing object key hash at offset \(offset + Constants.objectKeyHashOffset)")
947+
}
946948
// Only do memcmp if hashes match (fast reject on mismatch)
947949
if storedHash == searchHash {
948950
if memcmp(key.baseAddress!, json + Int(bounds.offset), Int(bounds.length)) == 0 {
@@ -986,8 +988,8 @@ extension JSONDescriptionProtocol {
986988
}
987989
} else if bounds.length == keySize {
988990
if keyType == .objectKey || keyType == .objectKeyWithEscaping {
989-
let storedHash: UInt32 = self.getInteger(at: offset + Constants.objectKeyHashOffset) ?? 0
990-
if storedHash == searchHash {
991+
if let storedHash: UInt32 = self.getInteger(at: offset + Constants.objectKeyHashOffset),
992+
storedHash == searchHash {
991993
if memcmp(key.baseAddress!, json + Int(bounds.offset), Int(bounds.length)) == 0 {
992994
return (index, offset)
993995
}

Tests/IkigaJSONTests/JSONTests.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1751,8 +1751,10 @@ final class IkigaJSONTests: XCTestCase {
17511751
}
17521752

17531753
func testEmptyObjectKey() throws {
1754-
// Test case for potential bug: empty keys (keyLength = 0) cause invalid range 1...0
1755-
// This tests the hash computation loop in JSONParser+Parsing.swift line 331
1754+
// Regression test for empty keys (keyLength = 0): the hash computation loop uses
1755+
// a range like 1..<(keyLength + 1), which becomes 1..<1 (a valid empty range).
1756+
// This guards against changes that might introduce an invalid range (e.g. 1...keyLength)
1757+
// and ensures the parser correctly handles empty object keys.
17561758
let json = """
17571759
{"": "value"}
17581760
""".data(using: .utf8)!

0 commit comments

Comments
 (0)