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
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Low-level helper functions and utilities for interpreting Unicode
//
@inlinable
@inline(__always)
internal func _decodeUTF8(_ x: UInt8) -> Unicode.Scalar {
_internalInvariant(UTF8.isASCII(x))
return Unicode.Scalar(_unchecked: UInt32(x))
}
@inlinable
@inline(__always)
internal func _decodeUTF8(_ x: UInt8, _ y: UInt8) -> Unicode.Scalar {
_internalInvariant(_utf8ScalarLength(x) == 2)
_internalInvariant(UTF8.isContinuation(y))
let x = UInt32(x)
let value = ((x & 0b0001_1111) &<< 6) | _continuationPayload(y)
return Unicode.Scalar(_unchecked: value)
}
@inlinable
@inline(__always)
internal func _decodeUTF8(
_ x: UInt8, _ y: UInt8, _ z: UInt8
) -> Unicode.Scalar {
_internalInvariant(_utf8ScalarLength(x) == 3)
_internalInvariant(UTF8.isContinuation(y) && UTF8.isContinuation(z))
let x = UInt32(x)
let value = ((x & 0b0000_1111) &<< 12)
| (_continuationPayload(y) &<< 6)
| _continuationPayload(z)
return Unicode.Scalar(_unchecked: value)
}
@inlinable
@inline(__always)
internal func _decodeUTF8(
_ x: UInt8, _ y: UInt8, _ z: UInt8, _ w: UInt8
) -> Unicode.Scalar {
_internalInvariant(_utf8ScalarLength(x) == 4)
_internalInvariant(
UTF8.isContinuation(y) && UTF8.isContinuation(z)
&& UTF8.isContinuation(w))
let x = UInt32(x)
let value = ((x & 0b0000_1111) &<< 18)
| (_continuationPayload(y) &<< 12)
| (_continuationPayload(z) &<< 6)
| _continuationPayload(w)
return Unicode.Scalar(_unchecked: value)
}
@inlinable
internal func _decodeScalar(
_ utf8: UnsafeBufferPointer<UInt8>, startingAt i: Int
) -> (Unicode.Scalar, scalarLength: Int) {
let cu0 = utf8[_unchecked: i]
let len = _utf8ScalarLength(cu0)
switch len {
case 1: return (_decodeUTF8(cu0), len)
case 2: return (_decodeUTF8(cu0, utf8[_unchecked: i &+ 1]), len)
case 3: return (_decodeUTF8(
cu0, utf8[_unchecked: i &+ 1], utf8[_unchecked: i &+ 2]), len)
case 4:
return (_decodeUTF8(
cu0,
utf8[_unchecked: i &+ 1],
utf8[_unchecked: i &+ 2],
utf8[_unchecked: i &+ 3]),
len)
default: Builtin.unreachable()
}
}
@inlinable
internal func _decodeScalar(
_ utf8: UnsafeBufferPointer<UInt8>, endingAt i: Int
) -> (Unicode.Scalar, scalarLength: Int) {
let len = _utf8ScalarLength(utf8, endingAt: i)
let (scalar, scalarLen) = _decodeScalar(utf8, startingAt: i &- len)
_internalInvariant(len == scalarLen)
return (scalar, len)
}
@inlinable @inline(__always)
internal func _utf8ScalarLength(_ x: UInt8) -> Int {
_internalInvariant(!UTF8.isContinuation(x))
if UTF8.isASCII(x) { return 1 }
// TODO(String micro-performance): check codegen
return (~x).leadingZeroBitCount
}
@inlinable @inline(__always)
internal func _utf8ScalarLength(
_ utf8: UnsafeBufferPointer<UInt8>, endingAt i: Int
) -> Int {
var len = 1
while UTF8.isContinuation(utf8[_unchecked: i &- len]) {
len &+= 1
}
_internalInvariant(len == _utf8ScalarLength(utf8[i &- len]))
return len
}
@inlinable
@inline(__always)
internal func _continuationPayload(_ x: UInt8) -> UInt32 {
return UInt32(x & 0x3F)
}
@inlinable
internal func _scalarAlign(
_ utf8: UnsafeBufferPointer<UInt8>, _ idx: Int
) -> Int {
guard _fastPath(idx != utf8.count) else { return idx }
var i = idx
while _slowPath(UTF8.isContinuation(utf8[_unchecked: i])) {
i &-= 1
_internalInvariant(i >= 0,
"Malformed contents: starts with continuation byte")
}
return i
}
//
// Scalar helpers
//
extension _StringGuts {
@inlinable
@inline(__always) // fast-path: fold common fastUTF8 check
internal func scalarAlign(_ idx: Index) -> Index {
let result: String.Index
if _fastPath(idx._isScalarAligned) {
result = idx
} else {
// TODO(String performance): isASCII check
result = scalarAlignSlow(idx)._scalarAligned._copyingEncoding(from: idx)
}
_internalInvariant(isOnUnicodeScalarBoundary(result),
"Alignment bit is set for non-aligned index")
_internalInvariant_5_1(result._isScalarAligned)
return result
}
@inline(never) // slow-path
@_alwaysEmitIntoClient // Swift 5.1
@_effects(releasenone)
internal func scalarAlignSlow(_ idx: Index) -> Index {
_internalInvariant_5_1(!idx._isScalarAligned)
if _slowPath(idx.transcodedOffset != 0 || idx._encodedOffset == 0) {
// Transcoded index offsets are already scalar aligned
return String.Index(_encodedOffset: idx._encodedOffset)
}
if _slowPath(self.isForeign) {
// In 5.1 this check was added to foreignScalarAlign, but when this is
// emitted into a client that then runs against a 5.0 stdlib, it calls
// a version of foreignScalarAlign that doesn't check for this, which
// ends up asking CFString for its endIndex'th character, which throws
// an exception. So we duplicate the check here for back deployment.
guard idx._encodedOffset != self.count else { return idx }
let foreignIdx = foreignScalarAlign(idx)
_internalInvariant_5_1(foreignIdx._isScalarAligned)
return foreignIdx
}
return String.Index(_encodedOffset:
self.withFastUTF8 { _scalarAlign($0, idx._encodedOffset) }
)
}
@inlinable
internal func fastUTF8ScalarLength(startingAt i: Int) -> Int {
_internalInvariant(isFastUTF8)
let len = _utf8ScalarLength(self.withFastUTF8 { $0[_unchecked: i] })
_internalInvariant((1...4) ~= len)
return len
}
@inlinable
internal func fastUTF8ScalarLength(endingAt i: Int) -> Int {
_internalInvariant(isFastUTF8)
return self.withFastUTF8 { utf8 in
_internalInvariant(i == utf8.count || !UTF8.isContinuation(utf8[i]))
var len = 1
while UTF8.isContinuation(utf8[i &- len]) {
_internalInvariant(i &- len > 0)
len += 1
}
_internalInvariant(len <= 4)
return len
}
}
@inlinable
internal func fastUTF8Scalar(startingAt i: Int) -> Unicode.Scalar {
_internalInvariant(isFastUTF8)
return self.withFastUTF8 { _decodeScalar($0, startingAt: i).0 }
}
@_alwaysEmitIntoClient
@inline(__always)
internal func isOnUnicodeScalarBoundary(_ offset: Int) -> Bool {
isOnUnicodeScalarBoundary(String.Index(_encodedOffset: offset))
}
@usableFromInline
@_effects(releasenone)
internal func isOnUnicodeScalarBoundary(_ i: String.Index) -> Bool {
_internalInvariant(i._encodedOffset <= count)
// TODO(String micro-performance): check isASCII
// Beginning and end are always scalar aligned; mid-scalar never is
guard i.transcodedOffset == 0 else { return false }
if i == self.startIndex || i == self.endIndex { return true }
if _fastPath(isFastUTF8) {
return self.withFastUTF8 {
return !UTF8.isContinuation($0[_unchecked: i._encodedOffset])
}
}
return i == foreignScalarAlign(i)
}
}
//
// Error-correcting helpers (U+FFFD for unpaired surrogates) for accessing
// contents of foreign strings
//
extension _StringGuts {
@_effects(releasenone)
private func _getForeignCodeUnit(at i: Int) -> UInt16 {
#if _runtime(_ObjC)
// Currently, foreign means NSString
return _object.withCocoaObject { _cocoaStringSubscript($0, i) }
#else
fatalError("No foreign strings on Linux in this version of Swift")
#endif
}
@usableFromInline
@_effects(releasenone)
internal func foreignErrorCorrectedScalar(
startingAt idx: String.Index
) -> (Unicode.Scalar, scalarLength: Int) {
_internalInvariant(idx.transcodedOffset == 0)
_internalInvariant(idx._encodedOffset < self.count)
let start = idx._encodedOffset
let leading = _getForeignCodeUnit(at: start)
if _fastPath(!UTF16.isSurrogate(leading)) {
return (Unicode.Scalar(_unchecked: UInt32(leading)), 1)
}
// Validate foreign strings on-read: trailing surrogates are invalid,
// leading need following trailing
//
// TODO(String performance): Consider having a valid performance flag
// available to check, and assert it's not set in the condition here.
let nextOffset = start &+ 1
if _slowPath(UTF16.isTrailSurrogate(leading) || nextOffset == self.count) {
return (Unicode.Scalar._replacementCharacter, 1)
}
let trailing = _getForeignCodeUnit(at: nextOffset)
if _slowPath(!UTF16.isTrailSurrogate(trailing)) {
return (Unicode.Scalar._replacementCharacter, 1)
}
return (UTF16._decodeSurrogates(leading, trailing), 2)
}
@_effects(releasenone)
internal func foreignErrorCorrectedScalar(
endingAt idx: String.Index
) -> (Unicode.Scalar, scalarLength: Int) {
_internalInvariant(idx.transcodedOffset == 0)
_internalInvariant(idx._encodedOffset <= self.count)
_internalInvariant(idx._encodedOffset > 0)
let end = idx._encodedOffset
let trailing = _getForeignCodeUnit(at: end &- 1)
if _fastPath(!UTF16.isSurrogate(trailing)) {
return (Unicode.Scalar(_unchecked: UInt32(trailing)), 1)
}
// Validate foreign strings on-read: trailing surrogates are invalid,
// leading need following trailing
//
// TODO(String performance): Consider having a valid performance flag
// available to check, and assert it's not set in the condition here.
let priorOffset = end &- 2
if _slowPath(UTF16.isLeadSurrogate(trailing) || priorOffset < 0) {
return (Unicode.Scalar._replacementCharacter, 1)
}
let leading = _getForeignCodeUnit(at: priorOffset)
if _slowPath(!UTF16.isLeadSurrogate(leading)) {
return (Unicode.Scalar._replacementCharacter, 1)
}
return (UTF16._decodeSurrogates(leading, trailing), 2)
}
@_effects(releasenone)
internal func foreignErrorCorrectedUTF16CodeUnit(
at idx: String.Index
) -> UInt16 {
_internalInvariant(idx.transcodedOffset == 0)
_internalInvariant(idx._encodedOffset < self.count)
let start = idx._encodedOffset
let cu = _getForeignCodeUnit(at: start)
if _fastPath(!UTF16.isSurrogate(cu)) {
return cu
}
// Validate foreign strings on-read: trailing surrogates are invalid,
// leading need following trailing
//
// TODO(String performance): Consider having a valid performance flag
// available to check, and assert it's not set in the condition here.
if UTF16.isLeadSurrogate(cu) {
let nextOffset = start &+ 1
guard nextOffset < self.count,
UTF16.isTrailSurrogate(_getForeignCodeUnit(at: nextOffset))
else { return UTF16._replacementCodeUnit }
} else {
let priorOffset = start &- 1
guard priorOffset >= 0,
UTF16.isLeadSurrogate(_getForeignCodeUnit(at: priorOffset))
else { return UTF16._replacementCodeUnit }
}
return cu
}
@usableFromInline @inline(never) // slow-path
@_effects(releasenone)
internal func foreignScalarAlign(_ idx: Index) -> Index {
guard idx._encodedOffset != self.count else { return idx._scalarAligned }
_internalInvariant(idx._encodedOffset < self.count)
let ecCU = foreignErrorCorrectedUTF16CodeUnit(at: idx)
if _fastPath(!UTF16.isTrailSurrogate(ecCU)) {
return idx._scalarAligned
}
_internalInvariant(idx._encodedOffset > 0,
"Error-correction shouldn't give trailing surrogate at position zero")
return String.Index(_encodedOffset: idx._encodedOffset &- 1)._scalarAligned
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func foreignErrorCorrectedGrapheme(
startingAt start: Int, endingAt end: Int
) -> Character {
#if _runtime(_ObjC)
_internalInvariant(self.isForeign)
// Both a fast-path for single-code-unit graphemes and validation:
// treat isolated surrogates as isolated graphemes
let count = end &- start
if start &- end == 1 {
return Character(String(self.foreignErrorCorrectedScalar(
startingAt: String.Index(_encodedOffset: start)
).0))
}
return withUnsafeTemporaryAllocation(
of: UInt16.self, capacity: count
) { buffer in
self._object.withCocoaObject {
_cocoaStringCopyCharacters(
from: $0,
range: start..<end,
into: buffer.baseAddress._unsafelyUnwrappedUnchecked
)
}
return Character(String._uncheckedFromUTF16(UnsafeBufferPointer(buffer)))
}
#else
fatalError("No foreign strings on Linux in this version of Swift")
#endif
}
}
// Higher level aggregate operations. These should only be called when the
// result is the sole operation done by a caller, otherwise it's always more
// efficient to use `withFastUTF8` in the caller.
extension _StringGuts {
@inlinable @inline(__always)
internal func errorCorrectedScalar(
startingAt i: Int
) -> (Unicode.Scalar, scalarLength: Int) {
if _fastPath(isFastUTF8) {
return withFastUTF8 { _decodeScalar($0, startingAt: i) }
}
return foreignErrorCorrectedScalar(
startingAt: String.Index(_encodedOffset: i))
}
@inlinable @inline(__always)
internal func errorCorrectedCharacter(
startingAt start: Int, endingAt end: Int
) -> Character {
if _fastPath(isFastUTF8) {
return withFastUTF8(range: start..<end) { utf8 in
return Character(unchecked: String._uncheckedFromUTF8(utf8))
}
}
return foreignErrorCorrectedGrapheme(startingAt: start, endingAt: end)
}
}
|