-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathNSScanner.swift
648 lines (575 loc) · 23.4 KB
/
NSScanner.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
public class NSScanner : NSObject, NSCopying {
internal var _scanString: String
internal var _skipSet: NSCharacterSet?
internal var _invertedSkipSet: NSCharacterSet?
internal var _scanLocation: Int
public func copyWithZone(zone: NSZone) -> AnyObject {
return NSScanner(string: string)
}
public var string: String {
return _scanString
}
public var scanLocation: Int {
get {
return _scanLocation
}
set {
if newValue > string.length {
fatalError("Index \(newValue) beyond bounds; string length \(string.length)")
}
_scanLocation = newValue
}
}
/*@NSCopying*/ public var charactersToBeSkipped: NSCharacterSet? {
get {
return _skipSet
}
set {
_skipSet = newValue?.copy() as? NSCharacterSet
_invertedSkipSet = nil
}
}
internal var invertedSkipSet: NSCharacterSet? {
get {
if let inverted = _invertedSkipSet {
return inverted
} else {
if let set = charactersToBeSkipped {
_invertedSkipSet = set.invertedSet
return _invertedSkipSet
}
return nil
}
}
}
public var caseSensitive: Bool = false
public var locale: NSLocale?
internal static let defaultSkipSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
public init(string: String) {
_scanString = string
_skipSet = NSScanner.defaultSkipSet
_scanLocation = 0
}
}
private struct _NSStringBuffer {
var bufferLen: Int
var bufferLoc: Int
var string: NSString
var stringLen: Int
var stringLoc: Int
var buffer = Array<unichar>(count: 32, repeatedValue: 0)
var curChar: unichar
static let EndCharacter = unichar(0xffff)
init(string: String, start: Int, end: Int) {
self.string = string._bridgeToObjectiveC()
stringLoc = start
stringLen = end
if stringLoc < stringLen {
bufferLen = min(32, stringLen - stringLoc);
let range = NSMakeRange(stringLoc, bufferLen)
bufferLoc = 1
curChar = buffer[0]
buffer.withUnsafeMutableBufferPointer({ (inout ptr: UnsafeMutableBufferPointer<unichar>) -> Void in
self.string.getCharacters(ptr.baseAddress, range: range)
})
} else {
bufferLen = 0
bufferLoc = 1
curChar = _NSStringBuffer.EndCharacter
}
}
var currentCharacter: unichar {
return curChar
}
var isAtEnd: Bool {
return curChar == _NSStringBuffer.EndCharacter
}
mutating func fill() {
bufferLen = min(32, stringLen - stringLoc);
let range = NSMakeRange(stringLoc, bufferLen)
buffer.withUnsafeMutableBufferPointer({ (inout ptr: UnsafeMutableBufferPointer<unichar>) -> Void in
string.getCharacters(ptr.baseAddress, range: range)
})
bufferLoc = 1
curChar = buffer[0]
}
mutating func advance() {
if bufferLoc < bufferLen { /*buffer is OK*/
curChar = buffer[bufferLoc++]
} else if (stringLoc + bufferLen < stringLen) { /* Buffer is empty but can be filled */
stringLoc += bufferLen
fill()
} else { /* Buffer is empty and we're at the end */
bufferLoc = bufferLen + 1
curChar = _NSStringBuffer.EndCharacter
}
}
mutating func skip(skipSet: NSCharacterSet?) {
if let set = skipSet {
while set.characterIsMember(currentCharacter) && !isAtEnd {
advance()
}
}
}
}
private func isADigit(ch: unichar) -> Bool {
struct Local {
static let set = NSCharacterSet.decimalDigitCharacterSet()
}
return Local.set.characterIsMember(ch)
}
// This is just here to allow just enough generic math to handle what is needed for scanning an abstract integer from a string, perhaps these should be on IntegerType?
internal protocol _BitShiftable {
func >>(lhs: Self, rhs: Self) -> Self
func <<(lhs: Self, rhs: Self) -> Self
}
internal protocol _IntegerLike : IntegerType, _BitShiftable {
init(_ value: Int)
static var max: Self { get }
static var min: Self { get }
}
internal protocol _FloatArithmeticType {
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self
}
internal protocol _FloatLike : FloatingPointType, _FloatArithmeticType {
init(_ value: Int)
init(_ value: Double)
static var max: Self { get }
static var min: Self { get }
}
extension Int : _IntegerLike { }
extension Int32 : _IntegerLike { }
extension Int64 : _IntegerLike { }
extension UInt32 : _IntegerLike { }
extension UInt64 : _IntegerLike { }
// these might be good to have in the stdlib
extension Float : _FloatLike {
static var max: Float { return FLT_MAX }
static var min: Float { return FLT_MIN }
}
extension Double : _FloatLike {
static var max: Double { return DBL_MAX }
static var min: Double { return DBL_MIN }
}
private func numericValue(ch: unichar) -> Int {
if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) {
return Int(ch) - Int(unichar(unicodeScalarLiteral: "0"))
} else {
return __CFCharDigitValue(UniChar(ch))
}
}
private func numericOrHexValue(ch: unichar) -> Int {
if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) {
return Int(ch) - Int(unichar(unicodeScalarLiteral: "0"))
} else if (ch >= unichar(unicodeScalarLiteral: "A") && ch <= unichar(unicodeScalarLiteral: "F")) {
return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "A"))
} else if (ch >= unichar(unicodeScalarLiteral: "a") && ch <= unichar(unicodeScalarLiteral: "f")) {
return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "a"))
} else {
return -1;
}
}
private func decimalSep(locale: NSLocale?) -> String {
if let loc = locale {
if let sep = loc.objectForKey(NSLocaleDecimalSeparator) as? NSString {
return sep._swiftObject
}
return "."
} else {
return decimalSep(NSLocale.currentLocale())
}
}
extension String {
internal func scan<T: _IntegerLike>(skipSet: NSCharacterSet?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool {
var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length)
buf.skip(skipSet)
var neg = false
var localResult: T = 0
if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") {
neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-")
buf.advance()
buf.skip(skipSet)
}
if (!isADigit(buf.currentCharacter)) {
return false
}
repeat {
let numeral = numericValue(buf.currentCharacter)
if numeral == -1 {
break
}
if (localResult >= T.max / 10) && ((localResult > T.max / 10) || T(numeral - (neg ? 1 : 0)) >= T.max - localResult * 10) {
// apply the clamps and advance past the ending of the buffer where there are still digits
localResult = neg ? T.min : T.max
neg = false
repeat {
buf.advance()
} while (isADigit(buf.currentCharacter))
break
} else {
// normal case for scanning
localResult = localResult * 10 + T(numeral)
}
buf.advance()
} while (isADigit(buf.currentCharacter))
to(neg ? -1 * localResult : localResult)
locationToScanFrom = buf.stringLoc
return true
}
internal func scanHex<T: _IntegerLike>(skipSet: NSCharacterSet?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool {
var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length)
buf.skip(skipSet)
var localResult: T = 0
var curDigit: Int
if buf.currentCharacter == unichar(unicodeScalarLiteral: "0") {
buf.advance()
let locRewindTo = buf.stringLoc
curDigit = numericOrHexValue(buf.currentCharacter)
if curDigit == -1 {
if buf.currentCharacter == unichar(unicodeScalarLiteral: "x") || buf.currentCharacter == unichar(unicodeScalarLiteral: "X") {
buf.advance()
curDigit = numericOrHexValue(buf.currentCharacter)
}
}
if curDigit == -1 {
locationToScanFrom = locRewindTo
to(T(0))
return true
}
} else {
curDigit = numericOrHexValue(buf.currentCharacter)
if curDigit == -1 {
return false
}
}
repeat {
if localResult > T.max >> T(4) {
localResult = T.max
} else {
localResult = (localResult << T(4)) + T(curDigit)
}
buf.advance()
curDigit = numericOrHexValue(buf.currentCharacter)
} while (curDigit != -1)
to(localResult)
locationToScanFrom = buf.stringLoc
return true
}
internal func scan<T: _FloatLike>(skipSet: NSCharacterSet?, locale: NSLocale?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool {
let ds_chars = decimalSep(locale).utf16
let ds = ds_chars[ds_chars.startIndex]
var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length)
buf.skip(skipSet)
var neg = false
var localResult: T = T(0)
if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") {
neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-")
buf.advance()
buf.skip(skipSet)
}
if (!isADigit(buf.currentCharacter)) {
return false
}
repeat {
let numeral = numericValue(buf.currentCharacter)
if numeral == -1 {
break
}
// if (localResult >= T.max / T(10)) && ((localResult > T.max / T(10)) || T(numericValue(buf.currentCharacter) - (neg ? 1 : 0)) >= T.max - localResult * T(10)) is evidently too complex; so break it down to more "edible chunks"
let limit1 = localResult >= T.max / T(10)
let limit2 = localResult > T.max / T(10)
let limit3 = T(numeral - (neg ? 1 : 0)) >= T.max - localResult * T(10)
if (limit1) && (limit2 || limit3) {
// apply the clamps and advance past the ending of the buffer where there are still digits
localResult = neg ? T.min : T.max
neg = false
repeat {
buf.advance()
} while (isADigit(buf.currentCharacter))
break
} else {
localResult = localResult * T(10) + T(numeral)
}
buf.advance()
} while (isADigit(buf.currentCharacter))
if buf.currentCharacter == ds {
var factor = T(0.1)
buf.advance()
repeat {
let numeral = numericValue(buf.currentCharacter)
if numeral == -1 {
break
}
localResult = localResult + T(numeral) * factor
factor = factor * T(0.1)
buf.advance()
} while (isADigit(buf.currentCharacter))
}
to(neg ? T(-1) * localResult : localResult)
locationToScanFrom = buf.stringLoc
return true
}
internal func scanHex<T: _FloatLike>(skipSet: NSCharacterSet?, locale: NSLocale?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool {
NSUnimplemented()
}
}
extension NSScanner {
// On overflow, the below methods will return success and clamp
public func scanInt(result: UnsafeMutablePointer<Int32>) -> Bool {
return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: Int32) -> Void in
result.memory = value
}
}
public func scanInteger(result: UnsafeMutablePointer<Int>) -> Bool {
return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: Int) -> Void in
result.memory = value
}
}
public func scanLongLong(result: UnsafeMutablePointer<Int64>) -> Bool {
return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: Int64) -> Void in
result.memory = value
}
}
public func scanUnsignedLongLong(result: UnsafeMutablePointer<UInt64>) -> Bool {
return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: UInt64) -> Void in
result.memory = value
}
}
public func scanFloat(result: UnsafeMutablePointer<Float>) -> Bool {
return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Float) -> Void in
result.memory = value
}
}
public func scanDouble(result: UnsafeMutablePointer<Double>) -> Bool {
return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Double) -> Void in
result.memory = value
}
}
public func scanHexInt(result: UnsafeMutablePointer<UInt32>) -> Bool {
return _scanString.scanHex(_skipSet, locationToScanFrom: &scanLocation) { (value: UInt32) -> Void in
result.memory = value
}
}
public func scanHexLongLong(result: UnsafeMutablePointer<UInt64>) -> Bool {
return _scanString.scanHex(_skipSet, locationToScanFrom: &scanLocation) { (value: UInt64) -> Void in
result.memory = value
}
}
public func scanHexFloat(result: UnsafeMutablePointer<Float>) -> Bool {
return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Float) -> Void in
result.memory = value
}
}
public func scanHexDouble(result: UnsafeMutablePointer<Double>) -> Bool {
return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Double) -> Void in
result.memory = value
}
}
public var atEnd: Bool {
var stringLoc = scanLocation
let stringLen = string.length
if let invSet = invertedSkipSet {
let range = string._nsObject.rangeOfCharacterFromSet(invSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
return stringLoc == stringLen
}
public class func localizedScannerWithString(string: String) -> AnyObject { NSUnimplemented() }
}
/// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer and better Optional usage.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
extension NSScanner {
public func scanInt() -> Int32? {
var value: Int32 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int32>) -> Int32? in
if scanInt(ptr) {
return ptr.memory
} else {
return nil
}
}
}
public func scanInteger() -> Int? {
var value: Int = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int>) -> Int? in
if scanInteger(ptr) {
return ptr.memory
} else {
return nil
}
}
}
public func scanLongLong() -> Int64? {
var value: Int64 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int64>) -> Int64? in
if scanLongLong(ptr) {
return ptr.memory
} else {
return nil
}
}
}
public func scanUnsignedLongLong() -> UInt64? {
var value: UInt64 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in
if scanUnsignedLongLong(ptr) {
return ptr.memory
} else {
return nil
}
}
}
public func scanFloat() -> Float? {
var value: Float = 0.0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in
if scanFloat(ptr) {
return ptr.memory
} else {
return nil
}
}
}
public func scanDouble() -> Double? {
var value: Double = 0.0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in
if scanDouble(ptr) {
return ptr.memory
} else {
return nil
}
}
}
public func scanHexInt() -> UInt32? {
var value: UInt32 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt32>) -> UInt32? in
if scanHexInt(ptr) {
return ptr.memory
} else {
return nil
}
}
}
public func scanHexLongLong() -> UInt64? {
var value: UInt64 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in
if scanHexLongLong(ptr) {
return ptr.memory
} else {
return nil
}
}
}
public func scanHexFloat() -> Float? {
var value: Float = 0.0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in
if scanHexFloat(ptr) {
return ptr.memory
} else {
return nil
}
}
}
public func scanHexDouble() -> Double? {
var value: Double = 0.0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in
if scanHexDouble(ptr) {
return ptr.memory
} else {
return nil
}
}
}
// These methods avoid calling the private API for _invertedSkipSet and manually re-construct them so that it is only usage of public API usage
// Future implementations on Darwin of these methods will likely be more optimized to take advantage of the cached values.
public func scanString(string searchString: String) -> String? {
let str = self.string._bridgeToObjectiveC()
var stringLoc = scanLocation
let stringLen = str.length
let options: NSStringCompareOptions = [caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch, NSStringCompareOptions.AnchoredSearch]
if let invSkipSet = charactersToBeSkipped?.invertedSet {
let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
let range = str.rangeOfString(searchString, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc))
if range.length > 0 {
/* ??? Is the range below simply range? 99.9% of the time, and perhaps even 100% of the time... Hmm... */
let res = str.substringWithRange(NSMakeRange(stringLoc, range.location + range.length - stringLoc))
scanLocation = range.location + range.length
return res
}
return nil
}
public func scanCharactersFromSet(set: NSCharacterSet) -> String? {
let str = self.string._bridgeToObjectiveC()
var stringLoc = scanLocation
let stringLen = str.length
let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch
if let invSkipSet = charactersToBeSkipped?.invertedSet {
let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
var range = str.rangeOfCharacterFromSet(set.invertedSet, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc))
if range.length == 0 {
range.location = stringLen
}
if stringLoc != range.location {
let res = str.substringWithRange(NSMakeRange(stringLoc, range.location - stringLoc))
scanLocation = range.location
return res
}
return nil
}
public func scanUpToString(string: String) -> String? {
let str = self.string._bridgeToObjectiveC()
var stringLoc = scanLocation
let stringLen = str.length
let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch
if let invSkipSet = charactersToBeSkipped?.invertedSet {
let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
var range = str.rangeOfString(string, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc))
if range.length == 0 {
range.location = stringLen
}
if stringLoc != range.location {
let res = str.substringWithRange(NSMakeRange(stringLoc, range.location - stringLoc))
scanLocation = range.location
return res
}
return nil
}
public func scanUpToCharactersFromSet(set: NSCharacterSet) -> String? {
let str = self.string._bridgeToObjectiveC()
var stringLoc = scanLocation
let stringLen = str.length
let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch
if let invSkipSet = charactersToBeSkipped?.invertedSet {
let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
var range = str.rangeOfCharacterFromSet(set, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc))
if range.length == 0 {
range.location = stringLen
}
if stringLoc != range.location {
let res = str.substringWithRange(NSMakeRange(stringLoc, range.location - stringLoc))
scanLocation = range.location
return res
}
return nil
}
}