|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2024 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +#if FOUNDATION_FRAMEWORK |
| 14 | +@_spi(Unstable) internal import CollectionsInternal |
| 15 | +#elseif canImport(_RopeModule) |
| 16 | +internal import _RopeModule |
| 17 | +#elseif canImport(_FoundationCollections) |
| 18 | +internal import _FoundationCollections |
| 19 | +#endif |
| 20 | + |
| 21 | +// MARK: - Internal Index Updating |
| 22 | + |
| 23 | +extension AttributedString.Guts { |
| 24 | + func _prepareTrackedIndicesUpdate(mutationRange: Range<BigString.Index>) { |
| 25 | + // Move any range endpoints inside of the mutation range to outside of the mutation range since a range should never end up splitting a mutation |
| 26 | + for idx in 0 ..< trackedRanges.count { |
| 27 | + let lowerBoundWithinMutation = trackedRanges[idx].lowerBound > mutationRange.lowerBound && trackedRanges[idx].lowerBound < mutationRange.upperBound |
| 28 | + let upperBoundWithinMutation = trackedRanges[idx].upperBound > mutationRange.lowerBound && trackedRanges[idx].upperBound < mutationRange.upperBound |
| 29 | + switch (lowerBoundWithinMutation, upperBoundWithinMutation) { |
| 30 | + case (true, true): |
| 31 | + // Range is fully within mutation, collapse it to the start of the mutation |
| 32 | + trackedRanges[idx] = Range(uncheckedBounds: (mutationRange.lowerBound, mutationRange.lowerBound)) |
| 33 | + case (true, false): |
| 34 | + // Range starts within mutation but extends beyond mutation - remove portion within mutation |
| 35 | + trackedRanges[idx] = Range(uncheckedBounds: (mutationRange.upperBound, trackedRanges[idx].upperBound)) |
| 36 | + case (false, true): |
| 37 | + // Range starts before mutation but extends into mutation - remove portion within mutation |
| 38 | + trackedRanges[idx] = Range(uncheckedBounds: (trackedRanges[idx].lowerBound, mutationRange.lowerBound)) |
| 39 | + case (false, false): |
| 40 | + // Neither endpoint of range is within mutation, leave as-is |
| 41 | + break |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + func _finalizeTrackedIndicesUpdate(mutationStartOffset: Int, isInsertion: Bool, utf8LengthDelta: Int) { |
| 47 | + // Update indices to point to the correct offsets based on the mutation deltas |
| 48 | + for idx in 0 ..< trackedRanges.count { |
| 49 | + var lowerBound = trackedRanges[idx].lowerBound |
| 50 | + var upperBound = trackedRanges[idx].upperBound |
| 51 | + |
| 52 | + // Shift the lower bound if either: |
| 53 | + // A) The lower bound is greater than the start of the mutation (meaning it must be after the mutation due to the prepare step) |
| 54 | + // B) The lower bound is equal to the start of the mutation, but the mutation is an insertion (meaning the text is inserted before the start offset) |
| 55 | + if lowerBound.utf8Offset > mutationStartOffset || (lowerBound.utf8Offset == mutationStartOffset && isInsertion), utf8LengthDelta != 0 { |
| 56 | + lowerBound = string.utf8.index(string.startIndex, offsetBy: lowerBound.utf8Offset + utf8LengthDelta) |
| 57 | + } else { |
| 58 | + // Form new indices even if the offsets don't change to ensure the indices are valid in the newly-mutated rope |
| 59 | + string.formIndex(&lowerBound, offsetBy: 0) |
| 60 | + } |
| 61 | + // Shift the upper bound if either: |
| 62 | + // - The upper bound is greater than the start of the mutation (meaning it must be after the mutation due to the prepare step) |
| 63 | + // - The lower bound is shifted in any way (which therefore requires the upper bound to be shifted). This is the case when the tracked range is empty and is at the location of an insertion mutation |
| 64 | + if upperBound.utf8Offset > mutationStartOffset || lowerBound != trackedRanges[idx].lowerBound, utf8LengthDelta != 0 { |
| 65 | + upperBound = string.utf8.index(string.startIndex, offsetBy: upperBound.utf8Offset + utf8LengthDelta) |
| 66 | + } else { |
| 67 | + // Form new indices even if the offsets don't change to ensure the indices are valid in the newly-mutated rope |
| 68 | + string.formIndex(&lowerBound, offsetBy: 0) |
| 69 | + } |
| 70 | + |
| 71 | + trackedRanges[idx] = Range(uncheckedBounds: (lowerBound, upperBound)) |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +// MARK: - Public API |
| 77 | + |
| 78 | +@available(FoundationPreview 6.2, *) |
| 79 | +extension AttributedString { |
| 80 | + // MARK: inout API |
| 81 | + |
| 82 | + /// Tracks the location of the provided range throughout the mutation closure, updating the provided range to one that represents the same effective locations after the mutation. If updating the provided range is not possible (tracking failed) then this function will fatal error. Use the Optional-returning variants to provide custom fallback behavior. |
| 83 | + /// - Parameters: |
| 84 | + /// - range: a range to track throughout the `body` closure |
| 85 | + /// - body: a mutating operation, or set of operations, to perform on the value of `self`. The value of `self` is provided to the closure as an `inout AttributedString` that the closure should mutate directly. Do not capture the value of `self` in the provided closure - the closure should mutate the provided `inout` copy. |
| 86 | + public mutating func transform<E>(updating range: inout Range<Index>, body: (inout AttributedString) throws(E) -> Void) throws(E) -> Void { |
| 87 | + guard let result = try self.transform(updating: range, body: body) else { |
| 88 | + fatalError("The provided mutation body did not allow for maintaining index tracking. Ensure that your mutation body mutates the provided AttributedString instead of replacing it with a different AttributedString or use the non-inout version of transform(updating:body:) which returns an Optional value to provide fallback behavior.") |
| 89 | + } |
| 90 | + range = result |
| 91 | + } |
| 92 | + |
| 93 | + /// Tracks the location of the provided ranges throughout the mutation closure, updating them to new ranges that represent the same effective locations after the mutation. If updating the provided ranges is not possible (tracking failed) then this function will fatal error. Use the Optional-returning variants to provide custom fallback behavior. |
| 94 | + /// - Parameters: |
| 95 | + /// - ranges: a list of ranges to track throughout the `body` closure. The updated array (after the function is called) is guaranteed to be the same size as the provided array. Updated ranges are located at the same indices as their respective original ranges in the input `ranges` array. |
| 96 | + /// - body: a mutating operation, or set of operations, to perform on the value of `self`. The value of `self` is provided to the closure as an `inout AttributedString` that the closure should mutate directly. Do not capture the value of `self` in the provided closure - the closure should mutate the provided `inout` copy. |
| 97 | + public mutating func transform<E>(updating ranges: inout [Range<Index>], body: (inout AttributedString) throws(E) -> Void) throws(E) -> Void { |
| 98 | + guard let result = try self.transform(updating: ranges, body: body) else { |
| 99 | + fatalError("The provided mutation body did not allow for maintaining index tracking. Ensure that your mutation body mutates the provided AttributedString instead of replacing it with a different AttributedString or use the non-inout version of transform(updating:body:) which returns an Optional value to provide fallback behavior.") |
| 100 | + } |
| 101 | + ranges = result |
| 102 | + } |
| 103 | + |
| 104 | + // MARK: Optional-returning API |
| 105 | + |
| 106 | + /// Tracks the location of the provided range throughout the mutation closure, returning a new, updated range that represents the same effective locations after the mutation |
| 107 | + /// - Parameters: |
| 108 | + /// - range: a range to track throughout the `mutation` block |
| 109 | + /// - mutation: a mutating operation, or set of operations, to perform on this `AttributedString` |
| 110 | + /// - Returns: the updated `Range` that is valid after the mutation has been performed, or `nil` if the mutation performed does not allow for tracking to succeed (such as replacing the provided inout variable with an entirely different AttributedString) |
| 111 | + public mutating func transform<E>(updating range: Range<Index>, body: (inout AttributedString) throws(E) -> Void) throws(E) -> Range<Index>? { |
| 112 | + try self.transform(updating: [range], body: body)?.first |
| 113 | + } |
| 114 | + |
| 115 | + /// Tracks the location of the provided ranges throughout the mutation closure, returning a new, updated range that represents the same effective locations after the mutation |
| 116 | + /// - Parameters: |
| 117 | + /// - index: an index to track throughout the `mutation` block |
| 118 | + /// - mutation: a mutating operation, or set of operations, to perform on this `AttributedString` |
| 119 | + /// - Returns: the updated `Range`s that is valid after the mutation has been performed, or `nil` if the mutation performed does not allow for tracking to succeed (such as replacing the provided inout variable with an entirely different AttributedString). When the return value is non-nil, the returned array is guaranteed to be the same size as the provided array with updated ranges at the same Array indices as their respective original ranges in the input array. |
| 120 | + public mutating func transform<E>(updating ranges: [Range<Index>], body: (inout AttributedString) throws(E) -> Void) throws(E) -> [Range<Index>]? { |
| 121 | + precondition(!ranges.isEmpty, "Cannot update an empty array of ranges") |
| 122 | + |
| 123 | + // Ensure we are uniquely referenced and mutate the tracked ranges to include the new ranges |
| 124 | + ensureUniqueReference() |
| 125 | + let originalCount = _guts.trackedRanges.count |
| 126 | + for range in ranges { |
| 127 | + precondition(range.lowerBound >= self.startIndex && range.lowerBound <= self.endIndex && range.upperBound >= self.startIndex && range.upperBound <= self.endIndex, "AttributedString index is out of bounds") |
| 128 | + _guts.trackedRanges.append(range._bstringRange) |
| 129 | + } |
| 130 | + |
| 131 | + // Ensure cleanup is performed regardless of whether the mutation closure throws or succeeds |
| 132 | + defer { |
| 133 | + // Ensure we are still uniquely referenced (it's possible we may have been uniquely referenced before, but the mutation closure created a new reference and we are no longer unique) |
| 134 | + ensureUniqueReference() |
| 135 | + |
| 136 | + |
| 137 | + // If the `trackedRanges` state is inconsistent, tracking has been lost |
| 138 | + if _guts.trackedRanges.count != originalCount + ranges.count { |
| 139 | + // Clear the ranges to prevent any future lingering issues with this AttributedString |
| 140 | + _guts.trackedRanges = [] |
| 141 | + } else { |
| 142 | + // Tracking state is consistent, so remove only the ranges we added earlier (to support recursive tracking) |
| 143 | + _guts.trackedRanges.removeSubrange(originalCount...) |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + try body(&self) |
| 148 | + |
| 149 | + guard _guts.trackedRanges.count == originalCount + ranges.count else { |
| 150 | + // Tracking state is inconsistent - return nil (defer block will handle cleanup) |
| 151 | + return nil |
| 152 | + } |
| 153 | + |
| 154 | + // Return the (mapped) array of ranges added above (defer block will handle cleanup) |
| 155 | + return _guts.trackedRanges.suffix(from: originalCount).map(\._attributedStringRange) |
| 156 | + } |
| 157 | +} |
0 commit comments