Skip to content

Commit 03004e9

Browse files
iCharlesHukperryua
andauthored
JSONDecoder should parse base64 via a buffer instead of creating a string (#1001)
resolves: rdar://132749546 Co-authored-by: Kevin Perry <kperry@apple.com>
1 parent 33abf9c commit 03004e9

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

Sources/FoundationEssentials/JSON/JSONDecoder.swift

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -672,8 +672,21 @@ extension JSONDecoderImpl: Decoder {
672672
}
673673

674674
case .base64:
675-
let string = try self.unwrapString(from: mapValue, for: codingPathNode, additionalKey)
676-
guard let data = Data(base64Encoded: string) else {
675+
guard case .string(let region, let isSimple) = mapValue else {
676+
throw self.createTypeMismatchError(type: String.self, for: codingPathNode.path(byAppending: additionalKey), value: mapValue)
677+
}
678+
var data: Data?
679+
if isSimple {
680+
data = withBuffer(for: region) { buffer, _ in
681+
Data(decodingBase64: buffer)
682+
}
683+
}
684+
if data == nil {
685+
// For compatibility, try decoding as a string and then base64 decoding it.
686+
let string = try self.unwrapString(from: mapValue, for: codingPathNode, additionalKey)
687+
data = Data(base64Encoded: string)
688+
}
689+
guard let data else {
677690
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPathNode.path(byAppending: additionalKey), debugDescription: "Encountered Data is not valid Base64."))
678691
}
679692

0 commit comments

Comments
 (0)