_BString, _BSubstring: Merge character views into top-level types. Add RangeReplaceableCollection conformances.

This emulates the standard String.
This commit is contained in:
Karoy Lorentey committed 2023-03-20 13:12:12 -07:00
1 parent eda72e344f
commit a10439bc32
30 files changed
+1195 -441

No files matched your search

@@ -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[...])
}
@@ -18,10 +18,6 @@ internal struct _BString: Sendable {
var rope: Rope
internal init() {
rope = Rope()
}
internal init(rope: Rope) {
self.rope = rope
}
@@ -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<Index>) -> _BSubstring {
_BSubstring(self, in: bounds)
}
}
#endif
@@ -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
@@ -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
@@ -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<Index>,
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
@@ -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
@@ -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) {
@@ -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
@@ -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<C: Collection<Character>>(
_ subrange: Range<Index>, 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<Index>, with newElements: __owned String
) {
_replaceSubrange(subrange, with: newElements)
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned Substring
) {
_replaceSubrange(subrange, with: newElements)
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned _BString
) {
_replaceSubrange(subrange, with: newElements)
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned _BSubstring
) {
_replaceSubrange(subrange, with: newElements)
}
internal init<S: Sequence<Character>>(_ 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<S: Sequence<Character>>(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<C: Collection<Character>>(
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<Index>) {
_removeSubrange(bounds)
}
internal mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
self = _BString()
}
}
#endif
@@ -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
@@ -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
@@ -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<Index>) {
mutating func _append(contentsOf other: __owned _BString, in range: Range<Index>) {
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<Index>) {
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
@@ -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<Character>) {
internal init(_from input: some Sequence<Character>) {
var builder = Builder()
var piece = ""
for character in input {
@@ -36,7 +36,7 @@ extension _BString {
self = builder.finalize()
}
internal init(_ input: some Sequence<UnicodeScalar>) {
internal init(_from input: some Sequence<UnicodeScalar>) {
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<Index>
) {
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
@@ -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<Index>, at index: Index) {
mutating func _insert(contentsOf other: __owned Self, in range: Range<Index>, 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 {
@@ -13,7 +13,7 @@
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
mutating func removeSubrange(_ bounds: Range<Index>) {
mutating func _removeSubrange(_ bounds: Range<Index>) {
precondition(bounds.upperBound <= endIndex, "Index out of bounds")
if bounds.isEmpty { return }
let lower = bounds.lowerBound._utf8Offset
@@ -13,7 +13,7 @@
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
extension _BString {
mutating func replaceSubrange(_ range: Range<Index>, with newElements: some StringProtocol) {
mutating func _replaceSubrange(_ range: Range<Index>, 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<Index>, with newElements: _BString) {
mutating func _replaceSubrange(_ range: Range<Index>, 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<Index>,
with newElements: _BSubstring
) {
_replaceSubrange(targetRange, with: newElements._base, in: newElements._bounds)
}
mutating func _replaceSubrange(
_ targetRange: Range<Index>,
with newElements: _BString,
in sourceRange: Range<Index>
@@ -46,7 +53,7 @@ extension _BString {
return
}
if targetRange._isEmptyUTF8 {
insert(
_insert(
contentsOf: newElements,
in: sourceRange,
at: targetRange.lowerBound)
@@ -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<Index>) -> _BSubstring.CharacterView {
_BSubstring.CharacterView(_base, in: bounds)
}
}
#endif
@@ -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)
@@ -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)
@@ -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<C: Collection<UnicodeScalar>>(
_ subrange: Range<Index>, 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<Index>, with newElements: __owned String.UnicodeScalarView
) {
_base._replaceSubrange(subrange, with: String(newElements))
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned Substring.UnicodeScalarView
) {
_base._replaceSubrange(subrange, with: Substring(newElements))
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned _BString.UnicodeScalarView
) {
_base._replaceSubrange(subrange, with: newElements._base)
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned _BSubstring.UnicodeScalarView
) {
_base._replaceSubrange(subrange, with: newElements._base, in: newElements._bounds)
}
internal init<S: Sequence<UnicodeScalar>>(_ 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<S: Sequence<UnicodeScalar>>(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<C: Collection<UnicodeScalar>>(
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<Index>) {
_base._removeSubrange(bounds)
}
internal mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
self._base = _BString()
}
}
#endif
@@ -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<Index>
internal init(_unchecked base: _BString, in bounds: Range<Index>) {
self._base = base
self._bounds = bounds
}
internal init(_ base: _BString, in bounds: Range<Index>) {
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<Index>) -> Self {
precondition(
bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex,
"Range out of bounds")
return Self(_base, in: bounds)
}
}
#endif
@@ -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<Index>
@@ -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<Index>
@@ -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<Index>
@@ -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<R>(
in range: Range<Index>,
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<C: Collection<UnicodeScalar>>(
_ subrange: Range<Index>, with newElements: __owned C
) {
_mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) }
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned String.UnicodeScalarView
) {
_mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) }
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned Substring.UnicodeScalarView
) {
_mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) }
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned _BString.UnicodeScalarView
) {
_mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) }
}
internal mutating func replaceSubrange(
_ subrange: Range<Index>, with newElements: __owned _BSubstring.UnicodeScalarView
) {
_mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) }
}
internal init<S: Sequence<UnicodeScalar>>(_ elements: S) {
let base = _BString.UnicodeScalarView(elements)
self.init(base._base, in: base.startIndex ..< base.endIndex)
}
internal mutating func append<S: Sequence<UnicodeScalar>>(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<C: Collection<UnicodeScalar>>(
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<Index>) {
_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
@@ -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<Index>
@@ -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<Index>) -> _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<Index>) -> _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<Index>) -> 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<R>(
in range: Range<Index>,
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<C: Collection>(
_ subrange: Range<Index>, with newElements: C
) where C.Element == Character {
_mutateBasePreservingBounds(in: subrange) {
$0.replaceSubrange(subrange, with: newElements)
}
}
}