_BString: Additional fixes and new functionality

- New methods for rounding up indices
- Sendable conformances
- Fix UTF-16 strings sometimes leaking into chunks
- Iterator improvements / rewrites, incl. a chunked UTF-8
   buffer iterator.
- Support for comparing and hashing UTF-8 slices.
This commit is contained in:
Karoy Lorentey committed 2023-03-20 13:12:10 -07:00
1 parent 9bbdfdc497
commit 605e45b9b9
10 files changed
+316 -101

No files matched your search

@@ -202,9 +202,47 @@ extension _BString {
}
func utf8Index(_ i: Index, offsetBy distance: Int) -> Index {
let offset = i._utf8Offset + distance
precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds")
return Index(_utf8Offset: offset)
index(i, offsetBy: distance, in: UTF8Metric())
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index,
in metric: some _StringMetric
) -> Index? {
// FIXME: Do we need a direct implementation?
if distance >= 0 {
if limit >= i {
let d = self.distance(from: i, to: limit, in: metric)
if d < distance { return nil }
}
} else {
if limit <= i {
let d = self.distance(from: i, to: limit, in: metric)
if d > distance { return nil }
}
}
return self.index(i, offsetBy: distance, in: metric)
}
func characterIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
index(i, offsetBy: distance, limitedBy: limit, in: CharacterMetric())
}
func unicodeScalarIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
index(i, offsetBy: distance, limitedBy: limit, in: UnicodeScalarMetric())
}
func utf16Index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
index(i, offsetBy: distance, limitedBy: limit, in: UTF16Metric())
}
func utf8Index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
index(i, offsetBy: distance, limitedBy: limit, in: UTF8Metric())
}
}
@@ -223,9 +261,19 @@ extension _BString {
}
func utf8Index(after i: Index) -> Index {
let offset = i._utf8Offset + 1
precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds")
return Index(_utf8Offset: offset)
precondition(i < endIndex, "Can't advance above end index")
let i = resolve(i, preferEnd: false)
let ri = i._rope!
var ci = i._chunkIndex
var chunk = rope[ri]
chunk.string.utf8.formIndex(after: &ci)
if ci == chunk.string.endIndex {
return Index(
baseUTF8Offset: i._utf8BaseOffset + chunk.utf8Count,
rope: rope.index(after: ri),
chunk: String.Index(_utf8Offset: 0))
}
return Index(_utf8Offset: i._utf8Offset + 1, rope: ri, chunkOffset: ci._utf8Offset)
}
}
@@ -244,9 +292,22 @@ extension _BString {
}
func utf8Index(before i: Index) -> Index {
let offset = i._utf8Offset - 1
precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds")
return Index(_utf8Offset: offset)
precondition(i > startIndex, "Can't advance below start index")
let i = resolve(i, preferEnd: true)
var ri = i._rope!
let ci = i._chunkIndex
if ci._utf8Offset > 0 {
return Index(
_utf8Offset: i._utf8Offset &- 1,
rope: ri,
chunkOffset: ci._utf8Offset &- 1)
}
rope.formIndex(before: &ri)
let chunk = rope[ri]
return Index(
baseUTF8Offset: i._utf8BaseOffset - chunk.utf8Count,
rope: ri,
chunk: String.Index(_utf8Offset: chunk.utf8Count - 1))
}
}
@@ -313,6 +374,37 @@ extension _BString {
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
func characterIndex(roundingUp i: Index) -> Index {
let j = characterIndex(roundingDown: i)
if i == j { return j }
return characterIndex(after: j)
}
func unicodeScalarIndex(roundingUp i: Index) -> Index {
let j = unicodeScalarIndex(roundingDown: i)
if i == j { return j }
return unicodeScalarIndex(after: j)
}
func utf8Index(roundingUp i: Index) -> Index {
// Note: this orders UTF-16 trailing surrogate indices in between the first and second byte
// of the UTF-8 encoding.
let j = utf8Index(roundingDown: i)
if i == j { return j }
return utf8Index(after: j)
}
func utf16Index(roundingUp i: Index) -> Index {
// Note: if `i` addresses some byte in the middle of a non-BMP scalar then the result will
// point to the trailing surrogate.
let j = utf16Index(roundingDown: i)
if i == j { return j }
return utf16Index(after: j)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
func _character(at start: Index) -> (character: Character, end: Index) {
@@ -13,7 +13,7 @@
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
internal struct Index {
internal struct Index: Sendable {
typealias Rope = _BString.Rope
// ┌─────────────────────┬──────────────┬────────────────────┐
@@ -56,7 +56,8 @@ extension _BString.Index {
internal var _chunkIndex: String.Index {
assert(_rope != nil)
return String.Index(_utf8Offset: _utf8ChunkOffset, utf16Delta: _isUTF16TrailingSurrogate ? 1 : 0)
return String.Index(
_utf8Offset: _utf8ChunkOffset, utf16TrailingSurrogate: _isUTF16TrailingSurrogate)
}
@inline(__always)
@@ -164,7 +165,8 @@ extension _BString {
let (ri, chunkOffset) = rope.find(
at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd)
let ci = String.Index(_utf8Offset: chunkOffset, utf16Delta: i._isUTF16TrailingSurrogate ? 1 : 0)
let ci = String.Index(
_utf8Offset: chunkOffset, utf16TrailingSurrogate: i._isUTF16TrailingSurrogate)
return Index(baseUTF8Offset: i._utf8Offset - ci._utf8Offset, rope: ri, chunk: ci)
}
}
@@ -38,18 +38,25 @@ extension _BString.ChunkIterator: IteratorProtocol {
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
internal struct UTF8Iterator {
internal var _rope: Rope.Iterator
internal var _chunk: String.UTF8View.Iterator
internal init(_base: Rope.Iterator) {
self._rope = _base
let str = self._rope.next()?.string ?? ""
self._chunk = str.utf8.makeIterator()
internal let _base: _BString
internal var _index: _BString.Index
internal init(_base: _BString, from index: _BString.Index) {
self._base = _base
if index < _base.endIndex {
self._index = _base.resolve(index, preferEnd: false)
} else {
self._index = index
}
}
}
internal func makeUTF8Iterator() -> UTF8Iterator {
UTF8Iterator(_base: self.rope.makeIterator())
UTF8Iterator(_base: self, from: self.startIndex)
}
internal func makeUTF8Iterator(from index: Index) -> UTF8Iterator {
UTF8Iterator(_base: self, from: index)
}
}
@@ -58,12 +65,56 @@ extension _BString.UTF8Iterator: IteratorProtocol {
internal typealias Element = UInt8
internal mutating func next() -> UInt8? {
if let codeUnit = _chunk.next() {
return codeUnit
guard _index < _base.endIndex else { return nil }
// Hand-optimized from `_base.subscript(utf8:)` and `_base.utf8Index(after:)`.
var ri = _index._rope!
var ci = _index._chunkIndex
let chunk = _base.rope[ri]
let result = chunk.string.utf8[ci]
chunk.string.utf8.formIndex(after: &ci)
if ci < chunk.string.endIndex {
_index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci)
} else {
_index = _BString.Index(
baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count,
rope: _base.rope.index(after: ri),
chunk: String.Index(_utf8Offset: 0))
}
guard let chunk = _rope.next() else { return nil }
_chunk = chunk.string.utf8.makeIterator()
return _chunk.next()!
return result
}
internal mutating func next<R>(
maximumCount: Int,
with body: (UnsafeBufferPointer<UInt8>) -> (consumed: Int, result: R)
) -> R {
guard _index < _base.endIndex else {
let r = body(UnsafeBufferPointer(start: nil, count: 0))
precondition(r.consumed == 0)
return r.result
}
var ri = _index._rope!
var ci = _index._utf8ChunkOffset
var utf8Offset = _index._utf8Offset
var string = _base.rope[ri].string
let (haveMore, result) = string.withUTF8 { buffer in
let slice = buffer[ci...].prefix(maximumCount)
assert(!slice.isEmpty)
let (consumed, result) = body(UnsafeBufferPointer(rebasing: slice))
precondition(consumed >= 0 && consumed <= slice.count)
utf8Offset += consumed
ci += consumed
return (ci < buffer.count, result)
}
if haveMore {
_index = _BString.Index(_utf8Offset: utf8Offset, rope: ri, chunkOffset: ci)
} else {
_index = _BString.Index(
baseUTF8Offset: _index._utf8BaseOffset + string.utf8.count,
rope: _base.rope.index(after: ri),
chunk: String.Index(_utf8Offset: 0))
}
return result
}
}
@@ -280,7 +331,6 @@ extension _BString.CharacterIterator: IteratorProtocol {
return true
}
}
assert(_base.rope.isEmpty)
return false
}
@@ -302,7 +352,27 @@ extension _BString.CharacterIterator {
}
var index: _BString.Index {
_BString.Index(_utf8Offset: utf8Offset)
_BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _chunkIndex)
}
internal var nextIndex: _BString.Index {
assert(!isAtEnd)
let chunk = _base.rope[_ropeIndex]
if _next < chunk.string.endIndex {
return _BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _next)
}
var i = _base.rope.index(after: _ropeIndex)
var base = _utf8BaseOffset
while i < _base.rope.endIndex {
let chunk = _base.rope[i]
let b = chunk.firstBreak
if b < chunk.string.endIndex {
return _BString.Index(baseUTF8Offset: base, rope: i, chunk: b)
}
base += chunk.utf8Count
_base.rope.formIndex(after: &i)
}
return _base.endIndex
}
/// The UTF-8 offset range of the current character, measured from the start of the string.
@@ -330,13 +400,12 @@ extension _BString.CharacterIterator {
return Range(uncheckedBounds: (start, end))
}
func isAbove(_ index: _BString.Index) -> Bool {
self.utf8Offset > index._utf8Offset
}
func isBelow(_ index: _BString.Index) -> Bool {
assert(index._rope != nil)
let ropeIndex = index._rope!
let chunkIndex = index._chunkIndex
if _ropeIndex < ropeIndex { return true }
guard _ropeIndex == ropeIndex else { return false }
return self._chunkIndex < chunkIndex
self.utf8Offset < index._utf8Offset
}
}
@@ -26,6 +26,7 @@ extension _BString.Chunk: _RopeElement {
func invariantCheck() {
#if DEBUG
precondition(string.endIndex._canBeUTF8)
let c = utf8Count
if c == 0 {
precondition(counts == Counts(), "Non-empty counts")
@@ -26,6 +26,7 @@ extension _BString {
init(_ string: String, _ counts: Counts) {
self.string = string
self.string.makeContiguousUTF8()
self.counts = counts
invariantCheck()
}
@@ -38,9 +39,9 @@ extension _BString {
init(_ slice: Slice) {
self.string = String(slice.string)
var slice = slice
slice.string = self.string[...]
self.counts = Counts(slice)
self.string.makeContiguousUTF8()
self.counts = Counts((self.string[...], slice.characters, slice.prefix, slice.suffix))
invariantCheck()
}
}
}
@@ -103,46 +103,61 @@ extension _BString {
/// Lexicographically compare the UTF-8 representations of `left` to `right`, returning a Boolean
/// value indicating whether `left` is equal to `right`.
internal func utf8IsEqual(to other: Self) -> Bool {
guard self.rope.summary == other.rope.summary else { return false }
if self.isIdentical(to: other) { return true }
guard self.rope.summary == other.rope.summary else { return false }
// FIXME: Implement a structural comparison that ignores shared subtrees when possible.
// This is somewhat tricky as this is only possible to do when the shared subtrees start
// at the same logical position in both trees. Additionally, the two input trees may not
// have the same height, even if they are equal.
var it1 = self.makeChunkIterator()
var it2 = other.makeChunkIterator()
var s1: Substring = ""
var s2: Substring = ""
while true {
if s1.isEmpty {
s1 = it1.next()?[...] ?? ""
}
if s2.isEmpty {
s2 = it2.next()?[...] ?? ""
}
guard s1.isEmpty == s2.isEmpty else { return false }
if s1.isEmpty { break }
let c = Swift.min(s1.utf8.count, s2.utf8.count)
assert(c > 0)
let stop = s1.withUTF8 { b1 in
s2.withUTF8 { b2 in
for i in 0 ..< c {
guard b1[i] == b2[i] else {
return true
}
}
return false
var it1 = self.makeUTF8Iterator()
var it2 = other.makeUTF8Iterator()
var remaining = self.utf8Count
while remaining > 0 {
let consumed = it1.next(maximumCount: remaining) { b1 in
let consumed = it2.next(maximumCount: b1.count) { b2 in
guard b2.elementsEqual(b1.prefix(b2.count)) else { return (0, 0) }
return (b2.count, b2.count)
}
return (consumed, consumed)
}
if stop { return false }
s1 = s1.suffix(from: s1._utf8Index(at: c))
s2 = s2.suffix(from: s2._utf8Index(at: c))
guard consumed > 0 else { return false }
remaining -= consumed
}
return true
}
internal static func utf8IsEqual(
_ left: Self,
in leftRange: Range<Index>,
to right: Self,
in rightRange: Range<Index>
) -> Bool {
let leftUTF8Count = left.utf8Distance(from: leftRange.lowerBound, to: leftRange.upperBound)
let rightUTF8Count = right.utf8Distance(from: rightRange.lowerBound, to: rightRange.upperBound)
guard leftUTF8Count == rightUTF8Count else { return false }
var remaining = leftUTF8Count
var it1 = left.makeUTF8Iterator(from: leftRange.lowerBound)
var it2 = right.makeUTF8Iterator(from: rightRange.lowerBound)
while remaining > 0 {
let consumed = it1.next(maximumCount: remaining) { b1 in
let consumed = it2.next(maximumCount: b1.count) { b2 in
guard b2.elementsEqual(b1.prefix(b2.count)) else { return (0, 0) }
return (b2.count, b2.count)
}
return (consumed, consumed)
}
guard consumed > 0 else { return false }
remaining -= consumed
}
return true
}
/// Lexicographically compare the UTF-8 representations of `left` to `right`, returning a Boolean
/// value indicating whether `left` is ordered before `right`.
internal func utf8IsLess(than other: Self) -> Bool {
@@ -26,7 +26,7 @@ extension _BString {
}
hasher.combine(0xFF as UInt8)
}
internal func hashCharacters(into hasher: inout Hasher, from range: Range<Index>) {
var it = self.makeCharacterIterator(from: range.lowerBound)
let endOffset = range.upperBound._utf8Offset
@@ -37,10 +37,13 @@ extension _BString {
s.removeSubrange(i...)
}
s._withNFCCodeUnits { hasher.combine($0) }
if it.utf8Offset >= endOffset {
break
}
}
hasher.combine(0xFF as UInt8)
}
/// Feed the UTF-8 encoding of `self` into hasher, with a terminating byte.
internal func hashUTF8(into hasher: inout Hasher) {
for chunk in self.rope {
@@ -48,8 +51,54 @@ extension _BString {
string.withUTF8 {
hasher.combine(bytes: .init($0))
}
hasher.combine(0xFF as UInt8)
}
hasher.combine(0xFF as UInt8)
}
/// Feed the UTF-8 encoding of `self[start..<end]` into hasher, with a terminating byte.
internal func hashUTF8(into hasher: inout Hasher, from start: Index, to end: Index) {
assert(start <= end)
guard start < end else {
hasher.combine(0xFF as UInt8)
return
}
let start = resolve(start, preferEnd: false)
let end = resolve(start, preferEnd: true)
var ri = start._rope!
let endRopeIndex = end._rope!
if ri == endRopeIndex {
var str = self.rope[ri].string
str.withUTF8 {
let slice = UnsafeRawBufferPointer($0)[start._utf8ChunkOffset ..< end._utf8ChunkOffset]
hasher.combine(bytes: UnsafeRawBufferPointer(rebasing: slice))
}
hasher.combine(0xFF as UInt8)
return
}
var str = self.rope[ri].string
str.withUTF8 {
let slice = UnsafeRawBufferPointer($0).prefix(start._utf8ChunkOffset)
hasher.combine(bytes: UnsafeRawBufferPointer(rebasing: slice))
}
rope.formIndex(after: &ri)
while ri < endRopeIndex {
var string = rope[ri].string
string.withUTF8 {
hasher.combine(bytes: .init($0))
}
}
str = self.rope[ri].string
str.withUTF8 {
let slice = UnsafeRawBufferPointer($0)[..<end._utf8ChunkOffset]
hasher.combine(bytes: UnsafeRawBufferPointer(rebasing: slice))
}
hasher.combine(0xFF as UInt8)
}
}