-
Notifications
You must be signed in to change notification settings - Fork 1.2k
JSONSerialization: Use NSDecimalNumber for parsing json numbers. #1655
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
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -822,45 +822,61 @@ private struct JSONReader { | |
] | ||
|
||
func parseNumber(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> (Any, Index)? { | ||
func parseTypedNumber(_ address: UnsafePointer<UInt8>, count: Int) -> (Any, IndexDistance)? { | ||
let temp_buffer_size = 64 | ||
var temp_buffer = [Int8](repeating: 0, count: temp_buffer_size) | ||
return temp_buffer.withUnsafeMutableBufferPointer { (buffer: inout UnsafeMutableBufferPointer<Int8>) -> (Any, IndexDistance)? in | ||
memcpy(buffer.baseAddress!, address, min(count, temp_buffer_size - 1)) // ensure null termination | ||
|
||
let startPointer = buffer.baseAddress! | ||
let intEndPointer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1) | ||
defer { intEndPointer.deallocate() } | ||
let doubleEndPointer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1) | ||
defer { doubleEndPointer.deallocate() } | ||
let intResult = strtol(startPointer, intEndPointer, 10) | ||
let intDistance = startPointer.distance(to: intEndPointer[0]!) | ||
let doubleResult = strtod(startPointer, doubleEndPointer) | ||
let doubleDistance = startPointer.distance(to: doubleEndPointer[0]!) | ||
|
||
guard doubleDistance > 0 else { return nil } | ||
if intDistance == doubleDistance { | ||
return (NSNumber(value: intResult), intDistance) | ||
} | ||
return (NSNumber(value: doubleResult), doubleDistance) | ||
let ZERO = UInt8(ascii: "0") | ||
let ONE = UInt8(ascii: "1") | ||
let NINE = UInt8(ascii: "9") | ||
let MINUS = UInt8(ascii: "-") | ||
|
||
func parseTypedNumber(_ string: String) throws -> (Any, IndexDistance)? { | ||
let scan = Scanner(string: string) | ||
var decimal = Decimal() | ||
guard scan.scanDecimal(&decimal) else { | ||
return nil | ||
} | ||
return (NSDecimalNumber(decimal: decimal), scan.scanLocation) | ||
} | ||
|
||
|
||
// Validate the first few characters look like a JSON encoded number: | ||
// Optional '-' sign at start only 1 leading zero if followed by a decimal point. | ||
var index = input | ||
func nextDigit() -> UInt8? { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this more clearly be called |
||
guard let (ascii, nextIndex) = source.takeASCII(index) else { return nil } | ||
index = nextIndex | ||
return ascii | ||
} | ||
|
||
guard var digit = nextDigit() else { return nil } | ||
guard digit == MINUS || (digit >= ZERO && digit <= NINE) else { return nil } | ||
if digit == MINUS { | ||
guard let d = nextDigit() else { return nil } | ||
digit = d | ||
} | ||
|
||
if digit == ZERO { | ||
if let digit2 = nextDigit(), digit2 >= ZERO && digit2 <= NINE { | ||
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, | ||
userInfo: ["NSDebugDescription" : "Leading zeros not allowed character \(input)." ]) | ||
} | ||
} else if digit < ONE || digit > NINE { | ||
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, | ||
userInfo: ["NSDebugDescription" : "Numbers must start with a 1-9 at \(input)." ]) | ||
} | ||
|
||
if source.encoding == .utf8 { | ||
return parseTypedNumber(source.buffer.baseAddress!.advanced(by: input), count: source.buffer.count - input).map { return ($0.0, input + $0.1) } | ||
let count = source.buffer.count - input | ||
let ptr = UnsafeMutableRawPointer(mutating: source.buffer.baseAddress!.advanced(by: input)) | ||
guard let string = String(bytesNoCopy: ptr, length: count, | ||
encoding: .utf8, freeWhenDone: false) else { return nil } | ||
return try parseTypedNumber(string).map { return ($0.0, input + $0.1) } | ||
} | ||
else { | ||
var numberCharacters = [UInt8]() | ||
var string = "" | ||
var index = input | ||
while let (ascii, nextIndex) = source.takeASCII(index), JSONReader.numberCodePoints.contains(ascii) { | ||
numberCharacters.append(ascii) | ||
string.append(String(UnicodeScalar(ascii))) | ||
index = nextIndex | ||
} | ||
numberCharacters.append(0) | ||
|
||
return numberCharacters.withUnsafeBufferPointer { | ||
parseTypedNumber($0.baseAddress!, count: $0.count) | ||
}.map { return ($0.0, index) } | ||
return try parseTypedNumber(string).map { return ($0.0, index) } | ||
} | ||
} | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's worth testing the performance of creating a new
Scanner
for every single number we try to parse — I suspect that this is a potentially prohibitively expensive operation.