diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 2bdb2701..6380f1b6 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -33,21 +33,6 @@ extension _BString { } } -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - var isEmpty: Bool { - rope.summary.isZero - } - - var startIndex: Index { - Index(_utf8Offset: 0)._knownCharacterAligned() - } - - var endIndex: Index { - Index(_utf8Offset: utf8Count)._knownCharacterAligned() - } -} - @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { var characterCount: Int { rope.summary.characters } @@ -536,7 +521,7 @@ extension _BString { rope.formIndex(after: &ri) while ri < endRopeIndex { - var string = rope[ri].string + let string = rope[ri].string body(string[...]) } diff --git a/Sources/RopeModule/BString/Basics/_BString.swift b/Sources/RopeModule/BString/Basics/_BString.swift index f6220e5b..8d5cf239 100644 --- a/Sources/RopeModule/BString/Basics/_BString.swift +++ b/Sources/RopeModule/BString/Basics/_BString.swift @@ -18,10 +18,6 @@ internal struct _BString: Sendable { var rope: Rope - internal init() { - rope = Rope() - } - internal init(rope: Rope) { self.rope = rope } diff --git a/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift b/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift new file mode 100644 index 00000000..77871d55 --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift @@ -0,0 +1,64 @@ +//===----------------------------------------------------------------------===// +// +// 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: BidirectionalCollection { + typealias SubSequence = _BSubstring + + var isEmpty: Bool { + rope.summary.isZero + } + + var startIndex: Index { + Index(_utf8Offset: 0)._knownCharacterAligned() + } + + var endIndex: Index { + Index(_utf8Offset: utf8Count)._knownCharacterAligned() + } + + internal var count: Int { characterCount } + + @inline(__always) + internal func index(after i: Index) -> Index { + characterIndex(after: i) + } + + @inline(__always) + internal func index(before i: Index) -> Index { + characterIndex(before: i) + } + + @inline(__always) + internal func index(_ i: Index, offsetBy distance: Int) -> Index { + characterIndex(i, offsetBy: distance) + } + + internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + characterIndex(i, offsetBy: distance, limitedBy: limit) + } + + internal func distance(from start: Index, to end: Index) -> Int { + characterDistance(from: start, to: end) + } + + internal subscript(position: Index) -> Character { + self[character: position] + } + + internal subscript(bounds: Range) -> _BSubstring { + _BSubstring(self, in: bounds) + } +} + +#endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift new file mode 100644 index 00000000..cb2a67a5 --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift @@ -0,0 +1,95 @@ +//===----------------------------------------------------------------------===// +// +// 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: Comparable { + internal static func < (left: Self, right: Self) -> Bool { + left.characterwiseIsLess(than: right) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + internal func characterwiseIsLess(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 + // 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 false } + // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. + var it1 = self.makeCharacterIterator() + var it2 = other.makeCharacterIterator() + while true { + switch (it1.next(), it2.next()) { + case (nil, nil): return false + case (nil, .some): return true + case (.some, nil): return false + case let (a?, b?): + if a == b { continue } + return a < b + } + } + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + /// 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 { + if self.isIdentical(to: other) { 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()?[...] ?? "" + } + if s1.isEmpty { + return !s2.isEmpty + } + if s2.isEmpty { + return false + } + let c = Swift.min(s1.utf8.count, s2.utf8.count) + assert(c > 0) + let r: Bool? = s1.withUTF8 { b1 in + s2.withUTF8 { b2 in + for i in 0 ..< c { + let u1 = b1[i] + let u2 = b2[i] + if u1 < u2 { return true } + if u1 > u2 { return false } + } + return nil + } + } + if let r = r { return r } + s1 = s1.suffix(from: s1._utf8Index(at: c)) + s2 = s2.suffix(from: s2._utf8Index(at: c)) + } + } +} + +#endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift b/Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift new file mode 100644 index 00000000..2ba2e91a --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift @@ -0,0 +1,21 @@ +//===----------------------------------------------------------------------===// +// +// 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: CustomStringConvertible { + internal var description: String { + String(_from: self) + } +} + +#endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift b/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift similarity index 67% rename from Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift rename to Sources/RopeModule/BString/Conformances/_BString+Equatable.swift index f22ad5ac..2d5c231c 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift @@ -18,9 +18,16 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString: Equatable { + internal static func ==(left: Self, right: Self) -> Bool { + left.characterwiseIsEqual(to: right) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal func characterIsEqual(to other: Self) -> Bool { + internal func characterwiseIsEqual(to other: Self) -> 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 @@ -41,7 +48,7 @@ extension _BString { return true } - internal static func characterIsEqual( + internal static func characterwiseIsEqual( _ left: Self, in leftRange: Range, to right: Self, @@ -73,29 +80,6 @@ extension _BString { } 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 - // 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 false } - // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. - var it1 = self.makeCharacterIterator() - var it2 = other.makeCharacterIterator() - while true { - switch (it1.next(), it2.next()) { - case (nil, nil): return false - case (nil, .some): return true - case (.some, nil): return false - case let (a?, b?): - if a == b { continue } - return a < b - } - } - } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) @@ -157,52 +141,6 @@ extension _BString { 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 { - if self.isIdentical(to: other) { 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()?[...] ?? "" - } - if s1.isEmpty { - return !s2.isEmpty - } - if s2.isEmpty { - return false - } - let c = Swift.min(s1.utf8.count, s2.utf8.count) - assert(c > 0) - let r: Bool? = s1.withUTF8 { b1 in - s2.withUTF8 { b2 in - for i in 0 ..< c { - let u1 = b1[i] - let u2 = b2[i] - if u1 < u2 { return true } - if u1 > u2 { return false } - } - return nil - } - } - if let r = r { return r } - s1 = s1.suffix(from: s1._utf8Index(at: c)) - s2 = s2.suffix(from: s2._utf8Index(at: c)) - } - } } #endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+Conformances.swift b/Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift similarity index 78% rename from Sources/RopeModule/BString/Conformances/_BString+Conformances.swift rename to Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift index aa069437..9c86e397 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Conformances.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift @@ -18,11 +18,4 @@ extension _BString: ExpressibleByStringLiteral { } } -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: CustomStringConvertible { - internal var description: String { - String(_from: self) - } -} - #endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift index 8ea6da27..99f682fa 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift @@ -11,6 +11,13 @@ #if swift(>=5.8) +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString: Hashable { + internal func hash(into hasher: inout Hasher) { + hashCharacters(into: &hasher) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal func hashCharacters(into hasher: inout Hasher) { diff --git a/Sources/RopeModule/BString/Conformances/_BString+LosslessStringConvertible.swift b/Sources/RopeModule/BString/Conformances/_BString+LosslessStringConvertible.swift new file mode 100644 index 00000000..b7b77efd --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+LosslessStringConvertible.swift @@ -0,0 +1,19 @@ +//===----------------------------------------------------------------------===// +// +// 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: LosslessStringConvertible { + // init?(_: String) is implemented by RangeReplaceableCollection.init(_:) +} + +#endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift b/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift new file mode 100644 index 00000000..7bf4da19 --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift @@ -0,0 +1,223 @@ +//===----------------------------------------------------------------------===// +// +// 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: RangeReplaceableCollection { + internal init() { + self.init(rope: Rope()) + } + + internal mutating func reserveCapacity(_ n: Int) { + // Do nothing. + } + + internal mutating func replaceSubrange>( + _ subrange: Range, with newElements: __owned C + ) { + if C.self == String.self { + let newElements = _identityCast(newElements, to: String.self) + self._replaceSubrange(subrange, with: newElements) + } else if C.self == Substring.self { + let newElements = _identityCast(newElements, to: Substring.self) + self._replaceSubrange(subrange, with: newElements) + } else if C.self == _BString.self { + let newElements = _identityCast(newElements, to: _BString.self) + self._replaceSubrange(subrange, with: newElements) + } else if C.self == _BSubstring.self { + let newElements = _identityCast(newElements, to: _BSubstring.self) + self._replaceSubrange(subrange, with: newElements) + } else { + self._replaceSubrange(subrange, with: _BString(newElements)) + } + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned String + ) { + _replaceSubrange(subrange, with: newElements) + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned Substring + ) { + _replaceSubrange(subrange, with: newElements) + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned _BString + ) { + _replaceSubrange(subrange, with: newElements) + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned _BSubstring + ) { + _replaceSubrange(subrange, with: newElements) + } + + internal init>(_ elements: S) { + if S.self == String.self { + let elements = _identityCast(elements, to: String.self) + self.init(_from: elements) + } else if S.self == Substring.self { + let elements = _identityCast(elements, to: Substring.self) + self.init(_from: elements) + } else if S.self == _BString.self { + self = _identityCast(elements, to: _BString.self) + } else if S.self == _BSubstring.self { + let elements = _identityCast(elements, to: _BSubstring.self) + self.init(_from: elements) + } else { + self.init(_from: elements) + } + } + + internal init(_ elements: String) { + self.init(_from: elements) + } + + internal init(_ elements: Substring) { + self.init(_from: elements) + } + + internal init(_ elements: _BString) { + self = elements + } + + internal init(_ elements: _BSubstring) { + self.init(_from: elements) + } + + internal init(repeating repeatedValue: Character, count: Int) { + self.init(repeating: _BString(String(repeatedValue)), count: count) + } + + internal init(repeating repeatedValue: some StringProtocol, count: Int) { + self.init(repeating: _BString(repeatedValue), count: count) + } + + internal init(repeating value: Self, count: Int) { + precondition(count >= 0, "Negative count") + guard count > 0 else { + self.init() + return + } + self.init() + var c = 0 + + var piece = value + var current = 1 + + while c < count { + if count & current != 0 { + self.append(contentsOf: piece) + c |= current + } + piece.append(contentsOf: piece) + current *= 2 + } + } + + internal mutating func append(_ newElement: __owned Character) { + append(contentsOf: String(newElement)) + } + + internal mutating func append>(contentsOf newElements: __owned S) { + if S.self == String.self { + let newElements = _identityCast(newElements, to: String.self) + append(contentsOf: newElements) + } else if S.self == Substring.self { + let newElements = _identityCast(newElements, to: Substring.self) + append(contentsOf: newElements) + } else if S.self == _BString.self { + let newElements = _identityCast(newElements, to: _BString.self) + append(contentsOf: newElements) + } else if S.self == _BSubstring.self { + let newElements = _identityCast(newElements, to: _BSubstring.self) + append(contentsOf: newElements) + } else { + append(contentsOf: _BString(newElements)) + } + } + + internal mutating func append(contentsOf newElements: __owned String) { + _append(contentsOf: newElements[...]) + } + + internal mutating func append(contentsOf newElements: __owned Substring) { + _append(contentsOf: newElements) + } + + internal mutating func append(contentsOf newElements: __owned _BString) { + _append(contentsOf: newElements) + } + + internal mutating func append(contentsOf newElements: __owned _BSubstring) { + _append(contentsOf: newElements._base, in: newElements._bounds) + } + + internal mutating func insert(_ newElement: Character, at i: Index) { + insert(contentsOf: String(newElement), at: i) + } + + internal mutating func insert>( + contentsOf newElements: __owned C, at i: Index + ) { + if C.self == String.self { + let newElements = _identityCast(newElements, to: String.self) + insert(contentsOf: newElements, at: i) + } else if C.self == Substring.self { + let newElements = _identityCast(newElements, to: Substring.self) + insert(contentsOf: newElements, at: i) + } else if C.self == _BString.self { + let newElements = _identityCast(newElements, to: _BString.self) + insert(contentsOf: newElements, at: i) + } else if C.self == _BSubstring.self { + let newElements = _identityCast(newElements, to: _BSubstring.self) + insert(contentsOf: newElements, at: i) + } else { + insert(contentsOf: _BString(newElements), at: i) + } + } + + internal mutating func insert(contentsOf newElements: __owned String, at i: Index) { + _insert(contentsOf: newElements[...], at: i) + } + + internal mutating func insert(contentsOf newElements: __owned Substring, at i: Index) { + _insert(contentsOf: newElements, at: i) + } + + internal mutating func insert(contentsOf newElements: __owned _BString, at i: Index) { + _insert(contentsOf: newElements, at: i) + } + + internal mutating func insert(contentsOf newElements: __owned _BSubstring, at i: Index) { + _insert(contentsOf: newElements._base, in: newElements._bounds, at: i) + } + + @discardableResult + internal mutating func remove(at i: Index) -> Character { + removeCharacter(at: i) + } + + internal mutating func removeSubrange(_ bounds: Range) { + _removeSubrange(bounds) + } + + internal mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + self = _BString() + } +} + +#endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+Sequence.swift b/Sources/RopeModule/BString/Conformances/_BString+Sequence.swift new file mode 100644 index 00000000..959b09be --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+Sequence.swift @@ -0,0 +1,25 @@ +//===----------------------------------------------------------------------===// +// +// 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: Sequence { + typealias Element = Character + + typealias Iterator = CharacterIterator + + internal func makeIterator() -> Iterator { + makeCharacterIterator() + } +} + +#endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+TextOutputStream.swift b/Sources/RopeModule/BString/Conformances/_BString+TextOutputStream.swift new file mode 100644 index 00000000..4e25e4f4 --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+TextOutputStream.swift @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// +// 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: TextOutputStream { + public mutating func write(_ string: String) { + append(contentsOf: string) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString: TextOutputStreamable { + public func write(to target: inout some TextOutputStream) { + for chunk in rope { + chunk.string.write(to: &target) + } + } +} + +#endif diff --git a/Sources/RopeModule/BString/Operations/_BString+Append.swift b/Sources/RopeModule/BString/Operations/_BString+Append.swift index d0ebc487..cee94405 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Append.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Append.swift @@ -13,15 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - mutating func append(contentsOf other: __owned some StringProtocol) { - append(contentsOf: Substring(other)) - } - - mutating func append(contentsOf other: __owned String) { - append(contentsOf: other[...]) - } - - mutating func append(contentsOf other: __owned Substring) { + mutating func _append(contentsOf other: __owned Substring) { if other.isEmpty { return } if isEmpty { self = Self(other) @@ -56,7 +48,7 @@ extension _BString { return rope.root.firstItem.value.string.unicodeScalars.first! } - mutating func append(contentsOf other: __owned _BString) { + mutating func _append(contentsOf other: __owned _BString) { guard !other.isEmpty else { return } guard !self.isEmpty else { self = other @@ -71,14 +63,14 @@ extension _BString { _append(other) } - mutating func append(contentsOf other: __owned _BString, in range: Range) { + mutating func _append(contentsOf other: __owned _BString, in range: Range) { guard !range._isEmptyUTF8 else { return } guard !self.isEmpty else { - self = Self(other, in: range) + self = Self(_from: other, in: range) return } - var other = _BString(other, in: range) + var other = _BString(_from: other, in: range) let hint = other._firstUnicodeScalar var old = _CharacterRecognizer() var new = self._breakState(upTo: endIndex, nextScalarHint: hint) @@ -101,7 +93,7 @@ extension _BString { mutating func prepend(contentsOf other: __owned _BString, in range: Range) { guard !range._isEmptyUTF8 else { return } - let extract = Self(other, in: range) + let extract = Self(_from: other, in: range) guard !self.isEmpty else { self = extract return diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index da2fefb0..b0c9a82c 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal init(_ input: some StringProtocol) { + internal init(_from input: some StringProtocol) { var builder = Rope.Builder() var ingester = Ingester(input) while let chunk = ingester.nextWellSizedChunk() { @@ -22,7 +22,7 @@ extension _BString { self.rope = builder.finalize() } - internal init(_ input: some Sequence) { + internal init(_from input: some Sequence) { var builder = Builder() var piece = "" for character in input { @@ -36,7 +36,7 @@ extension _BString { self = builder.finalize() } - internal init(_ input: some Sequence) { + internal init(_from input: some Sequence) { var builder = Builder() var piece = "" for scalar in input { @@ -50,8 +50,16 @@ extension _BString { self = builder.finalize() } + internal init(_from other: _BSubstring) { + self.init(_from: other._base, in: other._bounds) + } + + internal init(_from other: _BSubstring.UnicodeScalarView) { + self.init(_from: other._base, in: other._bounds) + } + internal init( - _ other: Self, + _from other: Self, in range: Range ) { self.rope = other.rope.extract( @@ -127,29 +135,4 @@ extension String { } } -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - internal init(repeating value: Self, count: Int) { - precondition(count >= 0, "Negative count") - guard count > 0 else { - self.init() - return - } - self.init() - var c = 0 - - var piece = value - var current = 1 - - while c < count { - if count & current != 0 { - self.append(contentsOf: piece) - c |= current - } - piece.append(contentsOf: piece) - current *= 2 - } - } -} - #endif diff --git a/Sources/RopeModule/BString/Operations/_BString+Insert.swift b/Sources/RopeModule/BString/Operations/_BString+Insert.swift index d6f02108..34a565ad 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Insert.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Insert.swift @@ -13,15 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - mutating func insert(contentsOf other: __owned some StringProtocol, at index: Index) { - insert(contentsOf: Substring(other), at: index) - } - - mutating func insert(contentsOf other: __owned String, at index: Index) { - insert(contentsOf: other[...], at: index) - } - - mutating func insert( + mutating func _insert( contentsOf other: __owned Substring, at index: Index ) { @@ -64,7 +56,7 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - mutating func insert(contentsOf other: __owned Self, at index: Index) { + mutating func _insert(contentsOf other: __owned Self, at index: Index) { guard index < endIndex else { precondition(index == endIndex, "Index out of bounds") self.append(contentsOf: other) @@ -88,10 +80,10 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - mutating func insert(contentsOf other: __owned Self, in range: Range, at index: Index) { + mutating func _insert(contentsOf other: __owned Self, in range: Range, at index: Index) { guard index < endIndex else { precondition(index == endIndex, "Index out of bounds") - self.append(contentsOf: other, in: range) + self._append(contentsOf: other, in: range) return } guard index > startIndex else { diff --git a/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift index d2c57039..4ab2d32d 100644 --- a/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift +++ b/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - mutating func removeSubrange(_ bounds: Range) { + mutating func _removeSubrange(_ bounds: Range) { precondition(bounds.upperBound <= endIndex, "Index out of bounds") if bounds.isEmpty { return } let lower = bounds.lowerBound._utf8Offset diff --git a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift index 7801ed1a..f50ec982 100644 --- a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift +++ b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - mutating func replaceSubrange(_ range: Range, with newElements: some StringProtocol) { + mutating func _replaceSubrange(_ range: Range, with newElements: some StringProtocol) { precondition(range.upperBound <= endIndex, "Index out of bounds") if range.isEmpty { insert(contentsOf: newElements, at: range.lowerBound) @@ -25,7 +25,7 @@ extension _BString { self = builder.finalize() } - mutating func replaceSubrange(_ range: Range, with newElements: _BString) { + mutating func _replaceSubrange(_ range: Range, with newElements: _BString) { precondition(range.upperBound <= endIndex, "Index out of bounds") if range.isEmpty { insert(contentsOf: newElements, at: range.lowerBound) @@ -36,7 +36,14 @@ extension _BString { self = builder.finalize() } - mutating func replaceSubrange( + mutating func _replaceSubrange( + _ targetRange: Range, + with newElements: _BSubstring + ) { + _replaceSubrange(targetRange, with: newElements._base, in: newElements._bounds) + } + + mutating func _replaceSubrange( _ targetRange: Range, with newElements: _BString, in sourceRange: Range @@ -46,7 +53,7 @@ extension _BString { return } if targetRange._isEmptyUTF8 { - insert( + _insert( contentsOf: newElements, in: sourceRange, at: targetRange.lowerBound) diff --git a/Sources/RopeModule/BString/Views/_BString+CharacterView.swift b/Sources/RopeModule/BString/Views/_BString+CharacterView.swift deleted file mode 100644 index 7aef3b27..00000000 --- a/Sources/RopeModule/BString/Views/_BString+CharacterView.swift +++ /dev/null @@ -1,91 +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 { - internal struct CharacterView { - var _base: _BString - - @inline(__always) - init(_base: _BString) { - self._base = _base - } - } - - @inline(__always) - internal var characters: CharacterView { - CharacterView(_base: self) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.CharacterView: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { - left._base.characterIsEqual(to: right._base) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.CharacterView: Hashable { - internal func hash(into hasher: inout Hasher) { - _base.hashCharacters(into: &hasher) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.CharacterView: BidirectionalCollection { - typealias Index = _BString.Index - typealias Element = Character - typealias SubSequence = _BSubstring.CharacterView - - @inline(__always) - internal var startIndex: Index { _base.startIndex } - - @inline(__always) - internal var endIndex: Index { _base.endIndex } - - internal var count: Int { _base.characterCount } - - @inline(__always) - internal func index(after i: Index) -> Index { - _base.characterIndex(after: i) - } - - @inline(__always) - internal func index(before i: Index) -> Index { - _base.characterIndex(before: i) - } - - @inline(__always) - internal func index(_ i: Index, offsetBy distance: Int) -> Index { - _base.characterIndex(i, offsetBy: distance) - } - - internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _base.characterIndex(i, offsetBy: distance, limitedBy: limit) - } - - internal func distance(from start: Index, to end: Index) -> Int { - _base.characterDistance(from: start, to: end) - } - - internal subscript(position: Index) -> Character { - _base[character: position] - } - - internal subscript(bounds: Range) -> _BSubstring.CharacterView { - _BSubstring.CharacterView(_base, in: bounds) - } -} - -#endif diff --git a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift index edcc9ab6..412ca1a3 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal struct UTF16View { + internal struct UTF16View: Sendable { var _base: _BString @inline(__always) diff --git a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift index 6a6d9cc7..561f5edd 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal struct UTF8View { + internal struct UTF8View: Sendable { var _base: _BString @inline(__always) diff --git a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift index 9c3e7a95..f281bf47 100644 --- a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal struct UnicodeScalarView { + internal struct UnicodeScalarView: Sendable { var _base: _BString @inline(__always) @@ -26,6 +26,10 @@ extension _BString { internal var unicodeScalars: UnicodeScalarView { UnicodeScalarView(_base: self) } + + internal init(_ view: _BString.UnicodeScalarView) { + self = view._base + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) @@ -88,4 +92,213 @@ extension _BString.UnicodeScalarView: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UnicodeScalarView: RangeReplaceableCollection { + internal init() { + self._base = _BString() + } + + internal mutating func reserveCapacity(_ n: Int) { + // Do nothing. + } + + internal mutating func replaceSubrange>( + _ subrange: Range, with newElements: __owned C + ) { + if C.self == String.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: String.UnicodeScalarView.self) + _base._replaceSubrange(subrange, with: String(newElements)) + } else if C.self == Substring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: Substring.UnicodeScalarView.self) + _base._replaceSubrange(subrange, with: Substring(newElements)) + } else if C.self == _BString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: _BString.UnicodeScalarView.self) + _base._replaceSubrange(subrange, with: newElements._base) + } else if C.self == _BSubstring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: _BSubstring.UnicodeScalarView.self) + _base._replaceSubrange(subrange, with: newElements._base, in: newElements._bounds) + } else { + _base._replaceSubrange(subrange, with: _BString(_from: newElements)) + } + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned String.UnicodeScalarView + ) { + _base._replaceSubrange(subrange, with: String(newElements)) + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned Substring.UnicodeScalarView + ) { + _base._replaceSubrange(subrange, with: Substring(newElements)) + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned _BString.UnicodeScalarView + ) { + _base._replaceSubrange(subrange, with: newElements._base) + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned _BSubstring.UnicodeScalarView + ) { + _base._replaceSubrange(subrange, with: newElements._base, in: newElements._bounds) + } + + internal init>(_ elements: S) { + if S.self == String.UnicodeScalarView.self { + let elements = _identityCast(elements, to: String.UnicodeScalarView.self) + self.init(_base: _BString(_from: elements)) + } else if S.self == Substring.UnicodeScalarView.self { + let elements = _identityCast(elements, to: Substring.UnicodeScalarView.self) + self.init(_base: _BString(_from: elements)) + } else if S.self == _BString.UnicodeScalarView.self { + let elements = _identityCast(elements, to: _BString.UnicodeScalarView.self) + self.init(_base: elements._base) + } else if S.self == _BSubstring.UnicodeScalarView.self { + let elements = _identityCast(elements, to: _BSubstring.UnicodeScalarView.self) + self.init(_base: _BString(_from: elements._base, in: elements._bounds)) + } else { + self.init(_base: _BString(_from: elements)) + } + } + + internal init(_ elements: String.UnicodeScalarView) { + self.init(_base: _BString(_from: elements)) + } + + internal init(_ elements: Substring.UnicodeScalarView) { + self.init(_base: _BString(_from: elements)) + } + + internal init(_ elements: _BString.UnicodeScalarView) { + self.init(_base: elements._base) + } + + internal init(_ elements: _BSubstring.UnicodeScalarView) { + self.init(_base: _BString(_from: elements._base, in: elements._bounds)) + } + + internal init(repeating repeatedValue: UnicodeScalar, count: Int) { + self.init(_base: _BString(repeating: _BString(String(repeatedValue)), count: count)) + } + + internal init(repeating repeatedValue: some StringProtocol, count: Int) { + self.init(_base: _BString(repeating: _BString(_from: repeatedValue), count: count)) + } + + internal init(repeating value: _BString.UnicodeScalarView, count: Int) { + self.init(_base: _BString(repeating: value._base, count: count)) + } + + internal init(repeating value: _BSubstring.UnicodeScalarView, count: Int) { + let value = _BString(value) + self.init(_base: _BString(repeating: value, count: count)) + } + + internal mutating func append(_ newElement: __owned UnicodeScalar) { + _base.append(contentsOf: String(newElement)) + } + + internal mutating func append>(contentsOf newElements: __owned S) { + if S.self == String.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: String.UnicodeScalarView.self) + append(contentsOf: newElements) + } else if S.self == Substring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: Substring.UnicodeScalarView.self) + append(contentsOf: newElements) + } else if S.self == _BString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: _BString.UnicodeScalarView.self) + append(contentsOf: newElements) + } else if S.self == _BSubstring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: _BSubstring.UnicodeScalarView.self) + append(contentsOf: newElements) + } else { + _base.append(contentsOf: _BString(_from: newElements)) + } + } + + internal mutating func append(contentsOf newElements: __owned String.UnicodeScalarView) { + _base.append(contentsOf: String(newElements)) + } + + internal mutating func append(contentsOf newElements: __owned Substring.UnicodeScalarView) { + _base.append(contentsOf: Substring(newElements)) + } + + internal mutating func append(contentsOf newElements: __owned _BString.UnicodeScalarView) { + _base.append(contentsOf: newElements._base) + } + + internal mutating func append(contentsOf newElements: __owned _BSubstring.UnicodeScalarView) { + _base._append(contentsOf: newElements._base, in: newElements._bounds) + } + + internal mutating func insert(_ newElement: UnicodeScalar, at i: Index) { + _base.insert(contentsOf: String(newElement), at: i) + } + + internal mutating func insert>( + contentsOf newElements: __owned C, at i: Index + ) { + if C.self == String.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: String.UnicodeScalarView.self) + insert(contentsOf: newElements, at: i) + } else if C.self == Substring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: Substring.UnicodeScalarView.self) + insert(contentsOf: newElements, at: i) + } else if C.self == _BString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: _BString.UnicodeScalarView.self) + insert(contentsOf: newElements, at: i) + } else if C.self == _BSubstring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: _BSubstring.UnicodeScalarView.self) + insert(contentsOf: newElements, at: i) + } else { + _base.insert(contentsOf: _BString(_from: newElements), at: i) + } + } + + internal mutating func insert( + contentsOf newElements: __owned String.UnicodeScalarView, + at i: Index + ) { + _base.insert(contentsOf: String(newElements), at: i) + } + + internal mutating func insert( + contentsOf newElements: __owned Substring.UnicodeScalarView, + at i: Index + ) { + _base.insert(contentsOf: Substring(newElements), at: i) + } + + internal mutating func insert( + contentsOf newElements: __owned _BString.UnicodeScalarView, + at i: Index + ) { + _base.insert(contentsOf: newElements._base, at: i) + } + + internal mutating func insert( + contentsOf newElements: __owned _BSubstring.UnicodeScalarView, + at i: Index + ) { + _base._insert(contentsOf: newElements._base, in: newElements._bounds, at: i) + } + + @discardableResult + internal mutating func remove(at i: Index) -> UnicodeScalar { + _base.removeUnicodeScalar(at: i) + } + + internal mutating func removeSubrange(_ bounds: Range) { + _base._removeSubrange(bounds) + } + + internal mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + self._base = _BString() + } +} + #endif diff --git a/Sources/RopeModule/BString/Views/_BSubstring+CharacterView.swift b/Sources/RopeModule/BString/Views/_BSubstring+CharacterView.swift deleted file mode 100644 index 6d17656a..00000000 --- a/Sources/RopeModule/BString/Views/_BSubstring+CharacterView.swift +++ /dev/null @@ -1,123 +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 _BSubstring { - internal struct CharacterView { - internal var _base: _BString - internal var _bounds: Range - - internal init(_unchecked base: _BString, in bounds: Range) { - self._base = base - self._bounds = bounds - } - - internal init(_ base: _BString, in bounds: Range) { - self._base = base - let lower = base.characterIndex(roundingDown: bounds.lowerBound) - let upper = base.characterIndex(roundingDown: bounds.upperBound) - self._bounds = Range(uncheckedBounds: (lower, upper)) - } - - internal init(_substring: _BSubstring) { - self.init(_unchecked: _substring._base, in: _substring._bounds) - } - } - - internal var characters: CharacterView { - CharacterView(_substring: self) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.CharacterView { - internal var base: _BString.CharacterView { _base.characters } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.CharacterView: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { - _BString.characterIsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.CharacterView: Hashable { - internal func hash(into hasher: inout Hasher) { - _base.hashCharacters(into: &hasher, from: _bounds) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.CharacterView: BidirectionalCollection { - typealias Index = _BString.Index - typealias Element = Character - typealias SubSequence = Self - - @inline(__always) - internal var startIndex: Index { _bounds.lowerBound } - - @inline(__always) - internal var endIndex: Index { _bounds.upperBound } - - internal var count: Int { - distance(from: _bounds.lowerBound, to: _bounds.upperBound) - } - - @inline(__always) - internal func index(after i: Index) -> Index { - precondition(i < endIndex, "Can't advance above end index") - return _base.characterIndex(after: i) - } - - @inline(__always) - internal func index(before i: Index) -> Index { - precondition(i > startIndex, "Can't advance below start index") - return _base.characterIndex(before: i) - } - - @inline(__always) - internal func index(_ i: Index, offsetBy distance: Int) -> Index { - precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - let j = _base.characterIndex(i, offsetBy: distance) - precondition(j >= startIndex && j <= endIndex, "Index out of bounds") - return j - } - - internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - guard let j = _base.characterIndex(i, offsetBy: distance, limitedBy: limit) else { return nil } - precondition(j >= startIndex && j <= endIndex, "Index out of bounds") - return j - } - - internal func distance(from start: Index, to end: Index) -> Int { - precondition(start >= startIndex && start <= endIndex, "Index out of bounds") - precondition(end >= startIndex && end <= endIndex, "Index out of bounds") - return _base.characterDistance(from: start, to: end) - } - - internal subscript(position: Index) -> Character { - precondition(position >= startIndex && position < endIndex, "Index out of bounds") - return _base[character: position] - } - - internal subscript(bounds: Range) -> Self { - precondition( - bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex, - "Range out of bounds") - return Self(_base, in: bounds) - } -} - -#endif diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift index 1a889f16..b64bd08b 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { - internal struct UTF16View { + internal struct UTF16View: Sendable { internal var _base: _BString internal var _bounds: Range diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift index 549494d4..7c50124e 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { - internal struct UTF8View { + internal struct UTF8View: Sendable { internal var _base: _BString internal var _bounds: Range diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift index 6c7ef34a..7e477c2b 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { - internal struct UnicodeScalarView { + internal struct UnicodeScalarView: Sendable { internal var _base: _BString internal var _bounds: Range @@ -39,6 +39,13 @@ extension _BSubstring { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + internal init(_ view: _BSubstring.UnicodeScalarView) { + self.init(_from: view._base, in: view._bounds) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView { internal var base: _BString.UnicodeScalarView { _base.unicodeScalars } @@ -120,4 +127,125 @@ extension _BSubstring.UnicodeScalarView: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UnicodeScalarView { + /// Run the closure `body` to mutate the contents of this view within `range`, then update + /// the bounds of this view to maintain their logical position in the resulting string. + /// The `range` argument is validated to be within the original bounds of the substring. + internal mutating func _mutateBasePreservingBounds( + in range: Range, + with body: (inout _BString.UnicodeScalarView) -> R + ) -> R { + precondition( + range.lowerBound >= _bounds.lowerBound && range.upperBound <= _bounds.upperBound, + "Range out of bounds") + + let startOffset = self.startIndex._utf8Offset + let endOffset = self.endIndex._utf8Offset + let oldCount = self._base.utf8Count + + var view = _BString.UnicodeScalarView(_base: self._base) + self._base = _BString() + + defer { + // The Unicode scalar view is regular -- we just need to maintain the UTF-8 offsets of + // our bounds across the mutation. No extra adjustment/rounding is necessary. + self._base = view._base + let delta = self._base.utf8Count - oldCount + let start = _base.utf8Index(at: startOffset)._knownScalarAligned() + let end = _base.utf8Index(at: endOffset + delta)._knownScalarAligned() + self._bounds = start ..< end + } + return body(&view) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UnicodeScalarView: RangeReplaceableCollection { + internal init() { + self.init(_substring: _BSubstring()) + } + + internal mutating func reserveCapacity(_ n: Int) { + // Do nothing. + } + + internal mutating func replaceSubrange>( + _ subrange: Range, with newElements: __owned C + ) { + _mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) } + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned String.UnicodeScalarView + ) { + _mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) } + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned Substring.UnicodeScalarView + ) { + _mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) } + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned _BString.UnicodeScalarView + ) { + _mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) } + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: __owned _BSubstring.UnicodeScalarView + ) { + _mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) } + } + + internal init>(_ elements: S) { + let base = _BString.UnicodeScalarView(elements) + self.init(base._base, in: base.startIndex ..< base.endIndex) + } + + internal mutating func append>(contentsOf newElements: __owned S) { + _mutateBasePreservingBounds(in: endIndex ..< endIndex) { + $0.append(contentsOf: newElements) + } + } + + internal mutating func insert(_ newElement: UnicodeScalar, at i: Index) { + _mutateBasePreservingBounds(in: i ..< i) { + $0.insert(newElement, at: i) + } + } + + + internal mutating func insert>( + contentsOf newElements: __owned C, at i: Index + ) { + _mutateBasePreservingBounds(in: i ..< i) { + $0.insert(contentsOf: newElements, at: i) + } + } + + @discardableResult + internal mutating func remove(at i: Index) -> UnicodeScalar { + _mutateBasePreservingBounds(in: i ..< i) { + $0.remove(at: i) + } + } + + internal mutating func removeSubrange(_ bounds: Range) { + _mutateBasePreservingBounds(in: bounds) { + $0.removeSubrange(bounds) + } + } + + internal mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + let bounds = _bounds + _mutateBasePreservingBounds(in: bounds) { + $0.removeSubrange(bounds) + } + assert(_bounds.isEmpty) + } +} + #endif diff --git a/Sources/RopeModule/BString/Views/_BSubstring.swift b/Sources/RopeModule/BString/Views/_BSubstring.swift index 849d510f..ed80ed1e 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -struct _BSubstring { +struct _BSubstring: Sendable { var _base: _BString var _bounds: Range @@ -32,13 +32,6 @@ struct _BSubstring { } } -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - internal subscript(bounds: Range) -> _BSubstring { - _BSubstring(self, in: bounds) - } -} - @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { internal var base: _BString { _base } @@ -46,17 +39,157 @@ extension _BSubstring { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { - typealias Index = _BString.Index + func _foreachChunk( + _ body: (Substring) -> Void + ) { + self._base._foreachChunk(from: _bounds.lowerBound, to: _bounds.upperBound, body) + } +} +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: CustomStringConvertible { + internal var description: String { + String(_from: _base, in: _bounds) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: ExpressibleByStringLiteral { + internal init(stringLiteral value: String) { + self.init(value) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: LosslessStringConvertible { + // init?(_: String) is implemented by RangeReplaceableCollection.init(_:) +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: Equatable { + internal static func ==(left: Self, right: Self) -> Bool { + _BString.characterwiseIsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: Hashable { + internal func hash(into hasher: inout Hasher) { + _base.hashCharacters(into: &hasher, from: _bounds) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: BidirectionalCollection { + typealias Index = _BString.Index + typealias Element = Character + typealias SubSequence = Self + + @inline(__always) internal var startIndex: Index { _bounds.lowerBound } + @inline(__always) internal var endIndex: Index { _bounds.upperBound } - internal subscript(bounds: Range) -> _BSubstring { + internal var count: Int { + distance(from: _bounds.lowerBound, to: _bounds.upperBound) + } + + @inline(__always) + internal func index(after i: Index) -> Index { + precondition(i < endIndex, "Can't advance above end index") + return _base.characterIndex(after: i) + } + + @inline(__always) + internal func index(before i: Index) -> Index { + precondition(i > startIndex, "Can't advance below start index") + return _base.characterIndex(before: i) + } + + @inline(__always) + internal func index(_ i: Index, offsetBy distance: Int) -> Index { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + let j = _base.characterIndex(i, offsetBy: distance) + precondition(j >= startIndex && j <= endIndex, "Index out of bounds") + return j + } + + internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + guard let j = _base.characterIndex(i, offsetBy: distance, limitedBy: limit) else { return nil } + precondition(j >= startIndex && j <= endIndex, "Index out of bounds") + return j + } + + internal func distance(from start: Index, to end: Index) -> Int { + precondition(start >= startIndex && start <= endIndex, "Index out of bounds") + precondition(end >= startIndex && end <= endIndex, "Index out of bounds") + return _base.characterDistance(from: start, to: end) + } + + internal subscript(position: Index) -> Character { + precondition(position >= startIndex && position < endIndex, "Index out of bounds") + return _base[character: position] + } + + internal subscript(bounds: Range) -> Self { precondition( bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex, "Range out of bounds") - return _BSubstring(self._base, in: bounds) + return Self(_base, in: bounds) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring { + /// Run the closure `body` to mutate the contents of this view within `range`, then update + /// the bounds of this view to maintain an approximation of their logical position in the + /// resulting string. + /// + /// The `range` argument is validated to be within the original bounds of the substring. + internal mutating func _mutateBasePreservingBounds( + in range: Range, + with body: (inout _BString) -> R + ) -> R { + precondition( + range.lowerBound >= _bounds.lowerBound && range.upperBound <= _bounds.upperBound, + "Range out of bounds") + + let startOffset = self.startIndex._utf8Offset + let endOffset = self.endIndex._utf8Offset + let oldCount = self._base.utf8Count + + defer { + // Substring mutations may change grapheme boundaries across the bounds of the original + // substring value, and we need to ensure that the substring's bounds remain well-aligned. + // Unfortunately, there are multiple ways of doing this, none of which are obviously + // superior to others. To keep the behavior easier to explan, we emulate substring + // initialization and round the start and end indices down to the nearest Character boundary + // after each mutation. + let delta = self._base.utf8Count - oldCount + let start = _base.characterIndex(roundingDown: Index(_utf8Offset: startOffset)) + let end = _base.characterIndex(roundingDown: Index(_utf8Offset: endOffset + delta)) + self._bounds = start ..< end + } + return body(&self._base) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: RangeReplaceableCollection { + init() { + let str = _BString() + let bounds = Range(uncheckedBounds: (str.startIndex, str.endIndex)) + self.init(_unchecked: str, in: bounds) + } + + internal mutating func replaceSubrange( + _ subrange: Range, with newElements: C + ) where C.Element == Character { + _mutateBasePreservingBounds(in: subrange) { + $0.replaceSubrange(subrange, with: newElements) + } } } diff --git a/Sources/RopeModule/BigString/BigString+CharacterView.swift b/Sources/RopeModule/BigString/BigString+CharacterView.swift index e6a366c9..d51acb8c 100644 --- a/Sources/RopeModule/BigString/BigString+CharacterView.swift +++ b/Sources/RopeModule/BigString/BigString+CharacterView.swift @@ -53,14 +53,14 @@ extension BigString.Index: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: Equatable { public static func == (left: Self, right: Self) -> Bool { - left._guts.characterIsEqual(to: right._guts) + left._guts.characterwiseIsEqual(to: right._guts) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: Comparable { public static func < (left: Self, right: Self) -> Bool { - left._guts.characterIsLess(than: right._guts) + left._guts.characterwiseIsLess(than: right._guts) } } @@ -196,7 +196,7 @@ extension BigString: RangeReplaceableCollection { public init(_ elements: Self.SubSequence) { let lower = elements.startIndex._value let upper = elements.endIndex._value - self._guts = _BString(elements.base._guts, in: lower ..< upper) + self._guts = _BString(_from: elements.base._guts, in: lower ..< upper) } public init(repeating repeatedValue: Character, count: Int) { @@ -242,7 +242,7 @@ extension BigString: RangeReplaceableCollection { public mutating func append(contentsOf newElements: __owned Self.SubSequence) { let lower = newElements.startIndex._value let upper = newElements.endIndex._value - _guts.append(contentsOf: newElements.base._guts, in: lower ..< upper) + _guts._append(contentsOf: newElements.base._guts, in: lower ..< upper) } public mutating func insert(_ newElement: __owned Character, at i: Index) { @@ -276,7 +276,7 @@ extension BigString: RangeReplaceableCollection { public mutating func insert(contentsOf newElements: __owned Self.SubSequence, at i: Index) { let lower = newElements.startIndex._value let upper = newElements.endIndex._value - _guts.insert(contentsOf: newElements.base._guts, in: lower ..< upper, at: i._value) + _guts._insert(contentsOf: newElements.base._guts, in: lower ..< upper, at: i._value) } @discardableResult diff --git a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift index a24d4ecc..91708379 100644 --- a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift @@ -142,19 +142,26 @@ extension BigString.UnicodeScalarView: BidirectionalCollection { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: RangeReplaceableCollection { - public mutating func replaceSubrange( + public mutating func replaceSubrange( _ subrange: Range, - with newElements: __owned some Collection - ) { - if let newElements = newElements as? Self { - replaceSubrange(subrange, with: newElements) - } else if let newElements = newElements as? String.UnicodeScalarView { - replaceSubrange(subrange, with: newElements) - } else if let newElements = newElements as? Substring.UnicodeScalarView { - replaceSubrange(subrange, with: newElements) - } else { - _guts.replaceSubrange(subrange._base, with: _BString(newElements)) + with newElements: __owned C + ) where C.Element == Unicode.Scalar { + if C.self == BigString.UnicodeScalarView.self { + let replacement = _identityCast(newElements, to: BigString.UnicodeScalarView.self) + _guts.replaceSubrange(subrange._base, with: replacement._guts) + return } + if C.self == String.UnicodeScalarView.self { + let replacement = _identityCast(newElements, to: String.UnicodeScalarView.self) + _guts.replaceSubrange(subrange._base, with: String(replacement)) + return + } + if C.self == Substring.UnicodeScalarView.self { + let replacement = _identityCast(newElements, to: Substring.UnicodeScalarView.self) + _guts.replaceSubrange(subrange._base, with: Substring(replacement)) + return + } + _guts.replaceSubrange(subrange._base, with: _BString(_from: newElements)) } public mutating func replaceSubrange( @@ -184,24 +191,31 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { _guts = .init() } - public init(_ elements: some Sequence) { - if let elements = elements as? Self { + public init(_ elements: S) where S.Element == UnicodeScalar { + if S.self == BigString.UnicodeScalarView.self { + let elements = _identityCast(elements, to: BigString.UnicodeScalarView.self) self._guts = elements._guts - } else if let elements = elements as? String.UnicodeScalarView { - self._guts = _BString(elements) - } else if let elements = elements as? Substring.UnicodeScalarView { - self._guts = _BString(elements) - } else { - self._guts = _BString(elements) + return } + if S.self == String.UnicodeScalarView.self { + let elements = _identityCast(elements, to: String.UnicodeScalarView.self) + self._guts = _BString(_from: String(elements)) + return + } + if S.self == Substring.UnicodeScalarView.self { + let elements = _identityCast(elements, to: Substring.UnicodeScalarView.self) + self._guts = _BString(_from: Substring(elements)) + return + } + self._guts = _BString(_from: elements) } public init(_ elements: String.UnicodeScalarView) { - self._guts = _BString(elements) + self._guts = _BString(_from: String(elements)) } public init(_ elements: Substring.UnicodeScalarView) { - self._guts = _BString(elements) + self._guts = _BString(_from: Substring(elements)) } public init(_ elements: Self) { @@ -211,7 +225,7 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { public init(_ elements: Self.SubSequence) { let lower = elements.startIndex._value let upper = elements.endIndex._value - self._guts = _BString(elements.base._guts, in: lower ..< upper) + self._guts = _BString(_from: elements.base._guts, in: lower ..< upper) } public init(repeating scalar: Unicode.Scalar, count: Int) { @@ -222,16 +236,32 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { _guts.append(contentsOf: String(newElement)) } - public mutating func append(contentsOf newElements: __owned some Sequence) { - if let newElements = newElements as? Self { - self.append(contentsOf: newElements) - } else if let newElements = newElements as? String.UnicodeScalarView { - self.append(contentsOf: newElements) - } else if let newElements = newElements as? Substring.UnicodeScalarView { - self.append(contentsOf: newElements) - } else { - _guts.append(contentsOf: _BString(newElements)) + public mutating func append( + contentsOf newElements: __owned S + ) where S.Element == UnicodeScalar { + if S.self == BigString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) + _guts.append(contentsOf: newElements._guts) + return } + if S.self == BigString.UnicodeScalarView.SubSequence.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.SubSequence.self) + _guts._append( + contentsOf: newElements.base._guts, + in: newElements.startIndex._value ..< newElements.endIndex._value) + return + } + if S.self == String.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: String.UnicodeScalarView.self) + _guts.append(contentsOf: String(newElements)) + return + } + if S.self == Substring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: Substring.UnicodeScalarView.self) + _guts.append(contentsOf: Substring(newElements)) + return + } + _guts.append(contentsOf: _BString(_from: newElements)) } public mutating func append(contentsOf newElements: __owned String.UnicodeScalarView) { @@ -249,23 +279,40 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { public mutating func append(contentsOf newElements: __owned Self.SubSequence) { let lower = newElements.startIndex._value let upper = newElements.endIndex._value - _guts.append(contentsOf: newElements.base._guts, in: lower ..< upper) + _guts._append(contentsOf: newElements.base._guts, in: lower ..< upper) } public mutating func insert(_ newElement: __owned Unicode.Scalar, at i: Index) { _guts.insert(contentsOf: String(newElement), at: i._value) } - public mutating func insert(contentsOf newElements: some Collection, at i: Index) { - if let newElements = newElements as? Self { - self.insert(contentsOf: newElements, at: i) - } else if let newElements = newElements as? String.UnicodeScalarView { - self.insert(contentsOf: newElements, at: i) - } else if let newElements = newElements as? Substring.UnicodeScalarView { - self.insert(contentsOf: newElements, at: i) - } else { - _guts.insert(contentsOf: _BString(newElements), at: i._value) + public mutating func insert>( + contentsOf newElements: C, at i: Index + ) { + if C.self == BigString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) + self._guts.insert(contentsOf: newElements._guts, at: i._value) + return } + if C.self == BigString.UnicodeScalarView.SubSequence.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.SubSequence.self) + self._guts._insert( + contentsOf: newElements.base._guts, + in: newElements.startIndex._value ..< newElements.endIndex._value, + at: i._value) + return + } + if C.self == String.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: String.UnicodeScalarView.self) + self._guts.insert(contentsOf: String(newElements), at: i._value) + return + } + if C.self == Substring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: Substring.UnicodeScalarView.self) + self._guts.insert(contentsOf: Substring(newElements), at: i._value) + return + } + _guts.insert(contentsOf: _BString(_from: newElements), at: i._value) } public mutating func insert(contentsOf newElements: String.UnicodeScalarView, at i: Index) { @@ -283,7 +330,7 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { public mutating func insert(contentsOf newElements: __owned Self.SubSequence, at i: Index) { let lower = newElements.startIndex._value let upper = newElements.endIndex._value - _guts.insert(contentsOf: newElements.base._guts, in: lower ..< upper, at: i._value) + _guts._insert(contentsOf: newElements.base._guts, in: lower ..< upper, at: i._value) } @discardableResult diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 50737dd7..0426301a 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -434,7 +434,7 @@ class TestBString: XCTestCase { } } - func testCharacterIndexRounding() { + func testCharacterIndexRoundingDown() { let ref = sampleString let str = _BString(ref) @@ -460,12 +460,40 @@ class TestBString: XCTestCase { check(str.utf8.indices) check(str.utf16.indices) check(str.unicodeScalars.indices) - check(str.characters.indices) + check(str.indices) XCTAssertEqual(str.characterIndex(roundingDown: str.endIndex), str.endIndex) } - func testUnicodeScalarIndexRounding() { + func testCharacterIndexRoundingUp() { + let ref = sampleString + let str = _BString(ref) + + func check( + _ indices: some Sequence<_BString.Index>, + file: StaticString = #file, + line: UInt = #line + ) { + var current = str.startIndex + for i in indices { + let j = str.characterIndex(roundingUp: i) + XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + while i >= current { + current = str.characterIndex(after: current) + } + } + XCTAssertEqual(current, str.endIndex, "end", file: file, line: line) + } + + check(str.utf8.indices) + check(str.utf16.indices) + check(str.unicodeScalars.indices) + check(str.indices) + XCTAssertEqual(str.characterIndex(roundingDown: str.endIndex), str.endIndex) + + } + + func testUnicodeScalarIndexRoundingDown() { let ref = sampleString let str = _BString(ref) @@ -490,8 +518,57 @@ class TestBString: XCTestCase { check(str.utf8.indices) check(str.utf16.indices) check(str.unicodeScalars.indices) - check(str.characters.indices) + check(str.indices) XCTAssertEqual(str.unicodeScalarIndex(roundingDown: str.endIndex), str.endIndex) } + + func testUnicodeScalarIndexRoundingUp() { + let ref = sampleString + let str = _BString(ref) + + func check( + _ indices: some Sequence<_BString.Index>, + file: StaticString = #file, + line: UInt = #line + ) { + var current = str.startIndex + for i in indices { + while i > current { + current = str.unicodeScalarIndex(after: current) + } + let j = str.unicodeScalarIndex(roundingUp: i) + XCTAssertEqual(j, current, "\(i)", file: file, line: line) + } + } + + check(str.utf8.indices) + check(str.utf16.indices) + check(str.unicodeScalars.indices) + check(str.indices) + XCTAssertEqual(str.unicodeScalarIndex(roundingDown: str.endIndex), str.endIndex) + } + + func testSubstringMutationIndexRounding() { + let b1: _BString = "Foobar" + var s1 = b1.suffix(3) + XCTAssertEqual(s1, "bar") + s1.insert("\u{308}", at: s1.startIndex) // Combining diaresis + XCTAssertEqual(s1.base, "Foöbar") + XCTAssertEqual(s1, "öbar") + + let b2: _BString = "Foo👩👧bar" // WOMAN, GIRL + var s2: _BSubstring = b2.prefix(4) + XCTAssertEqual(s2, "Foo👩") + s2.append("\u{200d}") // ZWJ + XCTAssertEqual(s2, "Foo") + XCTAssertEqual(s2.base, "Foo👩‍👧bar") // family with mother and daughter + + let b3: _BString = "Foo🇺🇸🇨🇦🇺🇸🇨🇦bar" // Regional indicators "USCAUSCA" + var s3: _BSubstring = b3.prefix(7) + XCTAssertEqual(s3, "Foo🇺🇸🇨🇦🇺🇸🇨🇦") + s3.insert("\u{1f1ed}", at: s3.index(s3.startIndex, offsetBy: 3)) // Regional indicator "H" + XCTAssertEqual(s3, "Foo🇭🇺🇸🇨🇦🇺🇸🇨\u{1f1e6}") // Regional indicators "HUSCAUSCA" + XCTAssertEqual(s3.base, "Foo🇭🇺🇸🇨🇦🇺🇸🇨\u{1f1e6}bar") + } } #endif diff --git a/Tests/RopeModuleTests/TestBString2.swift b/Tests/RopeModuleTests/TestBString2.swift index 91c8b894..a4ea9322 100644 --- a/Tests/RopeModuleTests/TestBString2.swift +++ b/Tests/RopeModuleTests/TestBString2.swift @@ -33,7 +33,7 @@ class TestBString2: CollectionTestCase { func testCharacterView() { let str = _BString(shortSample) - checkBidirectionalCollection(str.characters, expectedContents: shortSample) + checkBidirectionalCollection(str, expectedContents: shortSample) } }