File: AttributedString%2B_InternalRunsSlice.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (146 lines) | stat: -rw-r--r-- 5,573 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if FOUNDATION_FRAMEWORK
@_spi(Unstable) internal import CollectionsInternal
#elseif canImport(_RopeModule)
internal import _RopeModule
#elseif canImport(_FoundationCollections)
internal import _FoundationCollections
#endif

extension AttributedString {
    /// A mutable rope of `_InternalRun` values, sliced on an arbitrary UTF-8 offset range.
    /// Boundary runs may be sliced into two parts; this collection transparently constructs
    /// virtual (sub-)runs representing the parts that are logically inside it.
    ///
    /// Mutating one of these virtual runs effectively splits the underlying run, creating new runs
    /// as needed. The usual run coalescing rules continue to apply, as if the underlying rope was
    /// not sliced at all -- e.g., run coalescing will merge runs across the slice boundary.
    struct _InternalRunsSlice {
        typealias _AttributeStorage = AttributedString._AttributeStorage
        typealias _InternalRun = AttributedString._InternalRun
        typealias _InternalRuns = AttributedString._InternalRuns
        typealias Storage = Rope<_InternalRun>

        /// The guts of the underlying attributed string.
        var _guts: Guts

        /// The UTF-8 offset range of this slice.
        ///
        /// We cannot (easily) store actual indices for the bounds -- mutations via `update`
        /// would invalidate them, and keeping them updated would be too much trouble.
        var _utf8Bounds: Range<Int>

        init(_ guts: Guts, utf8Bounds: Range<Int>) {
            assert(utf8Bounds.lowerBound >= 0 && utf8Bounds.upperBound <= guts.string.utf8.count)
            self._guts = guts
            self._utf8Bounds = utf8Bounds
        }
    }
}

extension AttributedString._InternalRunsSlice: BidirectionalCollection {
    // Note: This is a true bidirectional collection, only supporting step-by-step access.
    // (It would be possible to implement `index(_:offsetBy:)` in logarithmic time, but we have
    // no use case for it -- this type is really just used to enumerate/mutate runs one by one
    // within a certain range.

    typealias Element = _InternalRun

    /// Runs slices share index values with their base collection -- even for indices that address
    /// partial runs on the edges of the slice.
    typealias Index = _InternalRuns.Index

    var isEmpty: Bool {
        _utf8Bounds.isEmpty
    }

    var startIndex: Index {
        _guts.runs.index(atUTF8Offset: _utf8Bounds.lowerBound).index
    }

    /// For non-empty slices, we reuse the base collection's endIndex as the slice's end.
    /// This is O(1) and avoids having to find an index representing the actual end position,
    /// which would be annoying to do when the bounds slice the last run in two halves.
    ///
    /// For empty slices, we need to return the start index to avoid breaking Collection
    /// expectations.
    var endIndex: Index {
        isEmpty ? startIndex : _guts.runs.endIndex
    }

    subscript(index: Index) -> Element {
        let (attributes, fullRange) = _guts.run(at: index)
        let clampedRange = fullRange.clamped(to: _utf8Bounds)
        precondition(!clampedRange.isEmpty, "Index out of bounds")
        return _InternalRun(length: clampedRange.count, attributes: attributes)
    }

    func index(after i: Index) -> Index {
        // Note: this does not check that `i` is within the bounds of the slice.
        let j = _guts.runs.index(after: i)
        if j.utf8Offset >= _utf8Bounds.upperBound { return endIndex }
        return j
    }

    func index(before i: Index) -> Index {
        // Note: this does not check that `i` is within the bounds of the slice.
        if i == _guts.runs.endIndex {
            return _guts.runs.index(atUTF8Offset: _utf8Bounds.upperBound, preferEnd: true).index
        }
        return _guts.runs.index(before: i)
    }
}

extension AttributedString._InternalRunsSlice {
    func update(
        at index: inout _InternalRuns.Index,
        with body: (
            _ attributes: inout _AttributeStorage,
            _ utf8Range: Range<Int>,
            _ mutated: inout Bool
        ) -> Void
    ) {
        _guts.updateRun(at: &index, within: _utf8Bounds, with: body)
    }

    func updateEach(
        with body: (
            _ attributes: inout _AttributeStorage,
            _ utf8Range: Range<Int>,
            _ mutated: inout Bool
        ) -> Void
    ) {
        var i = self.startIndex
        while i < self.endIndex {
            self.update(at: &i, with: body)
            self.formIndex(after: &i)
        }
    }

    func updateEach(
        when predicate: (_AttributeStorage) -> Bool,
        with body: (
            _ attributes: inout _AttributeStorage,
            _ utf8Range: Range<Int>
        ) -> Void
    ) {
        var i = self.startIndex
        while i < self.endIndex {
            if predicate(self._guts.runs[i].attributes) {
                self.update(at: &i) { attributes, range, _ in body(&attributes, range) }
            }
            self.formIndex(after: &i)
        }
    }
}