Skip to content

[5.0] JSONSerialization: avoid intermediate buffer copy #1865

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 30, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 5 additions & 9 deletions Foundation/JSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -152,17 +152,13 @@ open class JSONSerialization : NSObject {
} else {
fatalError("Top-level object was not NSArray or NSDictionary") // This is a fatal error in objective-c too (it is an NSInvalidArgumentException)
}

let count = jsonStr.lengthOfBytes(using: .utf8)
let bufferLength = count+1 // Allow space for null terminator
var utf8: [CChar] = Array<CChar>(repeating: 0, count: bufferLength)
if !jsonStr.getCString(&utf8, maxLength: bufferLength, encoding: .utf8) {
fatalError("Failed to generate a CString from a String")

let count = jsonStr.utf8.count
return jsonStr.withCString {
Data(bytes: $0, count: count)
}
let rawBytes = UnsafeRawPointer(UnsafePointer(utf8))
let result = Data(bytes: rawBytes.bindMemory(to: UInt8.self, capacity: count), count: count)
return result
}

open class func data(withJSONObject value: Any, options opt: WritingOptions = []) throws -> Data {
return try _data(withJSONObject: value, options: opt, stream: false)
}
Expand Down