From 283d4071bcf1705850b43ab001265673682abe8f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 9 Feb 2023 14:33:36 -0800 Subject: [PATCH] Assorted bug fixes and refinements --- .../BString/Basics/_BString+Contents.swift | 17 ++++-- .../BString/Basics/_BString+Iterators.swift | 58 +++++++++++++++++-- .../Conformances/_BString+Comparisons.swift | 32 ++++++++++ .../Operations/Range+_BString.swift} | 6 -- .../Operations/_BString+Initializers.swift | 16 ++++- Sources/RopeModule/BigString/BigString.swift | 6 ++ .../Utilities/String.Index+ABI.swift | 46 +++++++-------- 7 files changed, 141 insertions(+), 40 deletions(-) rename Sources/RopeModule/{Utilities/Range Utilities.swift => BString/Operations/Range+_BString.swift} (76%) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 4c8523f2..206e68f6 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -36,10 +36,9 @@ extension _BString { to end: Index, in metric: some _StringMetric ) -> Int { - guard !isEmpty else { - precondition(start == end && start == endIndex, "Invalid index") - return 0 - } + 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 { @@ -320,12 +319,22 @@ extension _BString { return chunk.string.utf8[path.chunk] } + subscript(utf8 offset: Int) -> UInt8 { + let (path, chunk) = _path(startIndex, offsetBy: offset, in: UTF8Metric()) + return chunk.string.utf8[path.chunk] + } + 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] } + subscript(utf16 offset: Int) -> UInt16 { + let (path, chunk) = _path(startIndex, offsetBy: offset, in: UTF16Metric()) + return chunk.string.utf16[path.chunk] + } + subscript(character index: Index) -> Character { precondition(index < endIndex, "Index out of bounds") let (path, chunk) = path(to: index, preferEnd: false) diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index 793e99f7..ba3fa117 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -135,11 +135,13 @@ extension _BString.UnicodeScalarIterator: IteratorProtocol { extension _BString { internal struct CharacterIterator { + internal var _utf8BaseOffset: Int internal var _base: _Rope.Iterator internal var _index: String.Index internal var _next: String.Index - internal init(_base: _Rope.Iterator) { + internal init(_base: _Rope.Iterator, utf8BaseOffset: Int) { + self._utf8BaseOffset = utf8BaseOffset self._base = _base guard !_base.isAtEnd else { _index = "".startIndex @@ -152,7 +154,8 @@ extension _BString { self._next = chunk.string[_index...].index(after: _index) } - internal init(_base: _Rope.Iterator, _ i: String.Index) { + internal init(_base: _Rope.Iterator, utf8BaseOffset: Int, _ i: String.Index) { + self._utf8BaseOffset = utf8BaseOffset self._base = _base self._index = i assert(i >= _base.current.firstBreak) @@ -165,16 +168,21 @@ extension _BString { } internal func makeCharacterIterator() -> CharacterIterator { - CharacterIterator(_base: rope.makeIterator()) + CharacterIterator(_base: rope.makeIterator(), utf8BaseOffset: 0) } internal func makeCharacterIterator(from index: Index) -> CharacterIterator { if index == endIndex { - return CharacterIterator(_base: rope.makeIterator(from: rope.endIndex)) + return CharacterIterator( + _base: rope.makeIterator(from: rope.endIndex), + utf8BaseOffset: index._utf8Offset) } let (path, _) = self.path(to: index, preferEnd: false) let base = rope.makeIterator(from: path.rope) - return CharacterIterator(_base: base, path.chunk) + return CharacterIterator( + _base: base, + utf8BaseOffset: index._utf8Offset - path.chunk._utf8Offset, + path.chunk) } } @@ -215,7 +223,10 @@ extension _BString.CharacterIterator: IteratorProtocol { _next = chunk.wholeCharacters.index(after: _next) return true } - while _base.stepForward() { + while true { + let c = _base.current.utf8Count + guard _base.stepForward() else { break } + _utf8BaseOffset += c let chunk = _base.current let i = chunk.firstBreak if i < chunk.string.endIndex { @@ -239,6 +250,7 @@ extension _BString.CharacterIterator: IteratorProtocol { } while _base.stepBackward() { let chunk = _base.current + _utf8BaseOffset -= chunk.utf8Count if chunk.hasBreaks { _next = chunk.string.endIndex _index = chunk.lastBreak @@ -259,8 +271,42 @@ extension _BString.CharacterIterator: IteratorProtocol { } extension _BString.CharacterIterator { + // The UTF-8 offset of the current position, from the start of the string. + var utf8Offset: Int { + _utf8BaseOffset + _index._utf8Offset + } + + /// The UTF-8 offset range of the current character, measured from the start of the string. + var utf8Range: Range { + assert(!isAtEnd) + let start = utf8Offset + var end = _utf8BaseOffset + if _next < _base.current.string.endIndex { + end += _next._utf8Offset + return Range(uncheckedBounds: (start, end)) + } + var it = _base + while true { + end += it.current.utf8Count + guard it.stepForward() else { break } + let chunk = it.current + let i = chunk.firstBreak + if i < chunk.string.endIndex { + end += i._utf8Offset + break + } + } + return Range(uncheckedBounds: (start, end)) + } + var index: _BString.Index { let utf8Base = _base.rope.offset(of: _base.index, in: _BString.UTF8Metric()) return _BString.Index(_utf8Offset: utf8Base + _index._utf8Offset) } + + func isBelow(_ path: _BString.Path) -> Bool { + if self._base.index < path.rope { return true } + guard self._base.index == path.rope else { return false } + return self._index < path.chunk + } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift index 8b423e7d..e65b2bf9 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift @@ -37,6 +37,38 @@ extension _BString { return true } + internal static func characterIsEqual( + _ left: Self, + in leftRange: Range, + to right: Self, + in rightRange: Range + ) -> Bool { + // FIXME: Implement properly normalized comparisons & hashing. + // This is somewhat tricky as we shouldn't just normalize individual pieces of the string + // 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 left.isIdentical(to: right), leftRange == rightRange { return true } + + // 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) + + let leftEnd = left.path(to: leftRange.upperBound, preferEnd: true).path + let rightEnd = right.path(to: rightRange.upperBound, preferEnd: true).path + + var a: Character? = nil + var b: Character? = nil + while it1.isBelow(leftEnd), it2.isBelow(rightEnd) { + a = it1.next() + b = it2.next() + assert(a != nil && b != nil) + guard a == b else { return false } + } + return !it1.isBelow(leftEnd) && !it2.isBelow(rightEnd) + } + + internal func characterIsLess(than other: Self) -> Bool { // FIXME: Implement properly normalized comparisons & hashing. // This is somewhat tricky as we shouldn't just normalize individual pieces of the string diff --git a/Sources/RopeModule/Utilities/Range Utilities.swift b/Sources/RopeModule/BString/Operations/Range+_BString.swift similarity index 76% rename from Sources/RopeModule/Utilities/Range Utilities.swift rename to Sources/RopeModule/BString/Operations/Range+_BString.swift index 0088e25d..6c9d1f0b 100644 --- a/Sources/RopeModule/Utilities/Range Utilities.swift +++ b/Sources/RopeModule/BString/Operations/Range+_BString.swift @@ -9,12 +9,6 @@ // //===----------------------------------------------------------------------===// -extension Range { - internal var _base: Range<_BString.Index> { - Range<_BString.Index>(uncheckedBounds: (lowerBound._value, upperBound._value)) - } -} - extension Range<_BString.Index> { internal var _isEmptyUTF8: Bool { lowerBound._utf8Offset == upperBound._utf8Offset diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index 0f3d14a0..5b2c86af 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -77,6 +77,14 @@ extension _BString { extension String { internal init(_from big: _BString) { + guard !big.isEmpty else { + self.init() + return + } + if big.rope.isSingleton { + self = big.rope[big.rope.startIndex].string + return + } self.init() self.reserveCapacity(big.utf8Count) for chunk in big.rope { @@ -86,11 +94,17 @@ extension String { internal init(_from big: _BString, in range: Range<_BString.Index>) { self.init() - guard !range._isEmptyUTF8 else { + 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) diff --git a/Sources/RopeModule/BigString/BigString.swift b/Sources/RopeModule/BigString/BigString.swift index dcc37cd8..0d44c07b 100644 --- a/Sources/RopeModule/BigString/BigString.swift +++ b/Sources/RopeModule/BigString/BigString.swift @@ -64,3 +64,9 @@ extension String.UnicodeScalarView { self = String().unicodeScalars } } + +extension Range { + internal var _base: Range<_BString.Index> { + Range<_BString.Index>(uncheckedBounds: (lowerBound._value, upperBound._value)) + } +} diff --git a/Sources/RopeModule/Utilities/String.Index+ABI.swift b/Sources/RopeModule/Utilities/String.Index+ABI.swift index d007f542..e8505f4c 100644 --- a/Sources/RopeModule/Utilities/String.Index+ABI.swift +++ b/Sources/RopeModule/Utilities/String.Index+ABI.swift @@ -12,54 +12,54 @@ // Bits of String.Index that are ABI but aren't exposed by public API. extension String.Index { @inline(__always) - var _rawBits: UInt64 { + var _abi_rawBits: UInt64 { unsafeBitCast(self, to: UInt64.self) } @inline(__always) - var _encodedOffset: Int { - Int(truncatingIfNeeded: _rawBits &>> 16) + var _abi_encodedOffset: Int { + Int(truncatingIfNeeded: _abi_rawBits &>> 16) } @inline(__always) - var _transcodedOffset: Int { - Int(truncatingIfNeeded: (_rawBits &>> 14) & 0x3) + var _abi_transcodedOffset: Int { + Int(truncatingIfNeeded: (_abi_rawBits &>> 14) & 0x3) } @inline(__always) - static var __scalarAlignmentBit: UInt64 { 0x1 } - + static var _abi_scalarAlignmentBit: UInt64 { 0x1 } + @inline(__always) - static var __characterAlignmentBit: UInt64 { 0x2 } - + static var _abi_characterAlignmentBit: UInt64 { 0x2 } + @inline(__always) - static var __utf8Bit: UInt64 { 0x4 } - + static var _abi_utf8Bit: UInt64 { 0x4 } + @inline(__always) - static var __utf16Bit: UInt64 { 0x8 } - + static var _abi_utf16Bit: UInt64 { 0x8 } + @inline(__always) var _encodingBits: UInt64 { - _rawBits & (Self.__utf8Bit | Self.__utf16Bit) + _abi_rawBits & (Self._abi_utf8Bit | Self._abi_utf16Bit) } @inline(__always) var _canBeUTF8: Bool { // The only way an index cannot be UTF-8 is it has only the UTF-16 flag set. - _encodingBits != Self.__utf16Bit + _encodingBits != Self._abi_utf16Bit } var _isScalarAligned: Bool { - 0 != _rawBits & Self.__scalarAlignmentBit + 0 != _abi_rawBits & Self._abi_scalarAlignmentBit } var _isCharacterAligned: Bool { - 0 != _rawBits & Self.__characterAlignmentBit + 0 != _abi_rawBits & Self._abi_characterAlignmentBit } var _characterAligned: String.Index { - let r = _rawBits | Self.__characterAlignmentBit | Self.__scalarAlignmentBit + let r = _abi_rawBits | Self._abi_characterAlignmentBit | Self._abi_scalarAlignmentBit return unsafeBitCast(r, to: String.Index.self) } } @@ -68,13 +68,13 @@ extension String.Index { @inline(__always) var _utf8Offset: Int { assert(_canBeUTF8) - return _encodedOffset + return _abi_encodedOffset } @inline(__always) var _utf16Delta: Int { assert(_canBeUTF8) - let r = _transcodedOffset + let r = _abi_transcodedOffset assert(r <= 1) return r } @@ -86,20 +86,20 @@ extension String.Index { @inline(__always) init(_utf8Offset: Int) { - self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | Self.__utf8Bit) + self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | Self._abi_utf8Bit) } init(_utf8Offset: Int, utf16Delta: Int) { assert(utf16Delta >= 0 && utf16Delta <= 1) let transcodedOffset: UInt64 = (utf16Delta != 0 ? 1 &<< 14 : 0) - self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | transcodedOffset | Self.__utf8Bit) + self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | transcodedOffset | Self._abi_utf8Bit) } } extension String.Index { @inline(__always) var _chunkData: UInt16 { - UInt16(_rawBits &>> 14) + UInt16(_abi_rawBits &>> 14) } @inline(__always)