Skip to content

Commit 6468e2b

Browse files
authored
JSONSerialization: avoid intermediate buffer copy (#1865)
1 parent 70e6498 commit 6468e2b

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed

Foundation/JSONSerialization.swift

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -152,17 +152,13 @@ open class JSONSerialization : NSObject {
152152
} else {
153153
fatalError("Top-level object was not NSArray or NSDictionary") // This is a fatal error in objective-c too (it is an NSInvalidArgumentException)
154154
}
155-
156-
let count = jsonStr.lengthOfBytes(using: .utf8)
157-
let bufferLength = count+1 // Allow space for null terminator
158-
var utf8: [CChar] = Array<CChar>(repeating: 0, count: bufferLength)
159-
if !jsonStr.getCString(&utf8, maxLength: bufferLength, encoding: .utf8) {
160-
fatalError("Failed to generate a CString from a String")
155+
156+
let count = jsonStr.utf8.count
157+
return jsonStr.withCString {
158+
Data(bytes: $0, count: count)
161159
}
162-
let rawBytes = UnsafeRawPointer(UnsafePointer(utf8))
163-
let result = Data(bytes: rawBytes.bindMemory(to: UInt8.self, capacity: count), count: count)
164-
return result
165160
}
161+
166162
open class func data(withJSONObject value: Any, options opt: WritingOptions = []) throws -> Data {
167163
return try _data(withJSONObject: value, options: opt, stream: false)
168164
}

0 commit comments

Comments
 (0)