Skip to content

Instantly share code, notes, and snippets.

@milseman
Created July 31, 2017 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milseman/8e9dba4a700a16ebeeccc6acd36a7e74 to your computer and use it in GitHub Desktop.
Save milseman/8e9dba4a700a16ebeeccc6acd36a7e74 to your computer and use it in GitHub Desktop.
extension String {
public func _compareStringLinux(_ rhs: String) -> Int {
// Fast lexigraphic comparison of (composed) pre-normalized prefixes
var lhsCore = self._core
var rhsCore = rhs._core
let minCount = Swift.min(lhsCore.count, rhsCore.count)
for idx in 0..<minCount {
// Detect when pre-normalization ends: Quick check if next code unit might be combining
if idx+1 < minCount && (lhsCore[idx+1] >= 0x300 || rhsCore[idx+1] >= 0x300) {
lhsCore = lhsCore[idx...]
rhsCore = rhsCore[idx...]
break
}
let lhsCU = lhsCore[idx]
let rhsCU = rhsCore[idx]
if lhsCU < rhsCU {
return -1
}
if rhsCU < lhsCU {
return 1
}
// Check for equality
if idx == minCount - 1 {
if lhsCore.count == rhsCore.count {
return 0
}
return lhsCore.count < rhsCore.count ? -1 : 1
}
}
// Fall back to UCA
return String(lhsCore)._compareDeterministicUnicodeCollation(String(rhsCore))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment