Skip to content

[4.0][stdlib] Speed up Character construction #9282

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
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
16 changes: 16 additions & 0 deletions stdlib/public/core/StringCharacterView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,22 @@ extension String.CharacterView : BidirectionalCollection {
/// - Parameter position: A valid index of the character view. `position`
/// must be less than the view's end index.
public subscript(i: Index) -> Character {
if i._countUTF16 == 1 {
// For single-code-unit graphemes, we can construct a Character directly
// from a single unicode scalar (if sub-surrogate).
let relativeOffset = i._base._position - _coreOffset
if _core.isASCII {
let asciiBuffer = _core.asciiBuffer._unsafelyUnwrappedUnchecked
return Character(UnicodeScalar(asciiBuffer[relativeOffset]))
} else if _core._baseAddress != nil {
let cu = _core._nthContiguous(relativeOffset)
// Only constructible if sub-surrogate
if (cu < 0xd800) {
return Character(UnicodeScalar(cu)._unsafelyUnwrappedUnchecked)
}
}
}

return Character(String(unicodeScalars[i._base..<i._endBase]))
}
}
Expand Down