Implement path caching in indices

This commit is contained in:
Karoy Lorentey committed 2023-03-20 13:12:10 -07:00
1 parent 575937f6ff
commit 79bdcb66eb
18 files changed
+410 -426

No files matched your search

@@ -66,15 +66,24 @@ extension _BString {
precondition(start <= endIndex && end <= endIndex, "Invalid index")
guard start != end else { return 0 }
assert(!isEmpty)
let a = path(to: Swift.min(start, end), preferEnd: false)
let b = path(to: Swift.max(start, end), preferEnd: true)
if a.path.rope == b.path.rope {
return metric.distance(from: a.path.chunk, to: b.path.chunk, in: a.chunk)
}
let a = resolve(Swift.min(start, end), preferEnd: false)
let b = resolve(Swift.max(start, end), preferEnd: true)
var d = 0
d += rope.distance(from: a.path.rope, to: b.path.rope, in: metric)
d -= metric.distance(from: a.chunk.string.startIndex, to: a.path.chunk, in: a.chunk)
d += metric.distance(from: b.chunk.string.startIndex, to: b.path.chunk, in: b.chunk)
let ropeIndexA = a._rope!
let ropeIndexB = b._rope!
let chunkIndexA = a._chunkIndex
let chunkIndexB = b._chunkIndex
if ropeIndexA == ropeIndexB {
d = metric.distance(from: chunkIndexA, to: chunkIndexB, in: rope[ropeIndexA])
} else {
let chunkA = rope[ropeIndexA]
let chunkB = rope[ropeIndexB]
d += rope.distance(from: ropeIndexA, to: ropeIndexB, in: metric)
d -= metric.distance(from: chunkA.string.startIndex, to: chunkIndexA, in: chunkA)
d += metric.distance(from: chunkB.string.startIndex, to: chunkIndexB, in: chunkB)
}
return start <= end ? d : -d
}
@@ -139,70 +148,45 @@ extension _BString {
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
func _path(
_ i: Index,
offsetBy distance: Int,
in metric: some _StringMetric
) -> (path: Path, chunk: Chunk) {
var (path, chunk) = path(to: i, preferEnd: false)
var d = distance
let r = metric.formIndex(&path.chunk, offsetBy: &d, in: chunk)
if r.found {
return (path, chunk)
}
if r.forward {
assert(distance >= 0)
assert(path.chunk == chunk.string.endIndex)
d += metric.nonnegativeSize(of: chunk.summary)
rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false)
precondition(path.rope < rope.endIndex)
chunk = rope[path.rope]
path.chunk = metric.index(at: d, in: chunk)
return (path, chunk)
}
assert(distance <= 0)
assert(path.chunk == chunk.string.startIndex)
rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false)
chunk = rope[path.rope]
path.chunk = metric.index(at: d, in: chunk)
return (path, chunk)
}
func index(
_ i: Index,
offsetBy distance: Int,
in metric: some _StringMetric
) -> Index {
precondition(i <= endIndex, "Index out of bounds")
var (path, chunk) = path(to: i, preferEnd: i == endIndex || distance < 0)
let base = baseIndex(with: i, at: path.chunk)
let i = resolve(i, preferEnd: i == endIndex || distance < 0)
var ri = i._rope!
var ci = i._chunkIndex
var d = distance
let r = metric.formIndex(&path.chunk, offsetBy: &d, in: chunk)
var chunk = rope[ri]
let r = metric.formIndex(&ci, offsetBy: &d, in: chunk)
if r.found {
return index(base: base, offsetBy: path.chunk)
return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: ci)
}
if r.forward {
assert(distance >= 0)
assert(path.chunk == chunk.string.endIndex)
assert(ci == chunk.string.endIndex)
d += metric.nonnegativeSize(of: chunk.summary)
rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false)
if path.rope == rope.endIndex {
return Index(_utf8Offset: self.utf8Count)
let start = ri
rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false)
if ri == rope.endIndex {
return endIndex
}
chunk = rope[path.rope]
path.chunk = metric.index(at: d, in: chunk)
return index(of: path)
chunk = rope[ri]
ci = metric.index(at: d, in: chunk)
let base = i._utf8BaseOffset + rope.distance(from: start, to: ri, in: UTF8Metric())
return Index(baseUTF8Offset: base, rope: ri, chunk: ci)
}
assert(distance <= 0)
assert(path.chunk == chunk.string.startIndex)
rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false)
chunk = rope[path.rope]
path.chunk = metric.index(at: d, in: chunk)
return index(of: path)
assert(ci == chunk.string.startIndex)
let start = ri
rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false)
chunk = rope[ri]
ci = metric.index(at: d, in: chunk)
let base = i._utf8BaseOffset + rope.distance(from: start, to: ri, in: UTF8Metric())
return Index(baseUTF8Offset: base, rope: ri, chunk: ci)
}
func characterIndex(_ i: Index, offsetBy distance: Int) -> Index {
@@ -271,51 +255,57 @@ extension _BString {
func characterIndex(roundingDown i: Index) -> Index {
let offset = i._utf8Offset
precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds")
guard offset > 0, offset < utf8Count else { return Index(_utf8Offset: offset) }
guard offset > 0 else { return resolve(i, preferEnd: false) }
guard offset < utf8Count else { return resolve(i, preferEnd: true) }
var (path, chunk) = path(to: i, preferEnd: true)
var base = baseIndex(with: i, at: path.chunk)
let i = resolve(i, preferEnd: true)
var ri = i._rope!
let ci = i._chunkIndex
var chunk = rope[ri]
if chunk.hasBreaks {
let first = chunk.firstBreak
let last = chunk.lastBreak
if path.chunk == first || path.chunk == last {
return i
if ci == first || ci == last { return i }
if ci > last {
return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: last)
}
if path.chunk > chunk.lastBreak {
return base._advanceUTF8(by: chunk.string._utf8Offset(of: chunk.lastBreak))
}
if path.chunk > chunk.firstBreak {
let j = chunk.string._index(roundingDown: path.chunk)
return base._advanceUTF8(by: chunk.string._utf8Offset(of: j))
if ci > first {
let j = chunk.wholeCharacters._index(roundingDown: ci)
return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: j)
}
}
var i = path.rope
while i > self.rope.startIndex {
self.rope.formIndex(before: &i)
chunk = self.rope[i]
base = base._advanceUTF8(by: -chunk.utf8Count)
var baseOffset = i._utf8BaseOffset
while ri > self.rope.startIndex {
self.rope.formIndex(before: &ri)
chunk = self.rope[ri]
baseOffset -= chunk.utf8Count
if chunk.hasBreaks { break }
}
return base._advanceUTF8(by: chunk.lastBreak._utf8Offset)
return Index(baseUTF8Offset: baseOffset, rope: ri, chunk: chunk.lastBreak)
}
func unicodeScalarIndex(roundingDown i: Index) -> Index {
precondition(i <= endIndex, "Index out of bounds")
guard i > startIndex, i < endIndex else { return Index(_utf8Offset: i._utf8Offset) }
let (path, chunk) = path(to: i, preferEnd: true)
let j = chunk.string.unicodeScalars._index(roundingDown: path.chunk)
return i._advanceUTF8(by: j._utf8Offset - path.chunk._utf8Offset)
guard i > startIndex else { return resolve(i, preferEnd: false) }
guard i < endIndex else { return endIndex }
let start = self.resolve(i, preferEnd: false)
let ri = start._rope!
let chunk = self.rope[ri]
let ci = chunk.string.unicodeScalars._index(roundingDown: start._chunkIndex)
return Index(baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: ci)
}
func utf8Index(roundingDown i: Index) -> Index {
precondition(i <= endIndex, "Index out of bounds")
// Clear any UTF-16 offset
return Index(_utf8Offset: i._utf8Offset)
var r = i
r._clearUTF16TrailingSurrogate()
return r
}
func utf16Index(roundingDown i: Index) -> Index {
if i._utf16Delta > 0 {
if i._isUTF16TrailingSurrogate {
precondition(i <= endIndex, "Index out of bounds")
return i
}
@@ -325,83 +315,80 @@ extension _BString {
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
func _character(
at start: Path, base: Index?, in chunk: Chunk
) -> (character: Character, end: Path, base: Index?) {
let offset = chunk.string._utf8Offset(of: start.chunk)
let c = chunk.string[start.chunk]
let d = c.utf8.count
if offset + d < chunk.utf8Count {
return (
character: c,
end: Path(start.rope, chunk.string._utf8Index(at: offset + d)),
base: base)
func _character(at start: Index) -> (character: Character, end: Index) {
precondition(start._utf8Offset < utf8Count, "Index out of bounds")
let start = resolve(start, preferEnd: false)
var ri = start._rope!
var ci = start._chunkIndex
var chunk = rope[ri]
let char = chunk.string[ci]
let endOffset = start._utf8ChunkOffset + char.utf8.count
if endOffset < chunk.utf8Count {
let endIndex = chunk.string._utf8Index(at: endOffset)
return (char, Index(baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: endIndex))
}
var s = String(c)
var base = base
var i = start.rope
var j = start.chunk
var s = String(char)
var base = start._utf8BaseOffset + chunk.utf8Count
while true {
base = base?._advanceUTF8(by: rope[i].utf8Count)
rope.formIndex(after: &i)
guard i < rope.endIndex else {
j = "".endIndex
rope.formIndex(after: &ri)
guard ri < rope.endIndex else {
ci = "".endIndex
break
}
let chunk = rope[i]
chunk = rope[ri]
s.append(contentsOf: chunk.prefix)
if chunk.hasBreaks {
j = rope[i].firstBreak
ci = chunk.firstBreak
break
}
base += chunk.utf8Count
}
return (Character(s), Path(i, j), base)
return (Character(s), Index(baseUTF8Offset: base, rope: ri, chunk: ci))
}
subscript(utf8 index: Index) -> UInt8 {
precondition(index < endIndex, "Index out of bounds")
let (path, chunk) = path(to: index, preferEnd: false)
return chunk.string.utf8[path.chunk]
let index = resolve(index, preferEnd: false)
return rope[index._rope!].string.utf8[index._chunkIndex]
}
subscript(utf8 offset: Int) -> UInt8 {
let (path, chunk) = _path(startIndex, offsetBy: offset, in: UTF8Metric())
return chunk.string.utf8[path.chunk]
precondition(offset >= 0 && offset < utf8Count, "Offset out of bounds")
let index = utf8Index(at: offset)
return self[utf8: index]
}
subscript(utf16 index: Index) -> UInt16 {
precondition(index < endIndex, "Index out of bounds")
let (path, chunk) = path(to: index, preferEnd: false)
return chunk.string.utf16[path.chunk]
let index = resolve(index, preferEnd: false)
return rope[index._rope!].string.utf16[index._chunkIndex]
}
subscript(utf16 offset: Int) -> UInt16 {
let (path, chunk) = _path(startIndex, offsetBy: offset, in: UTF16Metric())
return chunk.string.utf16[path.chunk]
precondition(offset >= 0 && offset < utf16Count, "Offset out of bounds")
let index = utf16Index(at: offset)
return self[utf16: index]
}
subscript(character index: Index) -> Character {
precondition(index < endIndex, "Index out of bounds")
let (path, chunk) = path(to: index, preferEnd: false)
let base = baseIndex(with: index, at: path.chunk)
return _character(at: path, base: base, in: chunk).character
_character(at: index).character
}
subscript(character offset: Int) -> Character {
let (path, chunk) = _path(startIndex, offsetBy: offset, in: CharacterMetric())
return _character(at: path, base: nil, in: chunk).character
precondition(offset >= 0 && offset < utf8Count, "Offset out of bounds")
return _character(at: Index(_utf8Offset: offset)).character
}
subscript(unicodeScalar index: Index) -> Unicode.Scalar {
precondition(index < endIndex, "Index out of bounds")
let (path, chunk) = path(to: index, preferEnd: false)
return chunk.string.unicodeScalars[path.chunk]
let index = resolve(index, preferEnd: false)
return rope[index._rope!].string.unicodeScalars[index._chunkIndex]
}
subscript(unicodeScalar offset: Int) -> Unicode.Scalar {
precondition(offset >= 0 && offset < unicodeScalarCount, "Offset out of bounds")
let (path, chunk) = _path(startIndex, offsetBy: offset, in: UnicodeScalarMetric())
return chunk.string.unicodeScalars[path.chunk]
let index = unicodeScalarIndex(at: offset)
return self[unicodeScalar: index]
}
}
@@ -14,55 +14,54 @@
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
internal struct Index {
// The layout is similar to (and somewhat compatible with) String.Index.
// ┌──────────┬────────────────┬───────────────────────┐
// │ b63:b16 │ b15:b14 │ b13:b0 │
// ├──────────┼────────────────┼───────────────────────┤
// │ position │ transc. offset │ reserved │
// └──────────┴────────────────┴───────────────────────┘
internal var _rawBits: UInt64
internal init(_raw: UInt64) {
typealias Rope = _BString.Rope
// ┌─────────────────────┬──────────────┬────────────────────┐
// │ b63:b9 │ b8 │ b7:b0 │
// ├─────────────────────┼──────────────┼────────────────────┤
// │ UTF-8 global offset │ UTF-16 delta │ UTF-8 chunk offset │
// └─────────────────────┴──────────────┴────────────────────┘
var _rawBits: UInt64
/// A (possibly invalid) rope index.
var _rope: Rope.Index?
internal init(_raw: UInt64, rope: Rope.Index?) {
self._rawBits = _raw
self._rope = rope
}
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Index {
internal var _utf8Offset: Int {
Int(truncatingIfNeeded: _rawBits &>> 9)
}
internal var _isUTF16TrailingSurrogate: Bool {
_orderingValue & 1 != 0
}
/// The base offset of the addressed chunk. Only valid if `_rope` is not nil.
internal var _utf8BaseOffset: Int {
_utf8Offset - _utf8ChunkOffset
}
/// The offset within the addressed chunk. Only valid if `_rope` is not nil.
internal var _utf8ChunkOffset: Int {
assert(_rope != nil)
return Int(truncatingIfNeeded: _rawBits & 0xFF)
}
internal var _chunkIndex: String.Index {
assert(_rope != nil)
return String.Index(_utf8Offset: _utf8ChunkOffset, utf16Delta: _isUTF16TrailingSurrogate ? 1 : 0)
}
@inline(__always)
internal var _orderingValue: UInt64 {
_rawBits &>> 14
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Index: Equatable {
internal static func ==(left: Self, right: Self) -> Bool {
left._orderingValue == right._orderingValue
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Index: Comparable {
internal static func <(left: Self, right: Self) -> Bool {
left._orderingValue < right._orderingValue
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Index: Hashable {
internal func hash(into hasher: inout Hasher) {
hasher.combine(_orderingValue)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Index: CustomStringConvertible {
internal var description: String {
let offset = _utf16Delta == 0 ? "" : "+\(_utf16Delta)"
return "\(_utf8Offset)[utf8]\(offset)"
_rawBits &>> 8
}
}
@@ -71,36 +70,102 @@ extension _BString.Index {
@inline(__always)
internal static func _bitsForUTF8Offset(_ utf8Offset: Int) -> UInt64 {
let v = UInt64(truncatingIfNeeded: UInt(bitPattern: utf8Offset))
assert(v &>> 48 == 0)
return v &<< 16
}
@inline(__always)
internal static func _bitsForUTF16Delta(_ utf16Delta: Int) -> UInt64 {
let v = UInt64(truncatingIfNeeded: UInt(bitPattern: utf16Delta))
assert(v == v & 1)
return (v & 1) &<< 14
}
internal init(_utf8Offset: Int) {
_rawBits = Self._bitsForUTF8Offset(_utf8Offset)
}
internal init(_utf8Offset: Int, utf16Delta: Int) {
_rawBits = Self._bitsForUTF8Offset(_utf8Offset)
_rawBits |= Self._bitsForUTF16Delta(utf16Delta)
}
internal var _utf8Offset: Int {
Int(truncatingIfNeeded: _rawBits &>> 16)
}
internal var _utf16Delta: Int {
Int(truncatingIfNeeded: _orderingValue & 0x3)
assert(v &>> 55 == 0)
return v &<< 9
}
internal func _advanceUTF8(by delta: Int) -> Self {
Self(_utf8Offset: _utf8Offset + delta)
@inline(__always)
internal static var _utf16TrailingSurrogateBits: UInt64 { 0x100 }
internal mutating func _clearUTF16TrailingSurrogate() {
_rawBits &= ~Self._utf16TrailingSurrogateBits
}
internal init(_utf8Offset: Int) {
_rawBits = Self._bitsForUTF8Offset(_utf8Offset)
_rope = nil
}
internal init(_utf8Offset: Int, utf16TrailingSurrogate: Bool) {
_rawBits = Self._bitsForUTF8Offset(_utf8Offset)
if utf16TrailingSurrogate {
_rawBits |= Self._utf16TrailingSurrogateBits
}
_rope = nil
}
internal init(
_utf8Offset: Int, utf16TrailingSurrogate: Bool = false, rope: Rope.Index, chunkOffset: Int
) {
_rawBits = Self._bitsForUTF8Offset(_utf8Offset)
if utf16TrailingSurrogate {
_rawBits |= Self._utf16TrailingSurrogateBits
}
assert(chunkOffset >= 0 && chunkOffset <= 0xFF)
_rawBits |= UInt64(truncatingIfNeeded: chunkOffset) & 0xFF
self._rope = rope
}
internal init(baseUTF8Offset: Int, rope: Rope.Index, chunk: String.Index) {
let chunkUTF8Offset = chunk._utf8Offset
self.init(
_utf8Offset: baseUTF8Offset + chunkUTF8Offset,
utf16TrailingSurrogate: chunk._utf16Delta > 0,
rope: rope,
chunkOffset: chunkUTF8Offset)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Index: Equatable {
static func ==(left: Self, right: Self) -> Bool {
left._orderingValue == right._orderingValue
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Index: Comparable {
static func <(left: Self, right: Self) -> Bool {
left._orderingValue < right._orderingValue
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Index: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(_orderingValue)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Index: CustomStringConvertible {
internal var description: String {
let utf16Offset = _isUTF16TrailingSurrogate ? "+1" : ""
return "\(_utf8Offset)[utf8]\(utf16Offset)"
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
func resolve(_ i: Index, preferEnd: Bool) -> Index {
if var ri = i._rope, rope.isValid(ri) {
if preferEnd {
guard i._utf8ChunkOffset == 0 else { return i }
rope.formIndex(before: &ri)
let length = rope[ri].utf8Count
let ci = String.Index(_utf8Offset: length)
return Index(baseUTF8Offset: i._utf8Offset - length, rope: ri, chunk: ci)
}
guard i._utf8ChunkOffset == rope[ri].utf8Count else { return i }
rope.formIndex(after: &ri)
let ci = String.Index(_utf8Offset: 0)
return Index(baseUTF8Offset: i._utf8Offset, rope: ri, chunk: ci)
}
let (ri, chunkOffset) = rope.find(
at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd)
let ci = String.Index(_utf8Offset: chunkOffset, utf16Delta: i._isUTF16TrailingSurrogate ? 1 : 0)
return Index(baseUTF8Offset: i._utf8Offset - ci._utf8Offset, rope: ri, chunk: ci)
}
}
@@ -17,10 +17,10 @@ extension _BString {
forInserting input: __owned Substring,
at index: Index,
allowForwardPeek: Bool
) -> (ingester: Ingester, start: Path, end: Path) {
) -> Ingester {
let hint = allowForwardPeek ? input.unicodeScalars.first : nil
let r = self._breakState(upTo: index, nextScalarHint: hint)
return (Ingester(input, startState: r.state), r.start, r.end)
let state = self._breakState(upTo: index, nextScalarHint: hint)
return Ingester(input, startState: state)
}
}
@@ -119,10 +119,12 @@ extension _BString {
}
internal func makeUnicodeScalarIterator(from index: Index) -> UnicodeScalarIterator {
let (path, chunk) = self.path(to: index, preferEnd: false)
var base = self.rope.makeIterator(from: path.rope)
let i = resolve(index, preferEnd: index == endIndex)
let ropeIndex = i._rope!
let chunkIndex = i._chunkIndex
var base = self.rope.makeIterator(from: ropeIndex)
_ = base.next()
return UnicodeScalarIterator(_base: base, chunk, path.chunk)
return UnicodeScalarIterator(_base: base, rope[ropeIndex], chunkIndex)
}
}
@@ -181,11 +183,11 @@ extension _BString {
self._next = "".endIndex
return
}
let path = string.path(to: start, preferEnd: false).path
self._i = path.rope
self._utf8BaseOffset -= path.chunk._utf8Offset
self._index = path.chunk
self._next = _base.rope[_i].wholeCharacters.index(after: path.chunk)
let i = string.resolve(start, preferEnd: false)
self._i = i._rope!
self._utf8BaseOffset = i._utf8BaseOffset
self._index = i._chunkIndex
self._next = _base.rope[_i].wholeCharacters.index(after: _index)
}
}
@@ -327,10 +329,13 @@ extension _BString.CharacterIterator {
return Range(uncheckedBounds: (start, end))
}
func isBelow(_ path: _BString.Path) -> Bool {
if _i < path.rope { return true }
guard _i == path.rope else { return false }
return self._index < path.chunk
func isBelow(_ index: _BString.Index) -> Bool {
assert(index._rope != nil)
let ropeIndex = index._rope!
let chunkIndex = index._chunkIndex
if _i < ropeIndex { return true }
guard _i == ropeIndex else { return false }
return self._index < chunkIndex
}
}
@@ -1,92 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2023 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
//
//===----------------------------------------------------------------------===//
#if swift(>=5.8)
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
struct Path {
var rope: Rope.Index
var _chunk: UInt16
init(startOf rope: Rope.Index) {
self.rope = rope
self._chunk = 0
}
init(_ rope: Rope.Index, _ chunk: String.Index) {
self.rope = rope
self._chunk = chunk._chunkData
}
var chunk: String.Index {
get {
String.Index(_chunkData: _chunk)
}
set {
_chunk = newValue._chunkData
}
_modify {
var index = self.chunk
defer {
self.chunk = index
}
yield &index
}
}
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Path: CustomStringConvertible {
var description: String {
"\(rope).\(chunk._description)"
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
func path(
to i: Index,
preferEnd: Bool
) -> (path: Path, chunk: Chunk) {
let (ropeIndex, remaining) = rope.find(
at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd)
let chunk = rope[ropeIndex]
let chunkIndex = chunk.index(at: remaining, utf16Delta: i._utf16Delta)
return (Path(ropeIndex, chunkIndex), chunk)
}
}
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
func baseIndex(
with index: Index,
at chunkIndex: String.Index
) -> Index {
Index(_utf8Offset: index._utf8Offset - chunkIndex._utf8Offset)
}
func index(base: Index, offsetBy index: String.Index) -> Index {
assert(index._canBeUTF8)
return Index(
_utf8Offset: base._utf8Offset + index._utf8Offset,
utf16Delta: index._utf16Delta)
}
func index(of path: Path) -> Index {
let position = rope.distance(from: rope.startIndex, to: path.rope, in: UTF8Metric())
let base = Index(_utf8Offset: position)
return index(base: base, offsetBy: path.chunk)
}
}
#endif
@@ -14,14 +14,13 @@
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString.Chunk {
/// UTF-16 index lookup.
func index(at utf8Offset: Int, utf16Delta: Int) -> String.Index {
func index(at utf8Offset: Int, utf16TrailingSurrogate: Bool) -> String.Index {
var index = string._utf8Index(at: utf8Offset)
if
utf16Delta != 0,
utf16TrailingSurrogate,
index < string.endIndex,
string.utf8[index]._isUTF8NonBMPLeadingCodeUnit
{
assert(utf16Delta == 1)
index = string.utf16.index(after: index)
}
return index
@@ -15,7 +15,6 @@
extension _BString {
struct Chunk {
typealias Slice = (string: Substring, characters: Int, prefix: Int, suffix: Int)
typealias Path = _BString.Path
var string: String
var counts: Counts
@@ -56,12 +56,12 @@ extension _BString {
// FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees.
var it1 = left.makeCharacterIterator(from: leftRange.lowerBound)
var it2 = right.makeCharacterIterator(from: rightRange.upperBound)
var it2 = right.makeCharacterIterator(from: rightRange.lowerBound)
if leftRange._isEmptyUTF8 { return rightRange._isEmptyUTF8 }
let leftEnd = left.path(to: leftRange.upperBound, preferEnd: true).path
let rightEnd = right.path(to: rightRange.upperBound, preferEnd: true).path
let leftEnd = left.resolve(leftRange.upperBound, preferEnd: true)
let rightEnd = right.resolve(rightRange.upperBound, preferEnd: true)
var a: Character? = nil
var b: Character? = nil
@@ -81,8 +81,7 @@ extension _BString {
// split up on random Character boundaries -- Unicode does not promise that
// norm(a + c) == norm(a) + norm(b) in this case.
// To do this properly, we'll probably need to expose new stdlib entry points. :-/
if self.isIdentical(to: other) { return true }
guard self.characterCount == other.characterCount else { return false }
if self.isIdentical(to: other) { return false }
// FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees.
var it1 = self.makeCharacterIterator()
var it2 = other.makeCharacterIterator()
@@ -27,7 +27,7 @@ extension _BString {
self = Self(other)
return
}
var ingester = ingester(forInserting: other, at: endIndex, allowForwardPeek: true).ingester
var ingester = ingester(forInserting: other, at: endIndex, allowForwardPeek: true)
let last = rope.index(before: rope.endIndex)
if let final = rope[last].append(from: &ingester) {
@@ -66,7 +66,7 @@ extension _BString {
let hint = other._firstUnicodeScalar
var other = other.rope
var old = _CharacterRecognizer()
var new = self._breakState(upTo: endIndex, nextScalarHint: hint).state
var new = self._breakState(upTo: endIndex, nextScalarHint: hint)
_ = other.resyncBreaks(old: &old, new: &new)
_append(other)
}
@@ -81,7 +81,7 @@ extension _BString {
var other = _BString(other, in: range)
let hint = other._firstUnicodeScalar
var old = _CharacterRecognizer()
var new = self._breakState(upTo: endIndex, nextScalarHint: hint).state
var new = self._breakState(upTo: endIndex, nextScalarHint: hint)
_ = other.rope.resyncBreaks(old: &old, new: &new)
_append(other.rope)
}
@@ -94,9 +94,8 @@ extension _BString {
}
let hint = self._firstUnicodeScalar
var old = _CharacterRecognizer()
var new = other._breakState(upTo: other.endIndex, nextScalarHint: hint).state
var new = other._breakState(upTo: other.endIndex, nextScalarHint: hint)
_ = self.rope.resyncBreaks(old: &old, new: &new)
_prepend(other.rope)
}
@@ -109,7 +108,7 @@ extension _BString {
}
let hint = self._firstUnicodeScalar
var old = _CharacterRecognizer()
var new = extract._breakState(upTo: extract.endIndex, nextScalarHint: hint).state
var new = extract._breakState(upTo: extract.endIndex, nextScalarHint: hint)
_ = self.rope.resyncBreaks(old: &old, new: &new)
_prepend(extract.rope)
}
@@ -58,7 +58,7 @@ extension _BString {
from: range.lowerBound._utf8Offset,
to: range.upperBound._utf8Offset,
in: UTF8Metric())
var old = other._breakState(upTo: range.lowerBound).state
var old = other._breakState(upTo: range.lowerBound)
var new = _CharacterRecognizer()
_ = self.rope.resyncBreaks(old: &old, new: &new)
}
@@ -72,7 +72,7 @@ extension _BString {
from: range.lowerBound._utf8Offset,
to: range.upperBound._utf8Offset,
in: UTF8Metric())
var old = other._breakState(upTo: range.lowerBound).state
var old = other._breakState(upTo: range.lowerBound)
var new = state
self.rope.resyncBreaksToEnd(old: &old, new: &new)
}
@@ -98,32 +98,32 @@ extension String {
internal init(_from big: _BString, in range: Range<_BString.Index>) {
self.init()
let estimatedUTF8Size = range.upperBound._utf8Offset - range.lowerBound._utf8Offset
guard estimatedUTF8Size > 0 else {
// We can safely ignore UTF-16 offsets, as we're rounding down to scalar boundaries
// anyway.
return
}
// Note: if the range isn't scalar aligned, then this may be slightly under- or overestimating
// the actual size of the result. (Underestimations can be problematic due to String's
// exponential resizing. If those become an issue, consider adding +3 here.)
self.reserveCapacity(estimatedUTF8Size)
let start = big.path(to: range.lowerBound, preferEnd: false)
let end = big.path(to: range.upperBound, preferEnd: true)
if start.path.rope == end.path.rope {
self += start.chunk.string[start.path.chunk ..< end.path.chunk]
var start = big.unicodeScalarIndex(roundingDown: range.lowerBound)
start = big.resolve(start, preferEnd: false)
var end = big.unicodeScalarIndex(roundingDown: range.upperBound)
end = big.resolve(end, preferEnd: true)
let utf8Capacity = end._utf8Offset - start._utf8Offset
guard utf8Capacity > 0 else { return }
self.reserveCapacity(utf8Capacity)
let startRopeIndex = start._rope!
let endRopeIndex = end._rope!
if startRopeIndex == endRopeIndex {
self += big.rope[startRopeIndex].string[start._chunkIndex ..< end._chunkIndex]
return
}
self += start.chunk.string[start.path.chunk...]
var i = big.rope.index(after: start.path.rope)
while i < end.path.rope {
self += big.rope[startRopeIndex].string[start._chunkIndex...]
var i = big.rope.index(after: startRopeIndex)
while i < endRopeIndex {
self += big.rope[i].string
big.rope.formIndex(after: &i)
}
self += end.chunk.string[..<end.path.chunk]
self += big.rope[endRopeIndex].string[..<end._chunkIndex]
}
}
@@ -35,23 +35,27 @@ extension _BString {
// Note: we must disable the forward peeking optimization as we'll need to know the actual
// full grapheme breaking state of the ingester at the start of the insertion.
// (We'll use it to resync grapheme breaks in the parts that follow the insertion.)
var (ingester, _, path) = ingester(forInserting: other, at: index, allowForwardPeek: false)
let i = path.chunk
let r = rope.update(at: &path.rope) { $0.insert(from: &ingester, at: i) }
let index = self.resolve(index, preferEnd: true)
var ingester = ingester(forInserting: other, at: index, allowForwardPeek: false)
var ri = index._rope!
var ci = index._chunkIndex
let r = rope.update(at: &ri) { $0.insert(from: &ingester, at: ci) }
switch r {
case let .inline(r):
assert(ingester.isAtEnd)
guard var r = r else { break }
let i = index._advanceUTF8(by: r.increment)
ci = String.Index(_utf8Offset: ci._utf8Offset + r.increment)
let i = Index(baseUTF8Offset: index._utf8BaseOffset, rope: ri, chunk: ci)
resyncBreaks(startingAt: i, old: &r.old, new: &r.new)
case let .split(spawn: spawn, endStates: r):
assert(ingester.isAtEnd)
rope.insert(spawn, at: rope.index(after: path.rope))
rope.formIndex(after: &ri)
rope.insert(spawn, at: ri)
guard var r = r else { break }
let i = index._advanceUTF8(by: r.increment)
let i = Index(_utf8Offset: index._utf8Offset + r.increment, rope: ri, chunkOffset: spawn.utf8Count)
resyncBreaks(startingAt: i, old: &r.old, new: &r.new)
case .large:
var builder = self._split(at: path, state: ingester.state)
var builder = self.split(at: index, state: ingester.state)
builder.append(from: &ingester)
self = builder.finalize()
}
@@ -14,56 +14,50 @@
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
func _breakState(
upTo end: Path,
in chunk: Chunk,
upTo index: Index,
nextScalarHint: Unicode.Scalar? = nil
) -> (prevBreak: Path, state: _CharacterRecognizer) {
guard end.rope > rope.startIndex || end._chunk > 0 else {
return (Path(startOf: rope.startIndex), _CharacterRecognizer())
) -> _CharacterRecognizer {
assert(index == unicodeScalarIndex(roundingDown: index))
guard index > startIndex else {
return _CharacterRecognizer()
}
let index = resolve(index, preferEnd: true)
let ropeIndex = index._rope!
let chunkIndex = index._chunkIndex
let chunk = rope[ropeIndex]
guard ropeIndex > rope.startIndex || chunkIndex > chunk.string.startIndex else {
return _CharacterRecognizer()
}
if let next = nextScalarHint, end.chunk > chunk.string.startIndex {
let i = chunk.string.unicodeScalars.index(before: end.chunk)
if let next = nextScalarHint, chunkIndex > chunk.string.startIndex {
let i = chunk.string.unicodeScalars.index(before: chunkIndex)
let prev = chunk.string.unicodeScalars[i]
if _CharacterRecognizer.quickBreak(between: prev, and: next) == true {
return (end, _CharacterRecognizer())
return _CharacterRecognizer()
}
}
if let r = chunk.immediateBreakState(upTo: end.chunk) {
return (Path(end.rope, r.prevBreak), r.state)
if let r = chunk.immediateBreakState(upTo: chunkIndex) {
return r.state
}
// Find chunk that includes the start of the character.
var i = end.rope
while i > rope.startIndex {
rope.formIndex(before: &i)
if rope[i].hasBreaks { break }
var ri = ropeIndex
while ri > rope.startIndex {
rope.formIndex(before: &ri)
if rope[ri].hasBreaks { break }
}
precondition(i < end.rope)
let prev = Path(i, rope[i].lastBreak)
precondition(ri < ropeIndex)
// Collect grapheme breaking state.
var state = _CharacterRecognizer(partialCharacter: rope[i].suffix)
rope.formIndex(after: &i)
while i < end.rope {
state.consumePartialCharacter(rope[i].string[...])
rope.formIndex(after: &i)
var state = _CharacterRecognizer(partialCharacter: rope[ri].suffix)
rope.formIndex(after: &ri)
while ri < ropeIndex {
state.consumePartialCharacter(rope[ri].string[...])
rope.formIndex(after: &ri)
}
state.consumePartialCharacter(rope[end.rope].string[..<end.chunk])
return (prev, state)
}
func _breakState(
upTo index: Index,
nextScalarHint: Unicode.Scalar? = nil
) -> (start: Path, end: Path, state: _CharacterRecognizer) {
guard index > startIndex else {
let dummy = Path(startOf: rope.startIndex)
return (dummy, dummy, _CharacterRecognizer())
}
let end = path(to: index, preferEnd: true)
let r = _breakState(upTo: end.path, in: end.chunk, nextScalarHint: nextScalarHint)
return (r.prevBreak, end.path, r.state)
state.consumePartialCharacter(chunk.string[..<chunkIndex])
return state
}
}
@@ -76,19 +70,21 @@ extension _BString {
startingAt index: Index,
old: inout _CharacterRecognizer,
new: inout _CharacterRecognizer
) -> Path? {
) -> (ropeIndex: Rope.Index, chunkIndex: String.Index)? {
guard index < endIndex else { return nil }
let p = path(to: index, preferEnd: false).path
var path = (rope: p.rope, chunk: p.chunk)
let end = rope.mutatingForEach(from: &path.rope) { chunk in
let start = path.chunk
path.chunk = "".startIndex
return chunk.resyncBreaks(startingAt: start, old: &old, new: &new)
let i = resolve(index, preferEnd: false)
var ropeIndex = i._rope!
var chunkIndex = i._chunkIndex
let end = rope.mutatingForEach(from: &ropeIndex) { chunk in
let start = chunkIndex
chunkIndex = String.Index(_utf8Offset: 0)
if let i = chunk.resyncBreaks(startingAt: start, old: &old, new: &new) {
return i
}
return nil
}
guard let end else { return nil }
path.chunk = end
return Path(path.rope, path.chunk)
return (ropeIndex, end)
}
mutating func resyncBreaksToEnd(
@@ -97,7 +93,7 @@ extension _BString {
new: inout _CharacterRecognizer
) {
guard let _ = resyncBreaks(startingAt: index, old: &old, new: &new) else { return }
let state = _breakState(upTo: endIndex).state
let state = _breakState(upTo: endIndex)
old = state
new = state
}
@@ -109,40 +105,35 @@ extension _BString.Rope {
old: inout _CharacterRecognizer,
new: inout _CharacterRecognizer
) -> Bool {
var index = startIndex
let r = self.mutatingForEach(from: &index) {
$0.resyncBreaksFromStart(old: &old, new: &new)
}
return r != nil
_resyncBreaks(old: &old, new: &new) != nil
}
mutating func _resyncBreaks(
old: inout _CharacterRecognizer,
new: inout _CharacterRecognizer
) -> (path: Index, String.Index)? {
var index = startIndex
let r = self.mutatingForEach(from: &index) {
) -> (ropeIndex: Index, chunkIndex: String.Index)? {
var ropeIndex = startIndex
let chunkIndex = self.mutatingForEach(from: &ropeIndex) {
$0.resyncBreaksFromStart(old: &old, new: &new)
}
guard let r else { return nil }
return (index, r)
guard let chunkIndex else { return nil }
return (ropeIndex, chunkIndex)
}
mutating func resyncBreaksToEnd(
old: inout _CharacterRecognizer,
new: inout _CharacterRecognizer
) {
guard let (index, stringIndex) = _resyncBreaks(old: &old, new: &new) else { return }
guard let (ropeIndex, chunkIndex) = _resyncBreaks(old: &old, new: &new) else { return }
let chars = self.summary.characters
if chars > 0 {
var i = endIndex
while i > startIndex {
while i > ropeIndex {
formIndex(before: &i)
if self[i].hasBreaks { break }
if i == index { break }
}
if i > index || self[i].lastBreak > stringIndex {
if i > ropeIndex || self[i].lastBreak > chunkIndex {
new = self[i].immediateLastBreakState!
formIndex(after: &i)
while i < endIndex {
@@ -154,13 +145,13 @@ extension _BString.Rope {
}
}
var i = index
let suffix = self[i].string.unicodeScalars[stringIndex...].dropFirst()
var ri = ropeIndex
let suffix = self[ri].string.unicodeScalars[chunkIndex...].dropFirst()
new.consumePartialCharacter(suffix)
formIndex(after: &i)
while i < endIndex {
new.consumePartialCharacter(self[i].string[...])
formIndex(after: &i)
formIndex(after: &ri)
while ri < endIndex {
new.consumePartialCharacter(self[ri].string[...])
formIndex(after: &ri)
}
old = new
}
@@ -25,22 +25,22 @@ extension _BString {
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
mutating func removeCharacter(at i: Index) -> Character {
let (start, chunk) = self.path(to: i, preferEnd: false)
let startBase = baseIndex(with: i, at: start.chunk)
let (character, end, endBase) = self._character(at: start, base: startBase, in: chunk)
let j = endBase!._advanceUTF8(by: end.chunk._utf8Offset)
self.removeSubrange(i ..< j)
let start = self.resolve(i, preferEnd: false)
let (character, end) = self._character(at: start)
self.removeSubrange(start ..< end)
return character
}
mutating func removeUnicodeScalar(at i: Index) -> Unicode.Scalar {
let (path, chunk) = self.path(to: i, preferEnd: false)
assert(path.chunk < chunk.string.endIndex)
let base = baseIndex(with: i, at: path.chunk)
let scalar = chunk.string.unicodeScalars[path.chunk]
let end = chunk.string.unicodeScalars.index(after: path.chunk)
let j = index(base: base, offsetBy: end)
self.removeSubrange(i ..< j)
precondition(i < endIndex, "Index out of bounds")
let start = unicodeScalarIndex(roundingDown: i)
let ropeIndex = start._rope!
let chunkIndex = start._chunkIndex
let chunk = rope[ropeIndex]
let scalar = chunk.string.unicodeScalars[chunkIndex]
let next = chunk.string.unicodeScalars.index(after: chunkIndex)
let end = Index(baseUTF8Offset: start._utf8BaseOffset, rope: ropeIndex, chunk: next)
self.removeSubrange(start ..< end)
return scalar
}
}
@@ -64,8 +64,8 @@ extension _BString {
// FIXME: Don't split the indices twice -- they are currently split once here and once in the
// builder initializer below.
let startState = _breakState(upTo: range.lowerBound).state
let endState = _breakState(upTo: range.upperBound).state
let startState = _breakState(upTo: range.lowerBound)
let endState = _breakState(upTo: range.upperBound)
let b = rope.builder(removing: lower ..< upper, in: UTF8Metric())
return Builder(base: b, prefixEndState: startState, suffixStartState: endState)
@@ -16,20 +16,27 @@ extension _BString {
mutating func split(
at index: Index
) -> Builder {
let b = rope.builder(splittingAt: index._utf8Offset, in: UTF8Metric())
let b = _ropeBuilder(at: index)
let state = b.breakState()
let builder = Builder(base: b, prefixEndState: state, suffixStartState: state)
return builder
}
mutating func _split(
at path: Path,
mutating func split(
at index: Index,
state: _CharacterRecognizer
) -> Builder {
let b = rope.split(at: path.rope, path.chunk)
let b = _ropeBuilder(at: index)
let builder = Builder(base: b, prefixEndState: state, suffixStartState: state)
return builder
}
mutating func _ropeBuilder(at index: Index) -> Rope.Builder {
if let ri = index._rope, rope.isValid(ri) {
return rope.split(at: ri, index._chunkIndex)
}
return rope.builder(splittingAt: index._utf8Offset, in: UTF8Metric())
}
}
#endif