Skip to content

Commit 99c2281

Browse files
authored
Merge pull request #1862 from ianpartridge/json-perf
2 parents 7f66150 + 12f1c45 commit 99c2281

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
@@ -146,17 +146,13 @@ open class JSONSerialization : NSObject {
146146
} else {
147147
fatalError("Top-level object was not NSArray or NSDictionary") // This is a fatal error in objective-c too (it is an NSInvalidArgumentException)
148148
}
149-
150-
let count = jsonStr.lengthOfBytes(using: .utf8)
151-
let bufferLength = count+1 // Allow space for null terminator
152-
var utf8: [CChar] = Array<CChar>(repeating: 0, count: bufferLength)
153-
if !jsonStr.getCString(&utf8, maxLength: bufferLength, encoding: .utf8) {
154-
fatalError("Failed to generate a CString from a String")
149+
150+
let count = jsonStr.utf8.count
151+
return jsonStr.withCString {
152+
Data(bytes: $0, count: count)
155153
}
156-
let rawBytes = UnsafeRawPointer(UnsafePointer(utf8))
157-
let result = Data(bytes: rawBytes.bindMemory(to: UInt8.self, capacity: count), count: count)
158-
return result
159154
}
155+
160156
open class func data(withJSONObject value: Any, options opt: WritingOptions = []) throws -> Data {
161157
return try _data(withJSONObject: value, options: opt, stream: false)
162158
}

0 commit comments

Comments
 (0)