Skip to content

Commit 13a74c7

Browse files
committed
Code review
1 parent e5f4c47 commit 13a74c7

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

Sources/Foundation/JSONSerialization.swift

+21-16
Original file line numberDiff line numberDiff line change
@@ -344,27 +344,32 @@ private extension JSONSerialization {
344344
return nil
345345
}
346346

347-
switch (bytes[0], bytes[1]) {
348-
case (0xEF, 0xBB):
349-
if bytes.count >= 3 && bytes[2] == 0xBF {
350-
return (.utf8, 3)
351-
}
352-
case (0x00, 0x00):
353-
if bytes.count >= 4 && bytes[2] == 0xFE && bytes[3] == 0xFF {
354-
return (.utf32BigEndian, 4)
355-
}
356-
case (0xFF, 0xFE):
357-
if bytes.count >= 4 && bytes[2] == 0 && bytes[3] == 0 {
358-
return (.utf32LittleEndian, 4)
359-
}
347+
if bytes.starts(with: Self.utf8BOM) {
348+
return (.utf8, 3)
349+
}
350+
if bytes.starts(with: Self.utf32BigEndianBOM) {
351+
return (.utf32BigEndian, 4)
352+
}
353+
if bytes.starts(with: Self.utf32LittleEndianBOM) {
354+
return (.utf32LittleEndian, 4)
355+
}
356+
if bytes.starts(with: [0xFF, 0xFE]) {
360357
return (.utf16LittleEndian, 2)
361-
case (0xFE, 0xFF):
358+
}
359+
if bytes.starts(with: [0xFE, 0xFF]) {
362360
return (.utf16BigEndian, 2)
363-
default:
364-
break
365361
}
362+
366363
return nil
367364
}
365+
366+
// These static properties don't look very nice, but we need them to
367+
// workaround: https://bugs.swift.org/browse/SR-14102
368+
private static let utf8BOM: [UInt8] = [0xEF, 0xBB, 0xBF]
369+
private static let utf32BigEndianBOM: [UInt8] = [0x00, 0x00, 0xFE, 0xFF]
370+
private static let utf32LittleEndianBOM: [UInt8] = [0xFF, 0xFE, 0x00, 0x00]
371+
private static let utf16BigEndianBOM: [UInt8] = [0xFF, 0xFE]
372+
private static let utf16LittleEndianBOM: [UInt8] = [0xFE, 0xFF]
368373
}
369374

370375
//MARK: - JSONSerializer

0 commit comments

Comments
 (0)