From 96a16f6dc1a67c80588a9902f5010ecb7e823266 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 17 Jun 2025 16:45:14 -0700 Subject: [PATCH 1/4] [BigString] Add new tests exercising broken indexing operations --- Tests/RopeModuleTests/TestBigString.swift | 82 +++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index 8d0823ec..e198d0aa 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -1051,4 +1051,86 @@ class TestBigString: CollectionTestCase { expectNotEqual(cafe1.utf8, cafe2.utf8) expectNotEqual(cafe1.utf16, cafe2.utf16) } + + func test_single_overlong_character() { + withEvery("x", in: 0 ..< 300) { x in + let str = "a" + String(repeating: "\u{301}", count: x) + let big = BigString(str) + expectEqual(big.count, 1) + expectEqual(big.distance(from: big.startIndex, to: big.endIndex), 1) + expectEqual(big.index(after: big.startIndex), big.endIndex) + checkBidirectionalCollection(big, expectedContents: str) + } + } + + func test_characters_on_chunk_boundaries() { + withEvery("x", in: 0 ..< 5) { x in + let str = String(repeating: "a\u{301}\u{302}", count: 64) + String(repeating: "x", count: x) + let c = str.count + let big = BigString(str) + big._dump() + expectEqual(big.count, c) + expectEqual(big.distance(from: big.startIndex, to: big.endIndex), c) + checkBidirectionalCollection(big, expectedContents: str) + } + } + + func test_character_calculations_between_unaligned_utf8_indices() { + withEvery("x", in: 0 ..< 5) { x in + let str = String(repeating: "a\u{301}\u{302}", count: 64) + String(repeating: "x", count: x) + let flat = str // sampleString + let big = BigString(flat) + big._dump() + + let indices1 = Array(flat.utf8.indices) + [flat.endIndex] + let indices2 = Array(big.utf8.indices) + [big.endIndex] + + expectEqual(indices2.count, indices1.count) + let c = min(indices1.count, indices2.count) + withEvery("a", in: 0 ..< c) { a in + let i1 = indices1[a] + let i2 = indices2[a] + withEvery("b", in: a ..< c) { b in + let j1 = indices1[b] + let j2 = indices2[b] + + let d1 = flat.distance(from: i1, to: j1) + let d2 = big.distance(from: i2, to: j2) + expectEqual(d2, d1) + + let k2 = big.index(i2, offsetBy: d2) + expectEqual(k2, big.index(roundingDown: j2)) + } + } + } + } + + func test_character_calculations_between_unaligned_utf16_indices() { + withEvery("x", in: 0 ..< 5) { x in + let str = String(repeating: "🇨🇦🇺🇸", count: 16) + String(repeating: "x", count: x) + let flat = str // sampleString + let big = BigString(flat) + big._dump() + + let indices1 = Array(flat.utf16.indices) + [flat.endIndex] + let indices2 = Array(big.utf16.indices) + [big.endIndex] + expectEqual(indices2.count, indices1.count) + let c = min(indices1.count, indices2.count) + withEvery("a", in: 0 ..< c) { a in + let i1 = indices1[a] + let i2 = indices2[a] + withEvery("b", in: a ..< c) { b in + let j1 = indices1[b] + let j2 = indices2[b] + + let d1 = flat.distance(from: i1, to: j1) + let d2 = big.distance(from: i2, to: j2) + expectEqual(d2, d1) + + let k2 = big.index(i2, offsetBy: d2) + expectEqual(k2, big.index(roundingDown: j2)) + } + } + } + } } From 65f99e3eff346e5033d9ac9310021a4ff55a9a64 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 17 Jun 2025 17:08:23 -0700 Subject: [PATCH 2/4] [BigString] Fix character indexing operations BigString sometimes miscounted distances in its character view due to alignment issues. Resolve this by overhauling distance calculations in the character metric: - Introduce a `prefixSize` function in `_StringMetric`, distinct from `distance`. - In the metric-agnostic index distance algorithm, use `prefixCount` to avoid double-counting characters that cross (or end on) chunk boundaries. - Simplify `_StringMetric.distance` by requiring that `start <= end`. - Crucially, change character-index operations to start by rounding each input index down to the nearest character break. --- .../BigString/Basics/BigString+Contents.swift | 38 ++++++---- .../BigString/Basics/BigString+Metrics.swift | 71 +++++++++++++++++-- ...gString+Chunk+Indexing by Characters.swift | 37 ++++++++-- 3 files changed, 120 insertions(+), 26 deletions(-) diff --git a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift index ee9ae542..ff3029a3 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift @@ -51,28 +51,31 @@ extension BigString { assert(!isEmpty) let (lesser, greater) = (start <= end ? (start, end) : (end, start)) let a = resolve(lesser, preferEnd: false) - let b = resolve(greater, preferEnd: true) - var d = 0 + let b = resolve(greater, preferEnd: false) let ropeIndexA = a._rope! let ropeIndexB = b._rope! let chunkIndexA = a._chunkIndex let chunkIndexB = b._chunkIndex + assert(ropeIndexA != _rope.endIndex) // Handled above + var d = 0 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) + d = _rope.distance(from: ropeIndexA, to: ropeIndexB, in: metric) + d -= metric.prefixSize(to: chunkIndexA, in: _rope[ropeIndexA]) + if ropeIndexB != _rope.endIndex { + d += metric.prefixSize(to: chunkIndexB, in: _rope[ropeIndexB]) + } } return start <= end ? d : -d } func _characterDistance(from start: Index, to end: Index) -> Int { - _distance(from: start, to: end, in: _CharacterMetric()) + let start = _characterIndex(roundingDown: start) + let end = _characterIndex(roundingDown: end) + return _distance(from: start, to: end, in: _CharacterMetric()) } func _unicodeScalarDistance(from start: Index, to end: Index) -> Int { @@ -93,7 +96,8 @@ extension BigString { // FIXME: See if we need direct implementations for these. func _characterOffset(of index: Index) -> Int { - _characterDistance(from: startIndex, to: index) + let index = _characterIndex(roundingDown: index) + return _characterDistance(from: startIndex, to: index) } func _unicodeScalarOffset(of index: Index) -> Int { @@ -179,7 +183,9 @@ extension BigString { } func _characterIndex(_ i: Index, offsetBy distance: Int) -> Index { - _index(i, offsetBy: distance, in: _CharacterMetric())._knownCharacterAligned() + let i = _characterIndex(roundingDown: i) + let result = _index(i, offsetBy: distance, in: _CharacterMetric()) + return result._knownCharacterAligned() } func _unicodeScalarIndex(_ i: Index, offsetBy distance: Int) -> Index { @@ -219,6 +225,8 @@ extension BigString { } func _characterIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + let i = _characterIndex(roundingDown: i) + let limit = _characterIndex(roundingDown: limit) guard let j = _index(i, offsetBy: distance, limitedBy: limit, in: _CharacterMetric()) else { return nil } @@ -244,7 +252,8 @@ extension BigString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { func _characterIndex(after i: Index) -> Index { - _index(i, offsetBy: 1, in: _CharacterMetric())._knownCharacterAligned() + let i = _characterIndex(roundingDown: i) + return _index(i, offsetBy: 1, in: _CharacterMetric())._knownCharacterAligned() } func _unicodeScalarIndex(after i: Index) -> Index { @@ -275,7 +284,8 @@ extension BigString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { func _characterIndex(before i: Index) -> Index { - _index(i, offsetBy: -1, in: _CharacterMetric())._knownCharacterAligned() + let i = _characterIndex(roundingDown: i) + return _index(i, offsetBy: -1, in: _CharacterMetric())._knownCharacterAligned() } func _unicodeScalarIndex(before i: Index) -> Index { @@ -315,7 +325,7 @@ extension BigString { guard offset < _utf8Count else { return resolve(i, preferEnd: true)._knownCharacterAligned() } let i = resolve(i, preferEnd: false) - guard !i._isKnownCharacterAligned else { return resolve(i, preferEnd: false) } + guard !i._isKnownCharacterAligned else { return i } var ri = i._rope! let ci = i._chunkIndex @@ -323,7 +333,7 @@ extension BigString { if chunk.hasBreaks { let first = chunk.firstBreak let last = chunk.lastBreak - if ci == first || ci == last { return i } + if ci == first || ci == last { return i._knownCharacterAligned() } if ci > last { return Index( baseUTF8Offset: i._utf8BaseOffset, _rope: ri, chunk: last diff --git a/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift index 502eb2e9..4aeb696d 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift @@ -11,12 +11,35 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) internal protocol _StringMetric: RopeMetric where Element == BigString._Chunk { + /// Measure the distance between the given start and end positions within + /// the specified chunk. + /// + /// `start` must be less than or equal to the `end` position. The measurement + /// is done by (logically) first rounding both indices down to the nearest + /// metric boundary. + /// + /// In the character metric, an element may start and end in different chunks, + /// which considerably complicates distance measurement. To allow measuring + /// distances without looking at data in more than one chunk, both indices + /// are expected to address a known character boundary. func distance( from start: String.Index, to end: String.Index, in chunk: BigString._Chunk ) -> Int - + + /// Measure the distance between the start of this chunk and the given end + /// position. + /// + /// The end position is (logically) rounded down to the nearest metric + /// boundary before starting the measurement. + /// + /// In the character metric, an element may start and end in different chunks, + /// which considerably complicates distance measurement. To allow measuring + /// distances without looking at data in more than one chunk, the given end + /// index is expected to address a known character boundary. + func prefixSize(to end: String.Index, in chunk: BigString._Chunk) -> Int + func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, @@ -34,15 +57,33 @@ extension BigString { func size(of summary: Summary) -> Int { summary.characters } - + func distance( from start: String.Index, to end: String.Index, in chunk: BigString._Chunk ) -> Int { - chunk.characterDistance(from: start, to: end) + assert(start <= end) + return chunk.characterDistance(from: start, to: end) } + func prefixSize(to end: String.Index, in chunk: BigString._Chunk) -> Int { + // The prefix must not count the initial partial character that + // ends in the chunk (any scalar before the first break) -- that character + // logically belongs to (and counted in) a prior chunk: the one that + // contains its leading scalar. + // + // To measure the prefix, we must therefore start counting from the + // `firstBreak` position. We can guarantee that `firstBreak` is on a + // character break: either the chunk has known breaks in it (in which case + // `firstBreak` is obviously one of them), or the chunk has no known + // breaks, but we know that `end` is on one. So in that case, `end` must + // be on the end of the chunk, and `firstBreak` points to the same. + assert(chunk.hasBreaks || chunk.firstBreak == end) + return chunk.characterDistance(from: chunk.firstBreak, to: end) + } + + @inline(__always) func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, @@ -68,9 +109,14 @@ extension BigString { to end: String.Index, in chunk: BigString._Chunk ) -> Int { - chunk.string.unicodeScalars.distance(from: start, to: end) + assert(start <= end) + return chunk.string.unicodeScalars[start ..< end].count } - + + func prefixSize(to end: String.Index, in chunk: BigString._Chunk) -> Int { + return chunk.string.unicodeScalars[.. Int { chunk.string.utf8.distance(from: start, to: end) } - + + @inline(__always) + func prefixSize(to end: String.Index, in chunk: BigString._Chunk) -> Int { + end._utf8Offset + } + func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, @@ -161,9 +213,14 @@ extension BigString { to end: String.Index, in chunk: BigString._Chunk ) -> Int { - chunk.string.utf16.distance(from: start, to: end) + assert(start <= end) + return chunk.string.utf16[start ..< end].count } + func prefixSize(to end: String.Index, in chunk: BigString._Chunk) -> Int { + return chunk.string.utf16[.. Int { + func characterDistance( + from start: String.Index, + to end: String.Index + ) -> Int { + // Note: both indices must already have been rounded to a character + // boundary. + if start == end { return 0 } + // Character rounding never ends up in a chunk with no breaks, unless both + // indices are at the very end of an overlong character. (Handled above.) + assert(hasBreaks) let firstBreak = self.firstBreak - let (start, a) = start < firstBreak ? (firstBreak, 1) : (start, 0) - let (end, b) = end < firstBreak ? (firstBreak, 1) : (end, 0) - let d = wholeCharacters.distance(from: start, to: end) - return d + a - b + let lastBreak = self.lastBreak + + assert(start <= end) + + assert(start >= firstBreak && (start <= lastBreak || start._utf8Offset == self.utf8Count), + "start is not Character aligned") + assert(end >= firstBreak && (end <= lastBreak || end._utf8Offset == self.utf8Count), + "end is not Character aligned") + + let wholeCharacters = self.wholeCharacters + let s = Swift.max(start, firstBreak) + let e = Swift.min(end, lastBreak) + var result = wholeCharacters.distance(from: s, to: e) + + if end > lastBreak { + /// We know `end` is rounded, so it can only ever be after the last break + /// if the final partial character actually ends with this chunk. + /// In that case, we need to include that extra character here. + assert(end._utf8Offset == self.utf8Count) + result += 1 + } + return result } /// If this returns false, the next position is on the first grapheme break following this From f1b0eba9482d82251f383ea4964546d87db78903 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 17 Jun 2025 19:51:37 -0700 Subject: [PATCH 3/4] [BigString] Add some basic benchmarks --- Benchmarks/Libraries/BigString.json | 192 ++++++++++ .../Benchmarks/BigStringBenchmarks.swift | 352 +++++++++++++++++- 2 files changed, 543 insertions(+), 1 deletion(-) create mode 100644 Benchmarks/Libraries/BigString.json diff --git a/Benchmarks/Libraries/BigString.json b/Benchmarks/Libraries/BigString.json new file mode 100644 index 00000000..afc373d3 --- /dev/null +++ b/Benchmarks/Libraries/BigString.json @@ -0,0 +1,192 @@ +{ + "kind": "group", + "title": "BigString Benchmarks", + "directory": "BigString", + "contents": [ + { + "kind": "group", + "title": "BigString operations", + "directory": "BigString", + "contents": [ + { + "kind": "chart", + "title": "ingestion", + "tasks": [ + "BigString init from native string", + "BigString init from bridged string" + ] + }, + { + "kind": "chart", + "title": "sequential iteration", + "tasks": [ + "BigString character iteration", + "BigString scalar iteration", + "BigString UTF-16 iteration", + "BigString UTF-8 iteration" + ] + }, + { + "kind": "chart", + "title": "index-offset-by", + "tasks": [ + "BigString.index(offsetBy:)", + "BigString.unicodeScalars.index(offsetBy:)", + "BigString.utf16.index(offsetBy:)", + "BigString.utf8.index(offsetBy:)" + ] + }, + { + "kind": "chart", + "title": "distance", + "tasks": [ + "BigString.distance(from:to:)", + "BigString.unicodeScalars.distance(from:to:)", + "BigString.utf16.distance(from:to:)", + "BigString.utf8.distance(from:to:)" + ] + } + ] + }, + { + "kind": "group", + "title": "String operations", + "directory": "String", + "contents": [ + { + "kind": "chart", + "title": "sequential iteration", + "tasks": [ + "String character iteration", + "String scalar iteration", + "String UTF-16 iteration", + "String UTF-8 iteration" + ] + }, + { + "kind": "chart", + "title": "index-offset-by", + "tasks": [ + "String.index(offsetBy:)", + "String.unicodeScalars.index(offsetBy:)", + "String.utf16.index(offsetBy:)", + "String.utf8.index(offsetBy:)" + ] + }, + { + "kind": "chart", + "title": "distance", + "tasks": [ + "String.distance(from:to:)", + "String.unicodeScalars.distance(from:to:)", + "String.utf16.distance(from:to:)", + "String.utf8.distance(from:to:)" + ] + } + ] + }, + { + "kind": "group", + "title": "BigString vs String", + "directory": "versus String", + "contents": [ + { + "kind": "chart", + "title": "character iteration", + "tasks": [ + "BigString character iteration", + "String character iteration" + ] + }, + { + "kind": "chart", + "title": "scalar iteration", + "tasks": [ + "BigString scalar iteration", + "String scalar iteration" + ] + }, + { + "kind": "chart", + "title": "UTF-8 iteration", + "tasks": [ + "BigString UTF-8 iteration", + "String UTF-8 iteration" + ] + }, + { + "kind": "chart", + "title": "UTF-16 iteration", + "tasks": [ + "BigString UTF-16 iteration", + "String UTF-16 iteration" + ] + }, + { + "kind": "chart", + "title": "Character-based index(offsetBy:)", + "tasks": [ + "BigString.index(offsetBy:)", + "String.index(offsetBy:)" + ] + }, + { + "kind": "chart", + "title": "UnicodeScalar-based index(offsetBy:)", + "tasks": [ + "BigString.unicodeScalars.index(offsetBy:)", + "String.unicodeScalars.index(offsetBy:)" + ] + }, + { + "kind": "chart", + "title": "UTF-8 index(offsetBy:)", + "tasks": [ + "BigString.utf8.index(offsetBy:)", + "String.utf8.index(offsetBy:)" + ] + }, + { + "kind": "chart", + "title": "UTF-16 index(offsetBy:)", + "tasks": [ + "BigString.utf16.index(offsetBy:)", + "String.utf16.index(offsetBy:)" + ] + }, + { + "kind": "chart", + "title": "Character-based distance", + "tasks": [ + "BigString.distance(from:to:)", + "String.distance(from:to:)" + ] + }, + { + "kind": "chart", + "title": "UnicodeScalar-based distance", + "tasks": [ + "BigString.unicodeScalars.distance(from:to:)", + "String.unicodeScalars.distance(from:to:)" + ] + }, + { + "kind": "chart", + "title": "UTF-8 distance", + "tasks": [ + "BigString.utf8.distance(from:to:)", + "String.utf8.distance(from:to:)" + ] + }, + { + "kind": "chart", + "title": "UTF-16 distance", + "tasks": [ + "BigString.utf16.distance(from:to:)", + "String.utf16.distance(from:to:)" + ] + } + ] + } + ] +} diff --git a/Benchmarks/Sources/Benchmarks/BigStringBenchmarks.swift b/Benchmarks/Sources/Benchmarks/BigStringBenchmarks.swift index e1c96ae6..657d945e 100644 --- a/Benchmarks/Sources/Benchmarks/BigStringBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/BigStringBenchmarks.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2025 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 @@ -74,6 +74,17 @@ struct BridgedStringInput { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +struct BigStringInput { + let flat: String + let big: BigString + + init(runeCount: Int, using rng: inout some RandomNumberGenerator) { + self.flat = String.randomLatin(runeCount: runeCount, using: &rng) + self.big = BigString(self.flat) + } +} + extension Benchmark { public mutating func addBigStringBenchmarks() { @@ -91,6 +102,13 @@ extension Benchmark { return BridgedStringInput(runeCount: c, using: &rng) } + self.registerInputGenerator(for: BigStringInput.self) { c in + var rng = SystemRandomNumberGenerator() + return BigStringInput(runeCount: c, using: &rng) + } + + // MARK: BigString initialization + self.addSimple( title: "BigString init from native string", input: NativeStringInput.self @@ -104,5 +122,337 @@ extension Benchmark { ) { input in blackHole(BigString(input.value)) } + + // MARK: BigString iteration + + self.addSimple( + title: "BigString character iteration", + input: BigStringInput.self, + maxSize: nil + ) { input in + for char in input.big { + blackHole(char) + } + } + + self.addSimple( + title: "BigString scalar iteration", + input: BigStringInput.self, + maxSize: nil + ) { input in + for scalar in input.big.unicodeScalars { + blackHole(scalar) + } + } + + self.addSimple( + title: "BigString UTF-8 iteration", + input: BigStringInput.self, + maxSize: nil + ) { input in + for u8 in input.big.utf8 { + blackHole(u8) + } + } + + self.addSimple( + title: "BigString UTF-16 iteration", + input: BigStringInput.self, + maxSize: nil + ) { input in + for u16 in input.big.utf16 { + blackHole(u16) + } + } + + // MARK: String iteration + + self.addSimple( + title: "String character iteration", + input: BigStringInput.self, + maxSize: nil + ) { input in + for char in input.flat { + blackHole(char) + } + } + + self.addSimple( + title: "String scalar iteration", + input: BigStringInput.self, + maxSize: nil + ) { input in + for scalar in input.flat.unicodeScalars { + blackHole(scalar) + } + } + + self.addSimple( + title: "String UTF-8 iteration", + input: BigStringInput.self, + maxSize: nil + ) { input in + for u8 in input.flat.utf8 { + blackHole(u8) + } + } + + self.addSimple( + title: "String UTF-16 iteration", + input: BigStringInput.self, + maxSize: nil + ) { input in + for u16 in input.flat.utf16 { + blackHole(u16) + } + } + + // MARK: BigString index(offsetBy:) + + self.addSimple( + title: "BigString.index(offsetBy:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.big + let start = str.startIndex + for i in 0 ... str.count { + let index = str.index(start, offsetBy: i) + blackHole(index) + } + } + + self.addSimple( + title: "BigString.unicodeScalars.index(offsetBy:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.big + let start = str.startIndex + for i in 0 ... str.unicodeScalars.count { + let index = str.unicodeScalars.index(start, offsetBy: i) + blackHole(index) + } + } + + self.addSimple( + title: "BigString.utf8.index(offsetBy:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.big + let start = str.startIndex + for i in 0 ... str.utf8.count { + let index = str.utf8.index(start, offsetBy: i) + blackHole(index) + } + } + + self.addSimple( + title: "BigString.utf16.index(offsetBy:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.big + let start = str.startIndex + for i in 0 ... str.utf16.count { + let index = str.utf16.index(start, offsetBy: i) + blackHole(index) + } + } + + // MARK: String index(offsetBy:) + + self.addSimple( + title: "String.index(offsetBy:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.flat + let start = str.startIndex + for i in 0 ... str.count { + let index = str.index(start, offsetBy: i) + blackHole(index) + } + } + + self.addSimple( + title: "String.unicodeScalars.index(offsetBy:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.flat + let start = str.startIndex + for i in 0 ... str.unicodeScalars.count { + let index = str.unicodeScalars.index(start, offsetBy: i) + blackHole(index) + } + } + + self.addSimple( + title: "String.utf8.index(offsetBy:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.flat + let start = str.startIndex + for i in 0 ... str.utf8.count { + let index = str.utf8.index(start, offsetBy: i) + blackHole(index) + } + } + + self.addSimple( + title: "String.utf16.index(offsetBy:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.flat + let start = str.startIndex + for i in 0 ... str.utf16.count { + let index = str.utf16.index(start, offsetBy: i) + blackHole(index) + } + } + + // MARK: BigString distance(from:to:) + + self.add( + title: "BigString.distance(from:to:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.big + let indices = Array(str.indices) + [str.endIndex] + return { timer in + for i in 0 ..< indices.count { + let j = (i + indices.count) / 2 + let expected = j - i + let actual = str.distance(from: indices[i], to: indices[j]) + precondition(actual == expected) + } + } + } + + self.add( + title: "BigString.unicodeScalars.distance(from:to:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.big + let indices = Array(str.unicodeScalars.indices) + [str.endIndex] + return { timer in + for i in 0 ..< indices.count { + let j = (i + indices.count) / 2 + let expected = j - i + let actual = str.unicodeScalars.distance(from: indices[i], to: indices[j]) + precondition(actual == expected) + } + } + } + + self.add( + title: "BigString.utf8.distance(from:to:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.big + let indices = Array(str.utf8.indices) + [str.endIndex] + return { timer in + for i in 0 ..< indices.count { + let j = (i + indices.count) / 2 + let expected = j - i + let actual = str.utf8.distance(from: indices[i], to: indices[j]) + precondition(actual == expected) + } + } + } + + self.add( + title: "BigString.utf16.distance(from:to:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.big + let indices = Array(str.utf16.indices) + [str.endIndex] + return { timer in + for i in 0 ..< indices.count { + let j = (i + indices.count) / 2 + let expected = j - i + let actual = str.utf16.distance(from: indices[i], to: indices[j]) + precondition(actual == expected) + } + } + } + + // MARK: String distance(from:to:) + + self.add( + title: "String.distance(from:to:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.flat + let indices = Array(str.indices) + [str.endIndex] + return { timer in + for i in 0 ..< indices.count { + let j = (i + indices.count) / 2 + let expected = j - i + let actual = str.distance(from: indices[i], to: indices[j]) + precondition(actual == expected) + } + } + } + + self.add( + title: "String.unicodeScalars.distance(from:to:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.flat + let indices = Array(str.unicodeScalars.indices) + [str.endIndex] + return { timer in + for i in 0 ..< indices.count { + let j = (i + indices.count) / 2 + let expected = j - i + let actual = str.unicodeScalars.distance(from: indices[i], to: indices[j]) + precondition(actual == expected) + } + } + } + + self.add( + title: "String.utf8.distance(from:to:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.flat + let indices = Array(str.utf8.indices) + [str.endIndex] + return { timer in + for i in 0 ..< indices.count { + let j = (i + indices.count) / 2 + let expected = j - i + let actual = str.utf8.distance(from: indices[i], to: indices[j]) + precondition(actual == expected) + } + } + } + + self.add( + title: "String.utf16.distance(from:to:)", + input: BigStringInput.self, + maxSize: nil + ) { input in + let str = input.flat + let indices = Array(str.utf16.indices) + [str.endIndex] + return { timer in + for i in 0 ..< indices.count { + let j = (i + indices.count) / 2 + let expected = j - i + let actual = str.utf16.distance(from: indices[i], to: indices[j]) + precondition(actual == expected) + } + } + } } } From fc411858ee8c2d1ca4113555c185752f5d8212f5 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 17 Jun 2025 20:09:58 -0700 Subject: [PATCH 4/4] [BigString] Speed up index distance calculations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This implements a roughly 40-45% improvement for distance measurements over `BigString`’s character and Unicode Scalar views. Interestingly, we don’t see an improvement for UTF-16 views — I’m guessing this is due to String’s breadcrumbing. (And it will go away with the upcoming UTF8Span-ification of this type.) The benchmarks I added only show an improvement for multi-chunk big string instances, but this is merely an artifact of the specific algorithm that is being measured — for single-chunk strings, the existing measurement method is already optimal, so the new heuristic never triggers for this particular payload. --- .../BigString/Basics/BigString+Metrics.swift | 35 ++++++++++++++++--- ...gString+Chunk+Indexing by Characters.swift | 13 ++++++- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift index 4aeb696d..42775e9c 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift @@ -110,11 +110,24 @@ extension BigString { in chunk: BigString._Chunk ) -> Int { assert(start <= end) - return chunk.string.unicodeScalars[start ..< end].count + + // Make use of the chunk's known scalar count to reduce the amount of data we need to look at. + if end._utf8Offset - start._utf8Offset < chunk.utf8Count / 2 { + return chunk.string.unicodeScalars[start ..< end].count + } + var result: Int + result = chunk.unicodeScalarCount + result -= chunk.string.unicodeScalars[.. Int { - return chunk.string.unicodeScalars[.. (found: Bool, forward: Bool) { + // FIXME: Make use of the chunk's known scalar count to reduce work guard distance != 0 else { i = chunk.string.unicodeScalars._index(roundingDown: i) return (true, false) @@ -214,11 +228,23 @@ extension BigString { in chunk: BigString._Chunk ) -> Int { assert(start <= end) - return chunk.string.utf16[start ..< end].count + + // Make use of the chunk's known UTF-16 count to reduce the amount of data we need to look at. + if end._utf8Offset - start._utf8Offset < chunk.utf8Count / 2 { + return chunk.string.utf16[start ..< end].count + } + var result = chunk.utf16Count + result -= chunk.string.utf16[.. Int { - return chunk.string.utf16[.. (found: Bool, forward: Bool) { + // FIXME: Make use of the chunk's known UTF-16 count to reduce work if distance >= 0 { if distance <= chunk.utf16Count, diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift index 4eae68fc..4371a259 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift @@ -41,7 +41,17 @@ extension BigString._Chunk { let wholeCharacters = self.wholeCharacters let s = Swift.max(start, firstBreak) let e = Swift.min(end, lastBreak) - var result = wholeCharacters.distance(from: s, to: e) + var result: Int + // Run the actual grapheme breaking algorithm, making sure we measure + // as little data as possible, by making best use of the known character + // count for the whole chunk. + if e._utf8Offset - s._utf8Offset <= (lastBreak._utf8Offset - firstBreak._utf8Offset) / 2 { + result = wholeCharacters.distance(from: s, to: e) + } else { + result = characterCount - 1 // The last break is handled below + result -= wholeCharacters.distance(from: firstBreak, to: s) + result -= wholeCharacters.distance(from: e, to: lastBreak) + } if end > lastBreak { /// We know `end` is rounded, so it can only ever be after the last break @@ -75,6 +85,7 @@ extension BigString._Chunk { func formCharacterIndex( _ i: inout String.Index, offsetBy distance: inout Int ) -> (found: Bool, forward: Bool) { + // FIXME: Make use of the chunk's known character count to reduce work if distance == 0 { if i < firstBreak { i = string.startIndex