From 141c3939bf9e792e6add1aaa8faddf007c36dc7f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 6 Dec 2022 18:41:04 -0800 Subject: [PATCH 001/113] [DocC] Add documentation bundles for all three targets --- .gitignore | 1 + .../Collections.docc/Collections.md | 34 +++++ .../Collections.docc/Extensions/Deque.md | 67 +++++++++ .../Extensions/OrderedDictionary.Elements.md | 40 ++++++ .../Extensions/OrderedDictionary.Values.md | 27 ++++ .../Extensions/OrderedDictionary.md | 97 +++++++++++++ .../Extensions/OrderedSet.UnorderedView.md | 56 ++++++++ .../Collections.docc/Extensions/OrderedSet.md | 136 ++++++++++++++++++ .../DequeModule.docc/DequeModule.md | 3 + .../DequeModule.docc/Extensions/Deque.md | 64 +++++++++ .../Extensions/OrderedDictionary.Elements.md | 37 +++++ .../Extensions/OrderedDictionary.Values.md | 24 ++++ .../Extensions/OrderedDictionary.md | 94 ++++++++++++ .../Extensions/OrderedSet.UnorderedView.md | 53 +++++++ .../Extensions/OrderedSet.md | 133 +++++++++++++++++ .../OrderedCollections.md | 10 ++ Utils/generate-docs.sh | 92 ++++++++++++ 17 files changed, 968 insertions(+) create mode 100644 Sources/Collections/Collections.docc/Collections.md create mode 100644 Sources/Collections/Collections.docc/Extensions/Deque.md create mode 100644 Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Elements.md create mode 100644 Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Values.md create mode 100644 Sources/Collections/Collections.docc/Extensions/OrderedDictionary.md create mode 100644 Sources/Collections/Collections.docc/Extensions/OrderedSet.UnorderedView.md create mode 100644 Sources/Collections/Collections.docc/Extensions/OrderedSet.md create mode 100644 Sources/DequeModule/DequeModule.docc/DequeModule.md create mode 100644 Sources/DequeModule/DequeModule.docc/Extensions/Deque.md create mode 100644 Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Elements.md create mode 100644 Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Values.md create mode 100644 Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md create mode 100644 Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md create mode 100644 Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md create mode 100644 Sources/OrderedCollections/OrderedCollections.docc/OrderedCollections.md create mode 100755 Utils/generate-docs.sh diff --git a/.gitignore b/.gitignore index f0e519a2..397ae000 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ xcuserdata/ .*.sw? /Benchmarks/.swiftpm /Benchmarks/.build +.docc-build diff --git a/Sources/Collections/Collections.docc/Collections.md b/Sources/Collections/Collections.docc/Collections.md new file mode 100644 index 00000000..7a0322c5 --- /dev/null +++ b/Sources/Collections/Collections.docc/Collections.md @@ -0,0 +1,34 @@ +# ``Collections`` + +**Swift Collections** is an open-source package of data structure implementations for the Swift programming language. + +This package provides separate modules for each group of data structures it implements. For instance, if you only need a double-ended queue type, you can pull in only that by importing `DequeModule`. + +The top-level module `Collections` imports and reexports each of these smaller packages. Importing this module is a useful shortcut if you want to import all data structures, or if you don't care about bringing in more code than you need. + +```swift +import Collections + +var deque: Deque = ["Ted", "Rebecca"] +deque.prepend("Keeley") + +let people = OrderedSet(deque) +people.contains("Rebecca") // true +``` + +#### Additional Resources + +- [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/) +- [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72) + + +## Topics + +### Deque Module + +- ``Deque`` + +### Ordered Collections + +- ``OrderedSet`` +- ``OrderedDictionary`` diff --git a/Sources/Collections/Collections.docc/Extensions/Deque.md b/Sources/Collections/Collections.docc/Extensions/Deque.md new file mode 100644 index 00000000..c65ac432 --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/Deque.md @@ -0,0 +1,67 @@ +# ``Collections/Deque`` + + + + +## Topics + +### Creating a Deque + +- ``init()`` +- ``init(_:)-8tyaw`` +- ``init(_:)-1tqf4`` +- ``init(minimumCapacity:)`` +- ``init(repeating:count:)-4v1gt`` +- ``init(unsafeUninitializedCapacity:initializingWith:)`` + +### Inspecting a Deque + +- ``count-8wcnm`` +- ``isEmpty`` + +### Manipulating Elements at the Front + +- ``first`` +- ``prepend(_:)`` +- ``prepend(contentsOf:)-96y15`` +- ``prepend(contentsOf:)-51zn6`` +- ``removeFirst()-1vdmt`` +- ``removeFirst(_:)-2vuji`` +- ``popFirst()`` +- ``prefix(_:)`` + +### Manipulating Elements at the End + +- ``last`` +- ``append(_:)-9h4m7`` +- ``append(contentsOf:)-8rqnl`` +- ``append(contentsOf:)-29aoh`` +- ``removeLast()`` +- ``removeLast(_:)`` +- ``popLast()`` +- ``suffix(_:)`` + +### Manipulating Elements Elsewhere + +- ``subscript(_:)-9nk44`` +- ``subscript(_:)-6ee8i`` +- ``subscript(_:)-1klky`` +- ``subscript(_:)-ejld`` +- ``insert(_:at:)-9hsp7`` +- ``insert(contentsOf:at:)-1d60f`` +- ``replaceSubrange(_:with:)-5rtzd`` +- ``remove(at:)-3imgi`` + +### Reordering Elements + +- ``swapAt(_:_:)-7910s`` +- ``sort()`` +- ``sort(by:)`` +- ``reverse()`` +- ``shuffle()`` +- ``shuffle(using:)`` +- ``partition(by:)-90y0t`` + +### Memory Management + +- ``reserveCapacity(_:)`` diff --git a/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Elements.md b/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Elements.md new file mode 100644 index 00000000..8e77d426 --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Elements.md @@ -0,0 +1,40 @@ +# ``Collections/OrderedDictionary/Elements-swift.struct`` + + + + +## Topics + +### Inspecting an Elements View + +- ``isEmpty`` +- ``count`` + +### Accessing Elements + +- ``subscript(_:)-4xwc2`` +- ``keys`` +- ``values`` +- ``index(forKey:)`` + +### Removing Elements + +- ``remove(at:)`` +- ``removeSubrange(_:)-5x7oo`` +- ``removeSubrange(_:)-7wdak`` +- ``removeAll(keepingCapacity:)`` +- ``removeAll(where:)`` +- ``removeFirst()`` +- ``removeFirst(_:)`` +- ``removeLast()`` +- ``removeLast(_:)`` + +### Reordering Elements + +- ``swapAt(_:_:)`` +- ``reverse()`` +- ``sort()`` +- ``sort(by:)`` +- ``partition(by:)`` +- ``shuffle()`` +- ``shuffle(using:)`` diff --git a/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Values.md b/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Values.md new file mode 100644 index 00000000..3ef31e8b --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Values.md @@ -0,0 +1,27 @@ +# ``Collections/OrderedDictionary/Values-swift.struct`` + + + + +## Topics + +### Inspecting a Values Collection + +- ``isEmpty`` +- ``count`` + +### Accessing Elements + +- ``subscript(_:)-25vfz`` +- ``elements`` +- ``withUnsafeBufferPointer(_:)`` +- ``withUnsafeMutableBufferPointer(_:)`` + +### Reordering Elements + +- ``swapAt(_:_:)-77eiy`` +- ``partition(by:)-9x0i5`` +- ``sort()`` +- ``sort(by:)`` +- ``shuffle()`` +- ``shuffle(using:)`` diff --git a/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.md b/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.md new file mode 100644 index 00000000..1db1199d --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.md @@ -0,0 +1,97 @@ +# ``Collections/OrderedDictionary`` + + + + +## Topics + +### Creating a Dictionary + +- ``init()`` +- ``init(minimumCapacity:persistent:)`` +- ``init(uniqueKeysWithValues:)-5ux9r`` +- ``init(uniqueKeysWithValues:)-88mzi`` +- ``init(uncheckedUniqueKeysWithValues:)-6gxhj`` +- ``init(uncheckedUniqueKeysWithValues:)-2j0dw`` +- ``init(uncheckedUniqueKeysWithValues:)-6gxhj`` +- ``init(uniqueKeys:values:)`` +- ``init(uncheckedUniqueKeys:values:)`` +- ``init(_:uniquingKeysWith:)-2y39b`` +- ``init(_:uniquingKeysWith:)-zhfp`` +- ``init(grouping:by:)-6mahw`` +- ``init(grouping:by:)-6m2zw`` + +### Inspecting a Dictionary + +- ``isEmpty`` +- ``count`` + +### Accessing Keys and Values + +- ``subscript(_:)`` +- ``subscript(_:default:)`` +- ``index(forKey:)`` + +### Collection Views + +- ``keys`` +- ``values-swift.property`` +- ``elements-swift.property`` + +### Updating Values + +- ``updateValue(_:forKey:)`` +- ``updateValue(_:forKey:insertingAt:)`` +- ``updateValue(forKey:default:with:)`` +- ``updateValue(forKey:insertingDefault:at:with:)`` + +### Removing Keys and Values + +- ``removeValue(forKey:)`` +- ``remove(at:)`` +- ``filter(_:)`` +- ``removeAll(where:)`` +- ``removeAll(keepingCapacity:)`` +- ``removeFirst()`` +- ``removeLast()`` +- ``removeFirst(_:)`` +- ``removeLast(_:)`` +- ``removeSubrange(_:)-512n3`` +- ``removeSubrange(_:)-8rmzx`` + +### Combining Dictionaries + +- ``merge(_:uniquingKeysWith:)-6ka2i`` +- ``merge(_:uniquingKeysWith:)-9wkad`` +- ``merging(_:uniquingKeysWith:)-4z49c`` +- ``merging(_:uniquingKeysWith:)-2e0xa`` + +### Comparing Dictionaries + +- ``==(_:_:)`` + +### Reordering Elements + +- ``swapAt(_:_:)`` +- ``reverse()`` +- ``sort()`` +- ``sort(by:)`` +- ``reverse()`` +- ``shuffle()`` +- ``shuffle(using:)`` +- ``partition(by:)`` + +### Transforming a Dictionary + +- ``mapValues(_:)`` +- ``compactMapValues(_:)`` + +### Memory Management + +- ``reserveCapacity(_:)`` + +### Supporting Types + +- ``Index`` +- ``Values-swift.struct`` +- ``Elements-swift.struct`` diff --git a/Sources/Collections/Collections.docc/Extensions/OrderedSet.UnorderedView.md b/Sources/Collections/Collections.docc/Extensions/OrderedSet.UnorderedView.md new file mode 100644 index 00000000..6e2681dc --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/OrderedSet.UnorderedView.md @@ -0,0 +1,56 @@ +# ``Collections/OrderedSet/UnorderedView`` + + + + +## Topics + +### Binary Set Operations + +- ``intersection(_:)-3q45l`` +- ``intersection(_:)-6ee3o`` + +- ``union(_:)-79uk3`` +- ``union(_:)-23dm1`` + +- ``subtracting(_:)-3ct1b`` +- ``subtracting(_:)-8e6mw`` + +- ``symmetricDifference(_:)-6aed7`` +- ``symmetricDifference(_:)-7r79p`` + +- ``formIntersection(_:)-4ow38`` +- ``formIntersection(_:)-80iht`` + +- ``formUnion(_:)-6ijb`` +- ``formUnion(_:)-8tuol`` + +- ``subtract(_:)-627eq`` +- ``subtract(_:)-4pjhu`` + +- ``formSymmetricDifference(_:)-8pkt5`` +- ``formSymmetricDifference(_:)-75z52`` + +### Binary Set Predicates + +- ``==(_:_:)`` + +- ``isSubset(of:)-2dx31`` +- ``isSubset(of:)-801lo`` +- ``isSubset(of:)-952h5`` + +- ``isSuperset(of:)-9t33p`` +- ``isSuperset(of:)-2vtig`` +- ``isSuperset(of:)-9krpz`` + +- ``isStrictSubset(of:)-9o6mg`` +- ``isStrictSubset(of:)-91par`` +- ``isStrictSubset(of:)-7n66e`` + +- ``isStrictSuperset(of:)-89ig3`` +- ``isStrictSuperset(of:)-1e0xt`` +- ``isStrictSuperset(of:)-5dsfd`` + +- ``isDisjoint(with:)-3wuso`` +- ``isDisjoint(with:)-25vmx`` +- ``isDisjoint(with:)-8nfqs`` diff --git a/Sources/Collections/Collections.docc/Extensions/OrderedSet.md b/Sources/Collections/Collections.docc/Extensions/OrderedSet.md new file mode 100644 index 00000000..a47d51f1 --- /dev/null +++ b/Sources/Collections/Collections.docc/Extensions/OrderedSet.md @@ -0,0 +1,136 @@ +# ``Collections/OrderedSet`` + + + + +## Topics + +### Creating a Set + +- ``init()`` +- ``init(_:)-5zktd`` +- ``init(_:)-3d7qr`` +- ``init(_:)-68j7`` +- ``init(_:)-8zm9d`` +- ``init(_:)-7rt2h`` +- ``init(_:)-8tli8`` +- ``init(_:)-2d3a9`` +- ``init(uncheckedUniqueElements:)`` +- ``init(minimumCapacity:persistent:)`` + +### Collection Views + +- ``UnorderedView`` +- ``unordered`` +- ``elements`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding and Updating Elements + +- ``append(_:)`` +- ``insert(_:at:)`` +- ``append(contentsOf:)`` +- ``updateOrAppend(_:)`` +- ``updateOrInsert(_:at:)`` +- ``update(_:at:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``removeAll(where:)`` +- ``remove(_:)`` +- ``remove(at:)`` +- ``removeAll(keepingCapacity:)`` +- ``removeFirst()`` +- ``removeLast()`` +- ``removeFirst(_:)`` +- ``removeLast(_:)`` +- ``removeSubrange(_:)-62u6a`` +- ``removeSubrange(_:)-2fqke`` + +### Combining Sets + +- ``intersection(_:)-4o09a`` +- ``intersection(_:)-9yzg3`` +- ``intersection(_:)-80md4`` + +- ``union(_:)-67y2h`` +- ``union(_:)-3lt5i`` +- ``union(_:)-2939h`` + +- ``subtracting(_:)-5graf`` +- ``subtracting(_:)-7kl8r`` +- ``subtracting(_:)-1gl4y`` + +- ``symmetricDifference(_:)-1810l`` +- ``symmetricDifference(_:)-8dvm6`` +- ``symmetricDifference(_:)-9huk7`` + +- ``formIntersection(_:)-43o1u`` +- ``formIntersection(_:)-2a4y4`` +- ``formIntersection(_:)-7odn2`` + +- ``formUnion(_:)-6pksr`` +- ``formUnion(_:)-3dkzw`` +- ``formUnion(_:)-59end`` + +- ``subtract(_:)-3b6nj`` +- ``subtract(_:)-9rtmd`` +- ``subtract(_:)-9wmg8`` + +- ``formSymmetricDifference(_:)-96csi`` +- ``formSymmetricDifference(_:)-2ll2z`` +- ``formSymmetricDifference(_:)-391sm`` + +### Comparing Sets + +- ``==(_:_:)`` + +- ``isSubset(of:)-ptij`` +- ``isSubset(of:)-3mw6r`` +- ``isSubset(of:)-8yb29`` +- ``isSubset(of:)-9hxl4`` + +- ``isSuperset(of:)-4rrsh`` +- ``isSuperset(of:)-2bbv8`` +- ``isSuperset(of:)-7xvog`` +- ``isSuperset(of:)-7oow7`` + +- ``isStrictSubset(of:)-8m21h`` +- ``isStrictSubset(of:)-9lv3x`` +- ``isStrictSubset(of:)-4efhn`` +- ``isStrictSubset(of:)-10abw`` + +- ``isStrictSuperset(of:)-7u97x`` +- ``isStrictSuperset(of:)-3kfwa`` +- ``isStrictSuperset(of:)-98d9s`` +- ``isStrictSuperset(of:)-5e6d5`` + +- ``isDisjoint(with:)-6vmoh`` +- ``isDisjoint(with:)-4tsmx`` +- ``isDisjoint(with:)-54iy6`` +- ``isDisjoint(with:)-7nqur`` + +### Reordering Elements + +- ``swapAt(_:_:)`` +- ``sort()`` +- ``sort(by:)`` +- ``reverse()`` +- ``shuffle()`` +- ``shuffle(using:)`` +- ``partition(by:)`` + +### Creating and Applying Differences + +- ``difference(from:)-30bkk`` +- ``applying(_:)`` + +### Memory Management + +- ``reserveCapacity(_:)`` diff --git a/Sources/DequeModule/DequeModule.docc/DequeModule.md b/Sources/DequeModule/DequeModule.docc/DequeModule.md new file mode 100644 index 00000000..0746973e --- /dev/null +++ b/Sources/DequeModule/DequeModule.docc/DequeModule.md @@ -0,0 +1,3 @@ +# ``DequeModule`` + +This module is dedicated to providing ``Deque``, a double-ended analogue of the standard `Array` type. diff --git a/Sources/DequeModule/DequeModule.docc/Extensions/Deque.md b/Sources/DequeModule/DequeModule.docc/Extensions/Deque.md new file mode 100644 index 00000000..4d3a8362 --- /dev/null +++ b/Sources/DequeModule/DequeModule.docc/Extensions/Deque.md @@ -0,0 +1,64 @@ +# ``DequeModule/Deque`` + +## Topics + +### Creating a Deque + +- ``init()`` +- ``init(_:)-8tyaw`` +- ``init(_:)-1tqf4`` +- ``init(minimumCapacity:)`` +- ``init(repeating:count:)-4v1gt`` +- ``init(unsafeUninitializedCapacity:initializingWith:)`` + +### Inspecting a Deque + +- ``count-8wcnm`` +- ``isEmpty`` + +### Manipulating Elements at the Front + +- ``first`` +- ``prepend(_:)`` +- ``prepend(contentsOf:)-96y15`` +- ``prepend(contentsOf:)-51zn6`` +- ``removeFirst()-1vdmt`` +- ``removeFirst(_:)-2vuji`` +- ``popFirst()`` +- ``prefix(_:)`` + +### Manipulating Elements at the End + +- ``last`` +- ``append(_:)-9h4m7`` +- ``append(contentsOf:)-8rqnl`` +- ``append(contentsOf:)-29aoh`` +- ``removeLast()`` +- ``removeLast(_:)`` +- ``popLast()`` +- ``suffix(_:)`` + +### Manipulating Elements Elsewhere + +- ``subscript(_:)-9nk44`` +- ``subscript(_:)-6ee8i`` +- ``subscript(_:)-1klky`` +- ``subscript(_:)-ejld`` +- ``insert(_:at:)-9hsp7`` +- ``insert(contentsOf:at:)-1d60f`` +- ``replaceSubrange(_:with:)-5rtzd`` +- ``remove(at:)-3imgi`` + +### Reordering Elements + +- ``swapAt(_:_:)-7910s`` +- ``sort()`` +- ``sort(by:)`` +- ``reverse()`` +- ``shuffle()`` +- ``shuffle(using:)`` +- ``partition(by:)-90y0t`` + +### Memory Management + +- ``reserveCapacity(_:)`` diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Elements.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Elements.md new file mode 100644 index 00000000..752f3f5c --- /dev/null +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Elements.md @@ -0,0 +1,37 @@ +# ``OrderedCollections/OrderedDictionary/Elements-swift.struct`` + +## Topics + +### Inspecting an Elements View + +- ``isEmpty`` +- ``count`` + +### Accessing Elements + +- ``subscript(_:)-4xwc2`` +- ``keys`` +- ``values`` +- ``index(forKey:)`` + +### Removing Elements + +- ``remove(at:)`` +- ``removeSubrange(_:)-5x7oo`` +- ``removeSubrange(_:)-7wdak`` +- ``removeAll(keepingCapacity:)`` +- ``removeAll(where:)`` +- ``removeFirst()`` +- ``removeFirst(_:)`` +- ``removeLast()`` +- ``removeLast(_:)`` + +### Reordering Elements + +- ``swapAt(_:_:)`` +- ``reverse()`` +- ``sort()`` +- ``sort(by:)`` +- ``partition(by:)`` +- ``shuffle()`` +- ``shuffle(using:)`` diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Values.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Values.md new file mode 100644 index 00000000..6e50c1f4 --- /dev/null +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Values.md @@ -0,0 +1,24 @@ +# ``OrderedCollections/OrderedDictionary/Values-swift.struct`` + +## Topics + +### Inspecting a Values Collection + +- ``isEmpty`` +- ``count`` + +### Accessing Elements + +- ``subscript(_:)-25vfz`` +- ``elements`` +- ``withUnsafeBufferPointer(_:)`` +- ``withUnsafeMutableBufferPointer(_:)`` + +### Reordering Elements + +- ``swapAt(_:_:)-77eiy`` +- ``partition(by:)-9x0i5`` +- ``sort()`` +- ``sort(by:)`` +- ``shuffle()`` +- ``shuffle(using:)`` diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md new file mode 100644 index 00000000..7e0845ee --- /dev/null +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md @@ -0,0 +1,94 @@ +# ``OrderedCollections/OrderedDictionary`` + +## Topics + +### Creating a Dictionary + +- ``init()`` +- ``init(minimumCapacity:persistent:)`` +- ``init(uniqueKeysWithValues:)-5ux9r`` +- ``init(uniqueKeysWithValues:)-88mzi`` +- ``init(uncheckedUniqueKeysWithValues:)-6gxhj`` +- ``init(uncheckedUniqueKeysWithValues:)-2j0dw`` +- ``init(uncheckedUniqueKeysWithValues:)-6gxhj`` +- ``init(uniqueKeys:values:)`` +- ``init(uncheckedUniqueKeys:values:)`` +- ``init(_:uniquingKeysWith:)-2y39b`` +- ``init(_:uniquingKeysWith:)-zhfp`` +- ``init(grouping:by:)-6mahw`` +- ``init(grouping:by:)-6m2zw`` + +### Inspecting a Dictionary + +- ``isEmpty`` +- ``count`` + +### Accessing Keys and Values + +- ``subscript(_:)`` +- ``subscript(_:default:)`` +- ``index(forKey:)`` + +### Collection Views + +- ``keys`` +- ``values-swift.property`` +- ``elements-swift.property`` + +### Updating Values + +- ``updateValue(_:forKey:)`` +- ``updateValue(_:forKey:insertingAt:)`` +- ``updateValue(forKey:default:with:)`` +- ``updateValue(forKey:insertingDefault:at:with:)`` + +### Removing Keys and Values + +- ``removeValue(forKey:)`` +- ``remove(at:)`` +- ``filter(_:)`` +- ``removeAll(where:)`` +- ``removeAll(keepingCapacity:)`` +- ``removeFirst()`` +- ``removeLast()`` +- ``removeFirst(_:)`` +- ``removeLast(_:)`` +- ``removeSubrange(_:)-512n3`` +- ``removeSubrange(_:)-8rmzx`` + +### Combining Dictionaries + +- ``merge(_:uniquingKeysWith:)-6ka2i`` +- ``merge(_:uniquingKeysWith:)-9wkad`` +- ``merging(_:uniquingKeysWith:)-4z49c`` +- ``merging(_:uniquingKeysWith:)-2e0xa`` + +### Comparing Dictionaries + +- ``==(_:_:)`` + +### Reordering Elements + +- ``swapAt(_:_:)`` +- ``reverse()`` +- ``sort()`` +- ``sort(by:)`` +- ``reverse()`` +- ``shuffle()`` +- ``shuffle(using:)`` +- ``partition(by:)`` + +### Transforming a Dictionary + +- ``mapValues(_:)`` +- ``compactMapValues(_:)`` + +### Memory Management + +- ``reserveCapacity(_:)`` + +### Supporting Types + +- ``Index`` +- ``Values-swift.struct`` +- ``Elements-swift.struct`` diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md new file mode 100644 index 00000000..ebc2c889 --- /dev/null +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md @@ -0,0 +1,53 @@ +# ``OrderedCollections/OrderedSet/UnorderedView`` + +## Topics + +### Binary Set Operations + +- ``intersection(_:)-3q45l`` +- ``intersection(_:)-6ee3o`` + +- ``union(_:)-79uk3`` +- ``union(_:)-23dm1`` + +- ``subtracting(_:)-3ct1b`` +- ``subtracting(_:)-8e6mw`` + +- ``symmetricDifference(_:)-6aed7`` +- ``symmetricDifference(_:)-7r79p`` + +- ``formIntersection(_:)-4ow38`` +- ``formIntersection(_:)-80iht`` + +- ``formUnion(_:)-6ijb`` +- ``formUnion(_:)-8tuol`` + +- ``subtract(_:)-627eq`` +- ``subtract(_:)-4pjhu`` + +- ``formSymmetricDifference(_:)-8pkt5`` +- ``formSymmetricDifference(_:)-75z52`` + +### Binary Set Predicates + +- ``==(_:_:)`` + +- ``isSubset(of:)-2dx31`` +- ``isSubset(of:)-801lo`` +- ``isSubset(of:)-952h5`` + +- ``isSuperset(of:)-9t33p`` +- ``isSuperset(of:)-2vtig`` +- ``isSuperset(of:)-9krpz`` + +- ``isStrictSubset(of:)-9o6mg`` +- ``isStrictSubset(of:)-91par`` +- ``isStrictSubset(of:)-7n66e`` + +- ``isStrictSuperset(of:)-89ig3`` +- ``isStrictSuperset(of:)-1e0xt`` +- ``isStrictSuperset(of:)-5dsfd`` + +- ``isDisjoint(with:)-3wuso`` +- ``isDisjoint(with:)-25vmx`` +- ``isDisjoint(with:)-8nfqs`` diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md new file mode 100644 index 00000000..eac28040 --- /dev/null +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md @@ -0,0 +1,133 @@ +# ``OrderedCollections/OrderedSet`` + +## Topics + +### Creating a Set + +- ``init()`` +- ``init(_:)-5zktd`` +- ``init(_:)-3d7qr`` +- ``init(_:)-68j7`` +- ``init(_:)-8zm9d`` +- ``init(_:)-7rt2h`` +- ``init(_:)-8tli8`` +- ``init(_:)-2d3a9`` +- ``init(uncheckedUniqueElements:)`` +- ``init(minimumCapacity:persistent:)`` + +### Collection Views + +- ``UnorderedView`` +- ``unordered`` +- ``elements`` + +### Finding Elements + +- ``contains(_:)`` +- ``firstIndex(of:)`` +- ``lastIndex(of:)`` + +### Adding and Updating Elements + +- ``append(_:)`` +- ``insert(_:at:)`` +- ``append(contentsOf:)`` +- ``updateOrAppend(_:)`` +- ``updateOrInsert(_:at:)`` +- ``update(_:at:)`` + +### Removing Elements + +- ``filter(_:)`` +- ``removeAll(where:)`` +- ``remove(_:)`` +- ``remove(at:)`` +- ``removeAll(keepingCapacity:)`` +- ``removeFirst()`` +- ``removeLast()`` +- ``removeFirst(_:)`` +- ``removeLast(_:)`` +- ``removeSubrange(_:)-62u6a`` +- ``removeSubrange(_:)-2fqke`` + +### Combining Sets + +- ``intersection(_:)-4o09a`` +- ``intersection(_:)-9yzg3`` +- ``intersection(_:)-80md4`` + +- ``union(_:)-67y2h`` +- ``union(_:)-3lt5i`` +- ``union(_:)-2939h`` + +- ``subtracting(_:)-5graf`` +- ``subtracting(_:)-7kl8r`` +- ``subtracting(_:)-1gl4y`` + +- ``symmetricDifference(_:)-1810l`` +- ``symmetricDifference(_:)-8dvm6`` +- ``symmetricDifference(_:)-9huk7`` + +- ``formIntersection(_:)-43o1u`` +- ``formIntersection(_:)-2a4y4`` +- ``formIntersection(_:)-7odn2`` + +- ``formUnion(_:)-6pksr`` +- ``formUnion(_:)-3dkzw`` +- ``formUnion(_:)-59end`` + +- ``subtract(_:)-3b6nj`` +- ``subtract(_:)-9rtmd`` +- ``subtract(_:)-9wmg8`` + +- ``formSymmetricDifference(_:)-96csi`` +- ``formSymmetricDifference(_:)-2ll2z`` +- ``formSymmetricDifference(_:)-391sm`` + +### Comparing Sets + +- ``==(_:_:)`` + +- ``isSubset(of:)-ptij`` +- ``isSubset(of:)-3mw6r`` +- ``isSubset(of:)-8yb29`` +- ``isSubset(of:)-9hxl4`` + +- ``isSuperset(of:)-4rrsh`` +- ``isSuperset(of:)-2bbv8`` +- ``isSuperset(of:)-7xvog`` +- ``isSuperset(of:)-7oow7`` + +- ``isStrictSubset(of:)-8m21h`` +- ``isStrictSubset(of:)-9lv3x`` +- ``isStrictSubset(of:)-4efhn`` +- ``isStrictSubset(of:)-10abw`` + +- ``isStrictSuperset(of:)-7u97x`` +- ``isStrictSuperset(of:)-3kfwa`` +- ``isStrictSuperset(of:)-98d9s`` +- ``isStrictSuperset(of:)-5e6d5`` + +- ``isDisjoint(with:)-6vmoh`` +- ``isDisjoint(with:)-4tsmx`` +- ``isDisjoint(with:)-54iy6`` +- ``isDisjoint(with:)-7nqur`` + +### Reordering Elements + +- ``swapAt(_:_:)`` +- ``sort()`` +- ``sort(by:)`` +- ``reverse()`` +- ``shuffle()`` +- ``shuffle(using:)`` +- ``partition(by:)`` + +### Creating and Applying Differences + +- ``difference(from:)-30bkk`` +- ``applying(_:)`` + +### Memory Management + +- ``reserveCapacity(_:)`` diff --git a/Sources/OrderedCollections/OrderedCollections.docc/OrderedCollections.md b/Sources/OrderedCollections/OrderedCollections.docc/OrderedCollections.md new file mode 100644 index 00000000..dcc7288a --- /dev/null +++ b/Sources/OrderedCollections/OrderedCollections.docc/OrderedCollections.md @@ -0,0 +1,10 @@ +# ``OrderedCollections`` + +The `OrderedCollections` module provides hashed collection types that work like the standard `Set` and `Dictionary`, but maintain their elements in a particular user-specified order. + +## Topics + +### Structures + +- ``OrderedSet`` +- ``OrderedDictionary`` diff --git a/Utils/generate-docs.sh b/Utils/generate-docs.sh new file mode 100755 index 00000000..86506af1 --- /dev/null +++ b/Utils/generate-docs.sh @@ -0,0 +1,92 @@ +#!/bin/sh +#===---------------------------------------------------------------------- +# +# This source file is part of the Swift Collections open source project +# +# Copyright (c) 2022 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 +# +#===---------------------------------------------------------------------- + +set -eu + +shopt -s nullglob +cd "$(dirname $0)/.." + +if [ "$(uname)" = "Darwin" ]; then + swift="xcrun swift" + export DOCC_HTML_DIR="$(dirname $(xcrun --find docc))/../share/docc/render" +else + swift="swift" +fi + +build_dir="$(mktemp -d "/tmp/$(basename $0).XXXXX")" +echo "Build directory: $build_dir" + +output_dir_base=/tmp/foo + +rm -rf "$output_dir_base" + +components="DequeModule OrderedCollections" + +if [ $# -eq 0 ]; then + targets="Collections $components" +else + targets="$@" +fi + +for target in $targets; do + if [ "$target" = "Collections" ]; then + # Update extensions under Collections.docc + rm -rf Sources/Collections/Collections.docc/Extensions/*.md + for component in $components; do + for file in Sources/"$component"/"$component".docc/Extensions/*.md; do + output="Sources/Collections/Collections.docc/Extensions/$(basename $file)" + blurb="" + sed 's?^# ``[^/]*/\(.*\)``?# ``Collections/\1``\n\n'"$blurb"'\n?' "$file" > "$output" + done + done + fi + + mkdir -p "$build_dir/$target/build" + mkdir -p "$build_dir/$target/symbol-graphs" + mkdir -p "$build_dir/$target/docc" + $swift build --target "$target" \ + --build-path "$build_dir/$target/build" \ + -Xswiftc -emit-symbol-graph \ + -Xswiftc -emit-symbol-graph-dir \ + -Xswiftc "$build_dir/$target/symbol-graphs" + + # Prevent DocC from getting confused by too much data :-/ + cp \ + "$build_dir/$target/symbol-graphs/$target.symbols.json" \ + "$build_dir/$target/docc" + extrafile="$build_dir/$target/symbol-graphs/${target}@Swift.symbols.json" + if [ -r "$extrafile" ]; then + cp "$extrafile" "$build_dir/$target/docc" + fi + + mkdir -p "$output_dir_base/$target" + xcrun docc convert \ + --analyze \ + --fallback-display-name "$target" \ + --fallback-bundle-identifier "org.swift.swift-collections.$target" \ + --fallback-bundle-version 1.1.0 \ + --default-code-listing-language swift \ + --additional-symbol-graph-dir "$build_dir/$target/docc" \ + --transform-for-static-hosting \ + --output-path "$output_dir_base/$target" \ + --hosting-base-path "/swift-collections/$target" \ + "Sources/$target/$target.docc" +done + +if [ $# -eq 1 ]; then + module="$1" + xcrun docc preview "Sources/$module/$module.docc" \ + --fallback-display-name "Swift Collections" \ + --fallback-bundle-identifier "org.swift.swift-collections.$module" \ + --fallback-bundle-version 1.1.0 \ + --additional-symbol-graph-dir "$build_dir/$module/docc" +fi From 08b38129b9d2b584d7447d79ce7a00867d601410 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 6 Dec 2022 18:41:29 -0800 Subject: [PATCH 002/113] [OrderedSet] Fix outdated documentation --- Sources/OrderedCollections/OrderedSet/OrderedSet.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index 83ca98a3..ef0e0ab9 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -66,10 +66,11 @@ /// it provides its own variants for insertion that are more explicit about /// where in the collection new elements gets inserted: /// -/// func insert(_ item: Element, at index: Int) -> (inserted: Bool, index: Int) /// func append(_ item: Element) -> (inserted: Bool, index: Int) -/// func update(at index: Int, with item: Element) -> Element +/// func insert(_ item: Element, at index: Int) -> (inserted: Bool, index: Int) /// func updateOrAppend(_ item: Element) -> Element? +/// func updateOrInsert(_ item: Element, at index: Int) -> (originalMember: Element?, index: Int) +/// func update(_ item: Element, at index: Int) -> Element /// /// Additionally,`OrderedSet` has an order-sensitive definition of equality (see /// above) that is incompatible with `SetAlgebra`'s documented semantic From a874de5f7f7c95d1a439169f10a4b0289a936627 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 6 Dec 2022 19:00:59 -0800 Subject: [PATCH 003/113] [OrderedCollections] Refresh some docs with DocC links --- ...Dictionary+Partial MutableCollection.swift | 2 +- .../OrderedDictionary/OrderedDictionary.swift | 66 +++++++------------ .../OrderedSet/OrderedSet.swift | 62 +++++++---------- 3 files changed, 49 insertions(+), 81 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift index f43d6993..35970a7f 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift @@ -132,7 +132,7 @@ extension OrderedDictionary { /// Use the `shuffle()` method to randomly reorder the elements of an ordered /// dictionary. /// - /// This method is equivalent to calling `shuffle(using:)`, passing in the + /// This method is equivalent to calling ``shuffle(using:)``, passing in the /// system's default random generator. /// /// - Complexity: O(*n*), where *n* is the length of the collection. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index f32222d3..34e0e3ba 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -93,13 +93,14 @@ /// /// (This isn't currently available on the regular `Dictionary`.) /// -/// The `Dictionary` type's original `updateValue(_:forKey:)` method is also -/// available, and so is `index(forKey:)`, grouping/uniquing initializers -/// (`init(uniqueKeysWithValues:)`, `init(_:uniquingKeysWith:)`, -/// `init(grouping:by:)`), methods for merging one dictionary with another -/// (`merge`, `merging`), filtering dictionary entries (`filter(_:)`), -/// transforming values (`mapValues(_:)`), and a combination of these two -/// (`compactMapValues(_:)`). +/// The `Dictionary` type's original ``updateValue(_:forKey:)`` method is also +/// available, and so is ``index(forKey:)``, grouping/uniquing initializers +/// (``init(uniqueKeysWithValues:)-5ux9r``, ``init(_:uniquingKeysWith:)-2y39b``, +/// ``init(grouping:by:)-6mahw``), methods for merging one dictionary with +/// another (``merge(_:uniquingKeysWith:)-6ka2i``, +/// ``merging(_:uniquingKeysWith:)-4z49c``), filtering dictionary entries +/// (``filter(_:)``), transforming values (``mapValues(_:)``), +/// and a combination of these two (``compactMapValues(_:)``). /// /// ### Sequence and Collection Operations /// @@ -107,60 +108,43 @@ /// beginning of the collection. However, to avoid ambiguity between key-based /// and indexing subscripts, `OrderedDictionary` doesn't directly conform to /// `Collection`. Instead, it only conforms to `Sequence`, and provides a -/// random-access collection view over its key-value pairs: +/// random-access collection view over its key-value pairs, called +/// ``elements-swift.property``: /// /// responses[0] // `nil` (key-based subscript) /// responses.elements[0] // `(200, "OK")` (index-based subscript) /// /// Because ordered dictionaries need to maintain unique keys, neither -/// `OrderedDictionary` nor its `elements` view can conform to the full -/// `MutableCollection` or `RangeReplaceableCollection` protocols. However, they -/// are able to partially implement requirements: they support mutations -/// that merely change the order of elements, or just remove a subset of -/// existing members: +/// `OrderedDictionary` nor its ``elements-swift.property`` view can conform to +/// the full `MutableCollection` or `RangeReplaceableCollection` protocols. +/// However, they are able to partially implement requirements: they support +/// mutations that merely change the order of elements, or just remove a subset +/// of existing members. /// -/// // Permutation operations from MutableCollection: -/// func swapAt(_ i: Int, _ j: Int) -/// func partition(by predicate: (Element) throws -> Bool) -> rethrows Int -/// func sort() where Element: Comparable -/// func sort(by predicate: (Element, Element) throws -> Bool) rethrows -/// func shuffle() -/// func shuffle(using generator: inout T) -/// -/// // Removal operations from RangeReplaceableCollection: -/// func removeAll(keepingCapacity: Bool = false) -/// func remove(at index: Int) -> Element -/// func removeSubrange(_ bounds: Range) -/// func removeLast() -> Element -/// func removeLast(_ n: Int) -/// func removeFirst() -> Element -/// func removeFirst(_ n: Int) -/// func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows -/// -/// `OrderedDictionary` also implements `reserveCapacity(_)` from +/// `OrderedDictionary` also implements ``reserveCapacity(_:)`` from /// `RangeReplaceableCollection`, to allow for efficient insertion of a known /// number of elements. (However, unlike `Array` and `Dictionary`, /// `OrderedDictionary` does not provide a `capacity` property.) /// /// ### Keys and Values Views /// -/// Like the standard `Dictionary`, `OrderedDictionary` provides `keys` and -/// `values` properties that provide lightweight views into the corresponding -/// parts of the dictionary. +/// Like the standard `Dictionary`, `OrderedDictionary` provides ``keys`` and +/// ``values-swift.property`` properties that provide lightweight views into +/// the corresponding parts of the dictionary. /// -/// The `keys` collection is of type `OrderedSet`, containing all the keys -/// in the original dictionary. +/// The ``keys`` collection is of type `OrderedSet`, containing all the +/// keys in the original dictionary. /// /// let d: OrderedDictionary = [2: "two", 1: "one", 0: "zero"] /// d.keys // [2, 1, 0] as OrderedSet /// -/// The `keys` property is read-only, so you cannot mutate the dictionary +/// The ``keys`` property is read-only, so you cannot mutate the dictionary /// through it. However, it returns an ordinary ordered set value, which can be /// copied out and then mutated if desired. (Such mutations won't affect the /// original dictionary value.) /// -/// The `values` collection is a mutable random-access collection of the values -/// in the dictionary: +/// The ``values-swift.property`` property returns a mutable random-access +/// collection of the values in the dictionary: /// /// d.values // "two", "one", "zero" /// d.values[2] = "nada" @@ -169,7 +153,7 @@ /// // `d` is now [2: "nada", 1: "one", 0: "two"] /// /// Both views store their contents in regular `Array` values, accessible -/// through their `elements` property. +/// through their own `elements` property. /// /// ## Performance /// diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index ef0e0ab9..5f0fbf70 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -44,9 +44,9 @@ /// # Set Operations /// /// `OrderedSet` implements most, but not all, `SetAlgebra` requirements. In -/// particular, it supports the membership test `contains(_:)` as well as all -/// high-level set operations such as `union(_:)`, `intersection(_:)` or -/// `isSubset(of:)`. +/// particular, it supports the membership test ``contains(_:)`` as well as all +/// high-level set operations such as ``union(_:)-67y2h``, +/// ``intersection(_:)-4o09a`` or ``isSubset(of:)-ptij``. /// /// buildingMaterials.contains("glass") // false /// buildingMaterials.intersection(["brick", "straw"]) // ["straw", "brick"] @@ -56,15 +56,15 @@ /// above, the ordering of elements in the result is guaranteed to match their /// order in the first input set, `buildingMaterials`. /// -/// On the other hand, predicates such as `isSubset(of:)` tend to ignore element -/// ordering: +/// On the other hand, predicates such as ``isSubset(of:)-ptij`` tend to ignore +/// element ordering: /// /// let moreMaterials: OrderedSet = ["bricks", "glass", "sticks", "straw"] /// buildingMaterials.isSubset(of: moreMaterials) // true /// -/// However, `OrderedSet` does not implement `insert(_:)` nor `update(with:)` -- -/// it provides its own variants for insertion that are more explicit about -/// where in the collection new elements gets inserted: +/// `OrderedSet` does not implement `insert(_:)` nor `update(with:)` from +/// `SetAlgebra` -- it provides its own variants for insertion that are more +/// explicit about where in the collection new elements gets inserted: /// /// func append(_ item: Element) -> (inserted: Bool, index: Int) /// func insert(_ item: Element, at index: Int) -> (inserted: Bool, index: Int) @@ -82,8 +82,9 @@ /// For cases where `SetAlgebra` conformance is desired (such as when passing an /// ordered set to a function that is generic over that protocol), `OrderedSet` /// provides an efficient *unordered view* of its elements that conforms to -/// `SetAlgebra`. The unordered view implements the same concept of equality as -/// the standard `Set`, ignoring element ordering. +/// `SetAlgebra`. This view is accessed through the ``unordered`` property, and +/// it implements the same concept of equality as the standard `Set`, ignoring +/// element ordering. /// /// var a: OrderedSet = [0, 1, 2, 3] /// let b: OrderedSet = [3, 2, 1, 0] @@ -127,34 +128,17 @@ /// Because `OrderedSet` needs to keep its members unique, it cannot conform to /// the full `MutableCollection` or `RangeReplaceableCollection` protocols. /// Operations such as `MutableCollection`'s subscript setter or -/// `RangeReplaceableCollection`'s `replaceSubrange` assume the ability to -/// insert/replace arbitrary elements in the collection, but allowing that could -/// lead to duplicate values. +/// `RangeReplaceableCollection`'s `replaceSubrange` method assume the ability +/// to insert/replace arbitrary elements in the collection, but allowing that +/// could lead to duplicate values. /// /// However, `OrderedSet` is able to partially implement these two protocols; -/// namely, there is no issue with mutation operations that merely change the -/// order of elements, or just remove some subset of existing members: +/// namely, is supports mutation operations that merely change the +/// order of elements (such as ``sort()`` or ``swapAt(_:_:)``, or just remove +/// some subset of existing members (such as ``remove(at:)`` or +/// ``removeAll(where:)``). /// -/// // Permutation operations from MutableCollection: -/// func swapAt(_ i: Int, _ j: Int) -/// func partition(by predicate: (Element) throws -> Bool) -> rethrows Int -/// func sort() where Element: Comparable -/// func sort(by predicate: (Element, Element) throws -> Bool) rethrows -/// func shuffle() -/// func shuffle(using generator: inout T) -/// func reverse() -/// -/// // Removal operations from RangeReplaceableCollection: -/// func removeAll(keepingCapacity: Bool = false) -/// func remove(at index: Int) -> Element -/// func removeSubrange(_ bounds: Range) -/// func removeLast() -> Element -/// func removeLast(_ n: Int) -/// func removeFirst() -> Element -/// func removeFirst(_ n: Int) -/// func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows -/// -/// `OrderedSet` also implements `reserveCapacity(_)` from +/// `OrderedSet` also implements ``reserveCapacity(_:)`` from /// `RangeReplaceableCollection`, to allow for efficient insertion of a known /// number of elements. (However, unlike `Array` and `Set`, `OrderedSet` does /// not provide a `capacity` property.) @@ -165,7 +149,7 @@ /// that only takes an array value or (or something that's generic over /// `RangeReplaceableCollection` or `MutableCollection`), then the best option /// is usually to directly extract the members of the `OrderedSet` as an `Array` -/// value using its `elements` property. `OrderedSet` uses a standard array +/// value using its ``elements`` property. `OrderedSet` uses a standard array /// value for element storage, so extracting the array value has minimal /// overhead. /// @@ -176,14 +160,14 @@ /// pickyFunction(set.elements) // OK /// /// It is also possible to mutate the set by updating the value of the -/// `elements` property. This guarantees that direct mutations happen in place +/// ``elements`` property. This guarantees that direct mutations happen in place /// when possible (i.e., without spurious copy-on-write copies). /// /// However, the set needs to ensure the uniqueness of its members, so every -/// update to `elements` includes a postprocessing step to detect and remove +/// update to ``elements`` includes a postprocessing step to detect and remove /// duplicates over the entire array. This can be slower than doing the /// equivalent updates with direct `OrderedSet` operations, so updating -/// `elements` is best used in cases where direct implementations aren't +/// ``elements`` is best used in cases where direct implementations aren't /// available -- for example, when you need to call a `MutableCollection` /// algorithm that isn't directly implemented by `OrderedSet` itself. /// From 847b548a03c8db491150820e0b97cdf286b4a3fe Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 6 Dec 2022 19:39:08 -0800 Subject: [PATCH 004/113] [Manifest] Exclude documentation bundles from 5.3 manifest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We should have a separate Package@swift-5.5.swift manifest that removes these exclusions; however, that requires some additional validation testing — let’s do that later. --- Package.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Package.swift b/Package.swift index 52ecce53..04ea5766 100644 --- a/Package.swift +++ b/Package.swift @@ -63,7 +63,7 @@ let package = Package( "OrderedCollections", ], path: "Sources/Collections", - exclude: ["CMakeLists.txt"], + exclude: ["CMakeLists.txt", "Collections.docc"], swiftSettings: settings), // Testing support module @@ -85,7 +85,7 @@ let package = Package( // Deque .target( name: "DequeModule", - exclude: ["CMakeLists.txt"], + exclude: ["CMakeLists.txt", "DequeModule.docc"], swiftSettings: settings), .testTarget( name: "DequeTests", @@ -95,7 +95,7 @@ let package = Package( // OrderedSet, OrderedDictionary .target( name: "OrderedCollections", - exclude: ["CMakeLists.txt"], + exclude: ["CMakeLists.txt", "OrderedCollections.docc"], swiftSettings: settings), .testTarget( name: "OrderedCollectionsTests", From e14a0359ca4aeee4e9ceb5339592a1dbce9a7289 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 6 Dec 2022 21:02:09 -0800 Subject: [PATCH 005/113] Add a configuration file for the Swift Package Index --- .spi.yml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .spi.yml diff --git a/.spi.yml b/.spi.yml new file mode 100644 index 00000000..adcda23e --- /dev/null +++ b/.spi.yml @@ -0,0 +1,4 @@ +version: 1 +builder: + configs: + - documentation_targets: [Collections, DequeModule, OrderedCollections] From b4c1070741a119654864b736268c3f03f6799a1b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 6 Dec 2022 21:02:34 -0800 Subject: [PATCH 006/113] [Docs] Update high-level Collections docs --- .../Collections.docc/Collections.md | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/Sources/Collections/Collections.docc/Collections.md b/Sources/Collections/Collections.docc/Collections.md index 7a0322c5..1d2cc013 100644 --- a/Sources/Collections/Collections.docc/Collections.md +++ b/Sources/Collections/Collections.docc/Collections.md @@ -2,9 +2,23 @@ **Swift Collections** is an open-source package of data structure implementations for the Swift programming language. -This package provides separate modules for each group of data structures it implements. For instance, if you only need a double-ended queue type, you can pull in only that by importing `DequeModule`. +The package currently provides the following implementations: -The top-level module `Collections` imports and reexports each of these smaller packages. Importing this module is a useful shortcut if you want to import all data structures, or if you don't care about bringing in more code than you need. +- ``Deque``, a double-ended queue backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. + +- ``OrderedSet``, a variant of the standard `Set` where the order of items is well-defined and items can be arbitrarily reordered. Uses a `ContiguousArray` as its backing store, augmented by a separate hash table of bit packed offsets into it. + +- ``OrderedDictionary``, an ordered variant of the standard `Dictionary`, providing similar benefits. + +## Modules + +This package provides separate products for each group of data structures it implements: + +- ``Collections``. This is an umbrella module that exports every other public module in the package. +- ``DequeModule``. Defines ``Deque``. +- ``OrderedCollections``. Defines the ordered collection types ``OrderedSet`` and ``OrderedDictionary``. + +If you aren't constrained by code size limitations, then importing ``Collections`` is the simplest way to start using the package. ```swift import Collections @@ -21,7 +35,6 @@ people.contains("Rebecca") // true - [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/) - [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72) - ## Topics ### Deque Module From 089666b32ba82c06a166e072ebcdf988108b66b7 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 7 Dec 2022 14:25:12 -0800 Subject: [PATCH 007/113] Add a separate package manifest for Swift 5.5+ --- Package@swift-5.5.swift | 100 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 Package@swift-5.5.swift diff --git a/Package@swift-5.5.swift b/Package@swift-5.5.swift new file mode 100644 index 00000000..7deefc6b --- /dev/null +++ b/Package@swift-5.5.swift @@ -0,0 +1,100 @@ +// swift-tools-version:5.5 +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 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 +// +//===----------------------------------------------------------------------===// + +import PackageDescription + +// This package recognizes the conditional compilation flags listed below. +// To use enable them, uncomment the corresponding lines or define them +// from the package manager command line: +// +// swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS +var settings: [SwiftSetting] = [ + + // Enables internal consistency checks at the end of initializers and + // mutating operations. This can have very significant overhead, so enabling + // this setting invalidates all documented performance guarantees. + // + // This is mostly useful while debugging an issue with the implementation of + // the hash table itself. This setting should never be enabled in production + // code. +// .define("COLLECTIONS_INTERNAL_CHECKS"), + + // Hashing collections provided by this package usually seed their hash + // function with the address of the memory location of their storage, + // to prevent some common hash table merge/copy operations from regressing to + // quadratic behavior. This setting turns off this mechanism, seeding + // the hash function with the table's size instead. + // + // When used in conjunction with the SWIFT_DETERMINISTIC_HASHING environment + // variable, this enables reproducible hashing behavior. + // + // This is mostly useful while debugging an issue with the implementation of + // the hash table itself. This setting should never be enabled in production + // code. +// .define("COLLECTIONS_DETERMINISTIC_HASHING"), +] + +let package = Package( + name: "swift-collections", + products: [ + .library(name: "Collections", targets: ["Collections"]), + .library(name: "DequeModule", targets: ["DequeModule"]), + .library(name: "OrderedCollections", targets: ["OrderedCollections"]), + ], + targets: [ + .target( + name: "Collections", + dependencies: [ + "DequeModule", + "OrderedCollections", + ], + path: "Sources/Collections", + exclude: ["CMakeLists.txt"], + swiftSettings: settings), + + // Testing support module + .target( + name: "_CollectionsTestSupport", + dependencies: [], + swiftSettings: settings, + linkerSettings: [ + .linkedFramework( + "XCTest", + .when(platforms: [.macOS, .iOS, .watchOS, .tvOS])), + ] + ), + .testTarget( + name: "CollectionsTestSupportTests", + dependencies: ["_CollectionsTestSupport"], + swiftSettings: settings), + + // Deque + .target( + name: "DequeModule", + exclude: ["CMakeLists.txt"], + swiftSettings: settings), + .testTarget( + name: "DequeTests", + dependencies: ["DequeModule", "_CollectionsTestSupport"], + swiftSettings: settings), + + // OrderedSet, OrderedDictionary + .target( + name: "OrderedCollections", + exclude: ["CMakeLists.txt"], + swiftSettings: settings), + .testTarget( + name: "OrderedCollectionsTests", + dependencies: ["OrderedCollections", "_CollectionsTestSupport"], + swiftSettings: settings), + ] +) From 6cb03fee98a3065f938c269fc2c5340a8e262f9f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:30:39 -0800 Subject: [PATCH 008/113] [BitCollections] Update file headers --- .../BitArray/BitArray+BitwiseOperations.swift | 2 +- .../BitArray+ChunkedBitsIterators.swift | 2 +- .../BitArray/BitArray+Codable.swift | 2 +- .../BitArray/BitArray+Collection.swift | 2 +- .../BitCollections/BitArray/BitArray+Copy.swift | 2 +- .../BitArray+CustomDebugStringConvertible.swift | 17 ----------------- .../BitArray/BitArray+CustomReflectable.swift | 2 +- .../BitArray/BitArray+Equatable.swift | 2 +- .../BitArray+ExpressibleByArrayLiteral.swift | 2 +- .../BitArray/BitArray+Extras.swift | 2 +- .../BitCollections/BitArray/BitArray+Fill.swift | 2 +- .../BitArray/BitArray+Hashable.swift | 2 +- .../BitArray/BitArray+Initializers.swift | 2 +- .../BitArray/BitArray+Invariants.swift | 2 +- .../BitArray+RangeReplaceableCollection.swift | 4 ++-- .../BitArray/BitArray+Testing.swift | 2 +- .../BitArray/BitArray._UnsafeHandle.swift | 2 +- Sources/BitCollections/BitArray/BitArray.swift | 2 +- 18 files changed, 18 insertions(+), 35 deletions(-) delete mode 100644 Sources/BitCollections/BitArray/BitArray+CustomDebugStringConvertible.swift diff --git a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift index 770a9bbc..b697032b 100644 --- a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift +++ b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift index 2f50b921..21b44484 100644 --- a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift +++ b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+Codable.swift b/Sources/BitCollections/BitArray/BitArray+Codable.swift index f8a0a8b5..1d2c7857 100644 --- a/Sources/BitCollections/BitArray/BitArray+Codable.swift +++ b/Sources/BitCollections/BitArray/BitArray+Codable.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022-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 diff --git a/Sources/BitCollections/BitArray/BitArray+Collection.swift b/Sources/BitCollections/BitArray/BitArray+Collection.swift index 728909c3..0c7385a8 100644 --- a/Sources/BitCollections/BitArray/BitArray+Collection.swift +++ b/Sources/BitCollections/BitArray/BitArray+Collection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+Copy.swift b/Sources/BitCollections/BitArray/BitArray+Copy.swift index 1f339c33..0da47fa9 100644 --- a/Sources/BitCollections/BitArray/BitArray+Copy.swift +++ b/Sources/BitCollections/BitArray/BitArray+Copy.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+CustomDebugStringConvertible.swift b/Sources/BitCollections/BitArray/BitArray+CustomDebugStringConvertible.swift deleted file mode 100644 index f8502d2e..00000000 --- a/Sources/BitCollections/BitArray/BitArray+CustomDebugStringConvertible.swift +++ /dev/null @@ -1,17 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2022 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 -// -//===----------------------------------------------------------------------===// - -extension BitArray: CustomDebugStringConvertible { - /// A textual representation of this instance, suitable for debugging. - public var debugDescription: String { - "BitArray(\(_bitString))" - } -} diff --git a/Sources/BitCollections/BitArray/BitArray+CustomReflectable.swift b/Sources/BitCollections/BitArray/BitArray+CustomReflectable.swift index a61d3b77..89cbe6e5 100644 --- a/Sources/BitCollections/BitArray/BitArray+CustomReflectable.swift +++ b/Sources/BitCollections/BitArray/BitArray+CustomReflectable.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022-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 diff --git a/Sources/BitCollections/BitArray/BitArray+Equatable.swift b/Sources/BitCollections/BitArray/BitArray+Equatable.swift index d7926a9e..5741ce6b 100644 --- a/Sources/BitCollections/BitArray/BitArray+Equatable.swift +++ b/Sources/BitCollections/BitArray/BitArray+Equatable.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift b/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift index e10c0e3b..0271097b 100644 --- a/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift +++ b/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+Extras.swift b/Sources/BitCollections/BitArray/BitArray+Extras.swift index a6554509..d0ecd69a 100644 --- a/Sources/BitCollections/BitArray/BitArray+Extras.swift +++ b/Sources/BitCollections/BitArray/BitArray+Extras.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022-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 diff --git a/Sources/BitCollections/BitArray/BitArray+Fill.swift b/Sources/BitCollections/BitArray/BitArray+Fill.swift index bf42c338..fd96dd56 100644 --- a/Sources/BitCollections/BitArray/BitArray+Fill.swift +++ b/Sources/BitCollections/BitArray/BitArray+Fill.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+Hashable.swift b/Sources/BitCollections/BitArray/BitArray+Hashable.swift index d8ff3da8..2e5726ed 100644 --- a/Sources/BitCollections/BitArray/BitArray+Hashable.swift +++ b/Sources/BitCollections/BitArray/BitArray+Hashable.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+Initializers.swift b/Sources/BitCollections/BitArray/BitArray+Initializers.swift index 155740c7..e9be95a4 100644 --- a/Sources/BitCollections/BitArray/BitArray+Initializers.swift +++ b/Sources/BitCollections/BitArray/BitArray+Initializers.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+Invariants.swift b/Sources/BitCollections/BitArray/BitArray+Invariants.swift index d194ea0b..d7f791e6 100644 --- a/Sources/BitCollections/BitArray/BitArray+Invariants.swift +++ b/Sources/BitCollections/BitArray/BitArray+Invariants.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift index 5ab87d7d..755210cf 100644 --- a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift +++ b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 @@ -29,7 +29,7 @@ extension BitArray { public init() { self.init(_storage: [], count: 0) } - + /// Creates a new bit array containing the specified number of a single, /// repeated Boolean value. /// diff --git a/Sources/BitCollections/BitArray/BitArray+Testing.swift b/Sources/BitCollections/BitArray/BitArray+Testing.swift index 3269ce30..54afb107 100644 --- a/Sources/BitCollections/BitArray/BitArray+Testing.swift +++ b/Sources/BitCollections/BitArray/BitArray+Testing.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift index ba69f1e7..7c4157f7 100644 --- a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift +++ b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 diff --git a/Sources/BitCollections/BitArray/BitArray.swift b/Sources/BitCollections/BitArray/BitArray.swift index e40cc0e2..832e5fa0 100644 --- a/Sources/BitCollections/BitArray/BitArray.swift +++ b/Sources/BitCollections/BitArray/BitArray.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 From 03b62ffb6e80d4514a86645c2858c5d7bc21cfb9 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:33:05 -0800 Subject: [PATCH 009/113] =?UTF-8?q?[BitArray]=20random(count:using:)=20?= =?UTF-8?q?=E2=86=92=20randomBits(count:using:)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...Array+Random.swift => BitArray+RandomBits.swift} | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) rename Sources/BitCollections/BitArray/{BitArray+Random.swift => BitArray+RandomBits.swift} (77%) diff --git a/Sources/BitCollections/BitArray/BitArray+Random.swift b/Sources/BitCollections/BitArray/BitArray+RandomBits.swift similarity index 77% rename from Sources/BitCollections/BitArray/BitArray+Random.swift rename to Sources/BitCollections/BitArray/BitArray+RandomBits.swift index 5c58cf78..9a13e78c 100644 --- a/Sources/BitCollections/BitArray/BitArray+Random.swift +++ b/Sources/BitCollections/BitArray/BitArray+RandomBits.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022-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 @@ -10,12 +10,13 @@ //===----------------------------------------------------------------------===// extension BitArray { - /// Create and return a new bit array consisting of `count` random bits. + /// Create and return a new bit array consisting of `count` random bits, + /// using the system random number generator. /// /// - Parameter count: The number of random bits to generate. - public static func random(count: Int) -> BitArray { + public static func randomBits(count: Int) -> BitArray { var rng = SystemRandomNumberGenerator() - return random(count: count, using: &rng) + return randomBits(count: count, using: &rng) } /// Create and return a new bit array consisting of `count` random bits, @@ -23,11 +24,11 @@ extension BitArray { /// /// - Parameter count: The number of random bits to generate. /// - Parameter rng: The random number generator to use. - public static func random( + public static func randomBits( count: Int, using rng: inout R ) -> BitArray { - precondition(count >= 0, "Invalid capacity value") + precondition(count >= 0, "Invalid count") guard count > 0 else { return BitArray() } let (w, b) = _BitPosition(count).endSplit var words = (0 ... w).map { _ in _Word(rng.next() as UInt) } From 4281dc4482114d17727f1c1cd7a6f3a8690bdf0e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:39:46 -0800 Subject: [PATCH 010/113] [BitArray] Change description to print bit arrays as binary numerals This matches std::bitset, and it seems to be the more logical option. --- .../BitArray+CustomStringConvertible.swift | 41 ------------ .../BitArray/BitArray+Descriptions.swift | 63 +++++++++++++++++++ 2 files changed, 63 insertions(+), 41 deletions(-) delete mode 100644 Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift create mode 100644 Sources/BitCollections/BitArray/BitArray+Descriptions.swift diff --git a/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift b/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift deleted file mode 100644 index 91357755..00000000 --- a/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift +++ /dev/null @@ -1,41 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2022 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 -// -//===----------------------------------------------------------------------===// - -extension BitArray: CustomStringConvertible { - // A textual representation of this instance. - public var description: String { - _bitString - } - - internal var _bitString: String { - var result: String - if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { - result = String(unsafeUninitializedCapacity: self.count) { target in - let b0: UInt8 = 48 // ASCII 0 - let b1: UInt8 = 49 // ASCII 1 - var i = 0 - for v in self { - target.initializeElement(at: i, to: v ? b1 : b0) - i &+= 1 - } - return i - } - } else { - result = "" - result.reserveCapacity(self.count) - for v in self { - result.append(v ? "1" : "0") - } - } - if result.isEmpty { result = "0" } - return result - } -} diff --git a/Sources/BitCollections/BitArray/BitArray+Descriptions.swift b/Sources/BitCollections/BitArray/BitArray+Descriptions.swift new file mode 100644 index 00000000..be4f0421 --- /dev/null +++ b/Sources/BitCollections/BitArray/BitArray+Descriptions.swift @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022-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 +// +//===----------------------------------------------------------------------===// + +extension UInt8 { + @inline(__always) + internal static var _ascii0: Self { 48 } + + @inline(__always) + internal static var _ascii1: Self { 49 } +} + +extension BitArray: CustomStringConvertible { + /// A textual representation of this instance. + /// Bit arrays print themselves as a string of binary bits, with the highest-indexed elements + /// appearing first, as in the binary representation of integers: + /// + /// let bits: BitArray = [false, false, false, true, true] + /// print(bits) // "11000" + /// + /// The description of an empty bit array is an empty string. + public var description: String { + _bitString + } +} + +extension BitArray: CustomDebugStringConvertible { + /// A textual representation of this instance, suitable for debugging. + public var debugDescription: String { + "BitArray(\(_bitString))" + } +} + +extension BitArray { + internal var _bitString: String { + guard !isEmpty else { return "" } + var result: String + if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { + result = String(unsafeUninitializedCapacity: self.count) { target in + var i = count - 1 + for v in self { + target.initializeElement(at: i, to: v ? ._ascii1 : ._ascii0) + i &-= 1 + } + return count + } + } else { + result = "" + result.reserveCapacity(self.count) + for v in self.reversed() { + result.append(v ? "1" : "0") + } + } + return result + } +} From c15e484f5aa2a404daa36bcb71b487433cc02885 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:43:06 -0800 Subject: [PATCH 011/113] [BitArray] Add init(minimumCapacity:) --- .../BitCollections/BitArray/BitArray+Initializers.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Sources/BitCollections/BitArray/BitArray+Initializers.swift b/Sources/BitCollections/BitArray/BitArray+Initializers.swift index e9be95a4..bc19006e 100644 --- a/Sources/BitCollections/BitArray/BitArray+Initializers.swift +++ b/Sources/BitCollections/BitArray/BitArray+Initializers.swift @@ -26,4 +26,12 @@ extension BitArray { let count = value.bitWidth self.init(_storage: words, count: count) } + + /// Creates a new, empty bit array with preallocated space for at least the + /// specified number of elements. + public init(minimumCapacity: Int) { + self.init() + reserveCapacity(minimumCapacity) + } +} } From c15b0d9889ef065ba1f6c9b33ae5cc057fd03ff6 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:59:24 -0800 Subject: [PATCH 012/113] =?UTF-8?q?[BitArray]=20Add=20BitArray=20=E2=86=92?= =?UTF-8?q?=20BinaryInteger=20conversion=20initializers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit extension BinaryInteger { public init(truncatingIfNeeded source: BitArray) public init?(exactly source: BitArray) public init(_ source: BitArray) } --- .../BitArray/BitArray+Initializers.swift | 236 +++++++++++++++++- .../BitArray/BitArray._UnsafeHandle.swift | 18 ++ 2 files changed, 253 insertions(+), 1 deletion(-) diff --git a/Sources/BitCollections/BitArray/BitArray+Initializers.swift b/Sources/BitCollections/BitArray/BitArray+Initializers.swift index bc19006e..5269a736 100644 --- a/Sources/BitCollections/BitArray/BitArray+Initializers.swift +++ b/Sources/BitCollections/BitArray/BitArray+Initializers.swift @@ -12,6 +12,16 @@ extension BitArray { /// Initialize a bit array from a bit set. /// + /// The result contains exactly as many bits as the maximum item in + /// the source set, plus one. If the set is empty, the result will + /// be empty, too. + /// + /// BitArray([] as BitSet) // (empty) + /// BitArray([0] as BitSet) // 1 + /// BitArray([1] as BitSet) // 10 + /// BitArray([1, 2, 4] as BitSet) // 1011 + /// BitArray([7] as BitSet) // 1000000 + /// /// - Complexity: O(1) public init(_ set: BitSet) { guard let l = set.last else { self.init(); return } @@ -19,11 +29,29 @@ extension BitArray { } /// Initialize a bit array from the binary representation of an integer. + /// The result will contain exactly `value.bitWidth` bits. + /// + /// BitArray(bitPattern: 3 as UInt8) // 00000011 + /// BitArray(bitPattern: 42 as Int8) // 00101010 + /// BitArray(bitPattern: -1 as Int8) // 11111111 + /// BitArray(bitPattern: 3 as Int16) // 0000000000000111 + /// BitArray(bitPattern: 42 as Int16) // 0000000000101010 + /// BitArray(bitPattern: -1 as Int16) // 1111111111111111 + /// BitArray(bitPattern: 3 as Int) // 0000000000...0000000111 + /// BitArray(bitPattern: 42 as Int) // 0000000000...0000101010 + /// BitArray(bitPattern: -1 as Int) // 1111111111...1111111111 /// /// - Complexity: O(value.bitWidth) public init(bitPattern value: I) { - let words = value.words.map { _Word($0) } + var words = value.words.map { _Word($0) } let count = value.bitWidth + if words.isEmpty { + precondition(count == 0, "Inconsistent bitWidth") + } else { + let (w, b) = _UnsafeHandle._BitPosition(count).endSplit + precondition(words.count == w + 1, "Inconsistent bitWidth") + words[w].formIntersection(_Word(upTo: b)) + } self.init(_storage: words, count: count) } @@ -34,4 +62,210 @@ extension BitArray { reserveCapacity(minimumCapacity) } } + +extension BinaryInteger { + @inlinable + internal static func _convert( + _ source: BitArray + ) -> (value: Self, isNegative: Bool) { + var value: Self = .zero + let isNegative = source._foreachTwosComplementWordDownward( + isSigned: Self.isSigned + ) { _, word in + value <<= UInt.bitWidth + value |= Self(truncatingIfNeeded: word) + return true + } + return (value, isNegative) + } + + /// Creates a new instance by truncating or extending the bits in the given + /// bit array, as needed. The bit at position 0 in `source` will correspond + /// to the least-significant bit in the result. + /// + /// If `Self` is an unsigned integer type, then the result will contain as + /// many bits from `source` it can accommodate, truncating off any extras. + /// + /// UInt8(truncatingIfNeeded: "" as BitArray) // 0 + /// UInt8(truncatingIfNeeded: "0" as BitArray) // 0 + /// UInt8(truncatingIfNeeded: "1" as BitArray) // 1 + /// UInt8(truncatingIfNeeded: "11" as BitArray) // 3 + /// UInt8(truncatingIfNeeded: "11111111" as BitArray) // 255 + /// UInt8(truncatingIfNeeded: "1100000001" as BitArray) // 1 + /// UInt8(truncatingIfNeeded: "1100000101" as BitArray) // 5 + /// + /// If `Self` is a signed integer type, then the contents of the bit array + /// are interpreted to be a two's complement representation of a signed + /// integer value, with the last bit in the array representing the sign of + /// the result. + /// + /// Int8(truncatingIfNeeded: "" as BitArray) // 0 + /// Int8(truncatingIfNeeded: "0" as BitArray) // 0 + /// Int8(truncatingIfNeeded: "1" as BitArray) // -1 + /// Int8(truncatingIfNeeded: "01" as BitArray) // 1 + /// Int8(truncatingIfNeeded: "101" as BitArray) // -3 + /// Int8(truncatingIfNeeded: "0101" as BitArray) // 5 + /// + /// Int8(truncatingIfNeeded: "00000001" as BitArray) // 1 + /// Int8(truncatingIfNeeded: "00000101" as BitArray) // 5 + /// Int8(truncatingIfNeeded: "01111111" as BitArray) // 127 + /// Int8(truncatingIfNeeded: "10000000" as BitArray) // -128 + /// Int8(truncatingIfNeeded: "11111111" as BitArray) // -1 + /// + /// Int8(truncatingIfNeeded: "000011111111" as BitArray) // -1 + /// Int8(truncatingIfNeeded: "111100000000" as BitArray) // 0 + /// Int8(truncatingIfNeeded: "111100000001" as BitArray) // 1 + @inlinable + public init(truncatingIfNeeded source: BitArray) { + self = Self._convert(source).value + } + + /// Creates a new instance from the bits in the given bit array, if the + /// corresponding integer value can be represented exactly. + /// If the value is not representable exactly, then the result is `nil`. + /// + /// If `Self` is an unsigned integer type, then the contents of the bit array + /// are interpreted to be the binary representation of a nonnegative + /// integer value. The bit array is allowed to contain bits in unrepresentable + /// positions, as long as they are all cleared. + /// + /// UInt8(exactly: "" as BitArray) // 0 + /// UInt8(exactly: "0" as BitArray) // 0 + /// UInt8(exactly: "1" as BitArray) // 1 + /// UInt8(exactly: "10" as BitArray) // 2 + /// UInt8(exactly: "00000000" as BitArray) // 0 + /// UInt8(exactly: "11111111" as BitArray) // 255 + /// UInt8(exactly: "0000000000000" as BitArray) // 0 + /// UInt8(exactly: "0000011111111" as BitArray) // 255 + /// UInt8(exactly: "0000100000000" as BitArray) // nil + /// UInt8(exactly: "1111111111111" as BitArray) // nil + /// + /// If `Self` is a signed integer type, then the contents of the bit array + /// are interpreted to be a two's complement representation of a signed + /// integer value, with the last bit in the array representing the sign of + /// the result. + /// + /// Int8(exactly: "" as BitArray) // 0 + /// Int8(exactly: "0" as BitArray) // 0 + /// Int8(exactly: "1" as BitArray) // -1 + /// Int8(exactly: "01" as BitArray) // 1 + /// Int8(exactly: "101" as BitArray) // -3 + /// Int8(exactly: "0101" as BitArray) // 5 + /// + /// Int8(exactly: "00000001" as BitArray) // 1 + /// Int8(exactly: "00000101" as BitArray) // 5 + /// Int8(exactly: "01111111" as BitArray) // 127 + /// Int8(exactly: "10000000" as BitArray) // -128 + /// Int8(exactly: "11111111" as BitArray) // -1 + /// + /// Int8(exactly: "00000000000" as BitArray) // 0 + /// Int8(exactly: "00001111111" as BitArray) // 127 + /// Int8(exactly: "00010000000" as BitArray) // nil + /// Int8(exactly: "11101111111" as BitArray) // nil + /// Int8(exactly: "11110000000" as BitArray) // -128 + /// Int8(exactly: "11111111111" as BitArray) // -1 + @inlinable + public init?(exactly source: BitArray) { + let (value, isNegative) = Self._convert(source) + guard isNegative == (value < 0) else { return nil } + let words = value.words + var equal = true + _ = source._foreachTwosComplementWordDownward(isSigned: Self.isSigned) { i, word in + assert(equal) + let w = ( + i < words.count ? words[i] + : isNegative ? UInt.max + : UInt.zero) + equal = (w == word) + return equal + } + guard equal else { return nil } + self = value + } + + /// Creates a new instance from the bits in the given bit array, if the + /// corresponding integer value can be represented exactly. + /// If the value is not representable exactly, then a runtime error will + /// occur. + /// + /// If `Self` is an unsigned integer type, then the contents of the bit array + /// are interpreted to be the binary representation of a nonnegative + /// integer value. The bit array is allowed to contain bits in unrepresentable + /// positions, as long as they are all cleared. + /// + /// UInt8("" as BitArray) // 0 + /// UInt8("0" as BitArray) // 0 + /// UInt8("1" as BitArray) // 1 + /// UInt8("10" as BitArray) // 2 + /// UInt8("00000000" as BitArray) // 0 + /// UInt8("11111111" as BitArray) // 255 + /// UInt8("0000000000000" as BitArray) // 0 + /// UInt8("0000011111111" as BitArray) // 255 + /// UInt8("0000100000000" as BitArray) // ERROR + /// UInt8("1111111111111" as BitArray) // ERROR + /// + /// If `Self` is a signed integer type, then the contents of the bit array + /// are interpreted to be a two's complement representation of a signed + /// integer value, with the last bit in the array representing the sign of + /// the result. + /// + /// Int8("" as BitArray) // 0 + /// Int8("0" as BitArray) // 0 + /// Int8("1" as BitArray) // -1 + /// Int8("01" as BitArray) // 1 + /// Int8("101" as BitArray) // -3 + /// Int8("0101" as BitArray) // 5 + /// + /// Int8("00000001" as BitArray) // 1 + /// Int8("00000101" as BitArray) // 5 + /// Int8("01111111" as BitArray) // 127 + /// Int8("10000000" as BitArray) // -128 + /// Int8("11111111" as BitArray) // -1 + /// + /// Int8("00000000000" as BitArray) // 0 + /// Int8("00001111111" as BitArray) // 127 + /// Int8("00010000000" as BitArray) // ERROR + /// Int8("11101111111" as BitArray) // ERROR + /// Int8("11110000000" as BitArray) // -128 + /// Int8("11111111111" as BitArray) // -1 + @inlinable + public init(_ source: BitArray) { + guard let value = Self(exactly: source) else { + fatalError(""" + BitArray value cannot be converted to \(Self.self) because it is \ + outside the representable range + """) + } + self = value + } +} + +extension BitArray { + @usableFromInline + internal func _foreachTwosComplementWordDownward( + isSigned: Bool, + body: (Int, UInt) -> Bool + ) -> Bool { + self._read { + guard $0._words.count > 0 else { return false } + + var isNegative = false + let end = $0.end.endSplit + assert(end.bit > 0) + let last = $0._words[end.word] + if isSigned, last.contains(end.bit - 1) { + // Sign extend last word + isNegative = true + if !body(end.word, last.union(_Word(upTo: end.bit).complement()).value) { + return isNegative + } + } else if !body(end.word, last.value) { + return isNegative + } + for i in stride(from: end.word - 1, through: 0, by: -1) { + if !body(i, $0._words[i].value) { return isNegative } + } + return isNegative + } + } } diff --git a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift index 7c4157f7..26ceb79d 100644 --- a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift +++ b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift @@ -81,6 +81,24 @@ extension BitArray._UnsafeHandle { Int(_count) } + internal var end: _BitPosition { + _BitPosition(_count) + } + + internal func set(at position: Int) { + ensureMutable() + assert(position >= 0 && position < _count) + let (word, bit) = _BitPosition(UInt(position)).split + _mutableWords[word].insert(bit) + } + + internal func clear(at position: Int) { + ensureMutable() + assert(position >= 0 && position < _count) + let (word, bit) = _BitPosition(UInt(position)).split + _mutableWords[word].remove(bit) + } + internal subscript(position: Int) -> Bool { get { assert(position >= 0 && position < _count) From a8bde6343976f70ce5043516f474fcd17bb52dac Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:59:56 -0800 Subject: [PATCH 013/113] [BitArray] Add toggleAll(), toggleAll(in:) --- .../BitArray/BitArray+BitwiseOperations.swift | 54 +++++++++++++++---- 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift index b697032b..24cdec23 100644 --- a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift +++ b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift @@ -114,16 +114,50 @@ extension BitArray { /// - Complexity: O(value.count) public static prefix func ~(value: Self) -> Self { var result = value - result._update { handle in - for i in 0 ..< handle._words.count { - handle._mutableWords[i].formComplement() - } - let p = _BitPosition(handle._count) - if p.bit > 0 { - handle._mutableWords[p.word].subtract(_Word(upTo: p.bit).complement()) - } - } - result._checkInvariants() + result.toggleAll() return result } + + public mutating func toggleAll() { + _update { handle in + let w = handle._mutableWords + for i in 0 ..< handle._words.count { + w[i].formComplement() + } + let p = handle.end + if p.bit > 0 { + w[p.word].subtract(_Word(upTo: p.bit).complement()) + } + } + _checkInvariants() + } + + public mutating func toggleAll(in range: Range) { + precondition(range.upperBound <= count, "Range out of bounds") + _update { handle in + let words = handle._mutableWords + let start = _BitPosition(range.lowerBound) + let end = _BitPosition(range.upperBound) + if start.word == end.word { + let bits = _Word(from: start.bit, to: end.bit) + words[start.word].formSymmetricDifference(bits) + return + } + words[start.word].formSymmetricDifference( + _Word(upTo: start.bit).complement()) + for i in stride(from: start.word + 1, to: end.word, by: 1) { + words[i].formComplement() + } + if end.bit > 0 { + words[end.word].formSymmetricDifference(_Word(upTo: end.bit)) + } + } + } + + @inlinable + public mutating func toggleAll( + in range: R + ) where R.Bound == Int { + toggleAll(in: range.relative(to: self)) + } } From a90b73966ae43f4c92ae2d5ec0deeb12c46c9499 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:00:27 -0800 Subject: [PATCH 014/113] [BitArray] Add conformance to ExpressibleByStringLiteral --- .../BitArray+ExpressibleByStringLiteral.swift | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Sources/BitCollections/BitArray/BitArray+ExpressibleByStringLiteral.swift diff --git a/Sources/BitCollections/BitArray/BitArray+ExpressibleByStringLiteral.swift b/Sources/BitCollections/BitArray/BitArray+ExpressibleByStringLiteral.swift new file mode 100644 index 00000000..a886a557 --- /dev/null +++ b/Sources/BitCollections/BitArray/BitArray+ExpressibleByStringLiteral.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 +// +//===----------------------------------------------------------------------===// + +extension BitArray: ExpressibleByStringLiteral { + /// Creates an instance initialized with the given elements. + @inlinable + public init(stringLiteral value: String) { + guard let bits = Self(value) else { + fatalError("Invalid bit array literal") + } + self = bits + } +} From 17343b752a208b8545dbec998cd71a465a54bde4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:01:46 -0800 Subject: [PATCH 015/113] [BitArray] fill(in:with:), insert(repeating:count:at:), append(repeating:count:) --- .../BitArray/BitArray+Extras.swift | 21 +++++++++++++++++++ .../BitArray/BitArray+Fill.swift | 7 +++++++ 2 files changed, 28 insertions(+) diff --git a/Sources/BitCollections/BitArray/BitArray+Extras.swift b/Sources/BitCollections/BitArray/BitArray+Extras.swift index d0ecd69a..6bf4c0b1 100644 --- a/Sources/BitCollections/BitArray/BitArray+Extras.swift +++ b/Sources/BitCollections/BitArray/BitArray+Extras.swift @@ -28,3 +28,24 @@ extension BitArray { } } } + +extension BitArray { + public mutating func insert( + repeating value: Bool, + count: Int, + at index: Int + ) { + precondition(count >= 0, "Can't insert a negative number of values") + precondition(index >= 0 && index <= count, "Index out of bounds") + guard count > 0 else { return } + _extend(by: count, with: false) + _copy(from: index ..< self.count - count, to: index + count) + fill(in: index ..< index + count, with: value) + } + + public mutating func append(repeating value: Bool, count: Int) { + precondition(count >= 0, "Can't append a negative number of values") + guard count > 0 else { return } + _extend(by: count, with: value) + } +} diff --git a/Sources/BitCollections/BitArray/BitArray+Fill.swift b/Sources/BitCollections/BitArray/BitArray+Fill.swift index fd96dd56..6c8223f6 100644 --- a/Sources/BitCollections/BitArray/BitArray+Fill.swift +++ b/Sources/BitCollections/BitArray/BitArray+Fill.swift @@ -31,4 +31,11 @@ extension BitArray { } } } + + public mutating func fill( + in range: R, + with value: Bool = true + ) where R.Bound == Int { + fill(in: range.relative(to: self), with: value) + } } From 866d00798f6c802bc7c70244d8f7766c933ed566 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:02:16 -0800 Subject: [PATCH 016/113] [BitArray] Add LosslessStringConvertible conformance --- .../BitArray+LosslessStringConvertible.swift | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift diff --git a/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift b/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift new file mode 100644 index 00000000..2166b166 --- /dev/null +++ b/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift @@ -0,0 +1,52 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension BitArray: LosslessStringConvertible { + /// Initializes a new bit array from a string representation. + /// + /// The string given is interpreted as if it was the binary representation + /// of an integer value, consisting of the digits `0` and `1`, with the + /// highest digits appearing first. + /// + /// BitArray("") // [] + /// BitArray("001") // [true, false, false] + /// BitArray("1110") // [false, true, true, true] + /// BitArray("42") // nil + /// BitArray("Foo") // nil + /// + public init?(_ description: String) { + let bits: BitArray? = description.utf8.withContiguousStorageIfAvailable { buffer in + Self(_utf8: buffer) + } ?? Self(_utf8: description.utf8) + guard let bits = bits else { + return nil + } + self = bits + } + + internal init?(_utf8 utf8: C) where C.Element == UInt8 { + let c = utf8.count + self.init(repeating: false, count: c) + var i = c &- 1 + let success = _update { handle in + for byte in utf8 { + if byte == ._ascii1 { + handle.set(at: i) + } else { + guard byte == ._ascii0 else { return false } + } + i &-= 1 + } + return true + } + guard success else { return nil } + } +} From a360969ec6ec8dd0ce8d65dbcdca3be6bb444a34 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:04:30 -0800 Subject: [PATCH 017/113] [BitArray] Add masking and resizing shifts --- .../BitArray/BitArray+Shifts.swift | 162 ++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 Sources/BitCollections/BitArray/BitArray+Shifts.swift diff --git a/Sources/BitCollections/BitArray/BitArray+Shifts.swift b/Sources/BitCollections/BitArray/BitArray+Shifts.swift new file mode 100644 index 00000000..7eb6601d --- /dev/null +++ b/Sources/BitCollections/BitArray/BitArray+Shifts.swift @@ -0,0 +1,162 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022-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 +// +//===----------------------------------------------------------------------===// + +extension BitArray { + /// Shift the bits in this array by the specified number of places to the + /// left (towards the end of the array), by inserting `amount` false values + /// at the beginning. + /// + /// If `amount` is negative, this is equivalent to shifting `-amount` + /// places to the right. + /// + /// var bits: BitArray = "1110110" + /// bits.maskingShiftLeft(by: 2) + /// // bits is now 111011000 + /// bits.maskingShiftLeft(by: -4) + /// // bits is now 11101 + /// bits.maskingShiftLeft(by: 8) + /// // bits is now 111010000000 + public mutating func resizingShiftLeft(by amount: Int) { + guard amount != 0 else { return } + if amount > 0 { + _resizingShiftLeft(by: amount) + } else { + _resizingShiftRight(by: -amount) + } + } + + /// Shift the bits in this array by the specified number of places to the + /// right (towards the start of the array), by removing `amount` existing + /// values from the front of the array. + /// + /// If `amount` is negative, then this is equivalent to shifting `-amount` + /// places to the left. If amount is greater than or equal to `count`, + /// then the resulting bit array will be empty. + /// + /// var bits: BitArray = "1110110" + /// bits.maskingShiftRight(by: 2) + /// // bits is now 11101 + /// bits.maskingShiftRight(by: -4) + /// // bits is now 111010000 + /// bits.maskingShiftRight(by: 10) + /// // bits is now empty + /// + /// If `amount` is between 0 and `count`, then this has the same effect as + /// `removeFirst(amount)`. + public mutating func resizingShiftRight(by amount: Int) { + guard amount != 0 else { return } + if amount > 0 { + _resizingShiftRight(by: amount) + } else { + _resizingShiftLeft(by: -amount) + } + } + + internal mutating func _resizingShiftLeft(by amount: Int) { + assert(amount > 0) + _extend(by: amount, with: false) + maskingShiftLeft(by: amount) + } + + internal mutating func _resizingShiftRight(by amount: Int) { + assert(amount > 0) + guard amount < count else { + self = .init() + return + } + self._copy(from: Range(uncheckedBounds: (amount, count)), to: 0) + self._removeLast(count &- amount) + } +} + +extension BitArray { + // FIXME: Add maskingShiftRight(by:in:) and maskingShiftLeft(by:in:) for shifting slices. + + /// Shift the bits in this array by the specified number of places to the + /// left (towards the end of the array), without changing + /// its count. + /// + /// Values that are shifted off the array are discarded. Values that are + /// shifted in are all set to false. + /// + /// If `amount` is negative, this is equivalent to shifting `-amount` + /// places to the right. If `amount` is greater than or equal to `count`, + /// then all values are set to false. + /// + /// var bits: BitArray = "1110110" + /// bits.maskingShiftLeft(by: 2) + /// // bits is now 1011000 + /// bits.maskingShiftLeft(by: -4) + /// // bits is now 0000101 + /// bits.maskingShiftLeft(by: 8) + /// // bits is now 0000000 + public mutating func maskingShiftLeft(by amount: Int) { + guard amount != 0 else { return } + _update { + if amount > 0 { + $0._maskingShiftLeft(by: amount) + } else { + $0._maskingShiftRight(by: -amount) + } + } + } + + /// Shift the bits in this array by the specified number of places to the + /// right (towards the beginning of the array), without changing + /// its count. + /// + /// Values that are shifted off the array are discarded. Values that are + /// shifted in are all set to false. + /// + /// If `amount` is negative, this is equivalent to shifting `-amount` + /// places to the left. If `amount` is greater than or equal to `count`, + /// then all values are set to false. + /// + /// var bits: BitArray = "1110110" + /// bits.maskingShiftRight(by: 2) + /// // bits is now 0011101 + /// bits.maskingShiftRight(by: -3) + /// // bits is now 1101000 + /// bits.maskingShiftRight(by: 8) + /// // bits is now 0000000 + public mutating func maskingShiftRight(by amount: Int) { + guard amount != 0 else { return } + _update { + if amount > 0 { + $0._maskingShiftRight(by: amount) + } else { + $0._maskingShiftLeft(by: -amount) + } + } + } +} + +extension BitArray._UnsafeHandle { + internal mutating func _maskingShiftLeft(by amount: Int) { + assert(amount > 0) + let d = Swift.min(amount, self.count) + if d == amount { + let range = Range(uncheckedBounds: (0, self.count &- d)) + self.copy(from: range, to: d) + } + self.clear(in: Range(uncheckedBounds: (0, d))) + } + + internal mutating func _maskingShiftRight(by amount: Int) { + assert(amount > 0) + let d = Swift.min(amount, self.count) + if d == amount { + let range = Range(uncheckedBounds: (d, self.count)) + self.copy(from: range, to: 0) + } + self.clear(in: Range(uncheckedBounds: (self.count &- d, self.count))) + } +} From 3e6df33472d54ed83dffe3bca7a3c8f65bab4c43 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:04:41 -0800 Subject: [PATCH 018/113] [BitArray] Update tests --- Tests/BitCollectionsTests/BitArrayTests.swift | 211 +++++++++++++++++- 1 file changed, 200 insertions(+), 11 deletions(-) diff --git a/Tests/BitCollectionsTests/BitArrayTests.swift b/Tests/BitCollectionsTests/BitArrayTests.swift index 303ec8b4..bbda7973 100644 --- a/Tests/BitCollectionsTests/BitArrayTests.swift +++ b/Tests/BitCollectionsTests/BitArrayTests.swift @@ -144,7 +144,115 @@ final class BitArrayTests: CollectionTestCase { expectEqualElements(actual, expected) } } - + + func test_conversion_to_BinaryInteger_truncating() { + let cases: [(bits: BitArray, signed: Int8, unsigned: UInt8)] = [ + ("", 0, 0), + ("0", 0, 0), + ("1", -1, 1), + ("00", 0, 0), + ("01", 1, 1), + ("10", -2, 2), + ("11", -1, 3), + ("001", 1, 1), + ("010", 2, 2), + ("011", 3, 3), + ("100", -4, 4), + ("101", -3, 5), + ("110", -2, 6), + ("111", -1, 7), + // 8 bits + ("00000000", 0, 0), + ("10000000", -128, 128), + ("10000001", -127, 129), + ("11111111", -1, 255), + // 9 bits + ("000000000", 0, 0), + ("000000100", 4, 4), + ("010000000", -128, 128), + ("010000001", -127, 129), + ("011111111", -1, 255), + ("100000000", 0, 0), + ("100000001", 1, 1), + ("101111111", 127, 127), + ("110000000", -128, 128), + ("110000001", -127, 129), + ("111111110", -2, 254), + ("111111111", -1, 255), + // 32 bits + ("00000000000000000000000000000000", 0, 0), + ("00000000000000000000000001111111", 127, 127), + ("00000000000000000000000010000000", -128, 128), + ("00000000000000000000000011111111", -1, 255), + ("00000000000000000000000100000000", 0, 0), + ("11111111111111111111111110000000", -128, 128), + ("11111111111111111111111111111110", -2, 254), + ("11111111111111111111111111111111", -1, 255), + ] + + withEvery("pair", in: cases) { (bits, signed, unsigned) in + let actual1 = Int8(truncatingIfNeeded: bits) + expectEqual(actual1, signed) + + let actual2 = UInt8(truncatingIfNeeded: bits) + expectEqual(actual2, unsigned) + } + } + + func test_conversion_to_BinaryInteger_exact() { + let cases: [(bits: BitArray, signed: Int8?, unsigned: UInt8?)] = [ + ("", 0, 0), + ("0", 0, 0), + ("1", -1, 1), + ("00", 0, 0), + ("01", 1, 1), + ("10", -2, 2), + ("11", -1, 3), + ("001", 1, 1), + ("010", 2, 2), + ("011", 3, 3), + ("100", -4, 4), + ("101", -3, 5), + ("110", -2, 6), + ("111", -1, 7), + // 8 bits + ("00000000", 0, 0), + ("10000000", -128, 128), + ("10000001", -127, 129), + ("11111111", -1, 255), + // 9 bits + ("000000000", 0, 0), + ("000000100", 4, 4), + ("010000000", nil, 128), + ("010000001", nil, 129), + ("011111111", nil, 255), + ("100000000", nil, nil), + ("100000001", nil, nil), + ("101111111", nil, nil), + ("110000000", -128, nil), + ("110000001", -127, nil), + ("111111110", -2, nil), + ("111111111", -1, nil), + // 32 bits + ("00000000000000000000000000000000", 0, 0), + ("00000000000000000000000001111111", 127, 127), + ("00000000000000000000000010000000", nil, 128), + ("00000000000000000000000011111111", nil, 255), + ("00000000000000000000000100000000", nil, nil), + ("11111111111111111111111110000000", -128, nil), + ("11111111111111111111111111111110", -2, nil), + ("11111111111111111111111111111111", -1, nil), + ] + + withEvery("pair", in: cases) { (bits, signed, unsigned) in + let actual1 = Int8(exactly: bits) + expectEqual(actual1, signed) + + let actual2 = UInt8(exactly: bits) + expectEqual(actual2, unsigned) + } + } + func test_init_BitSet() { expectEqualElements(BitArray(BitSet([])), []) expectEqualElements(BitArray(BitSet([0])), [true]) @@ -212,7 +320,76 @@ final class BitArrayTests: CollectionTestCase { true, true, false, false, true, true, true, ]) } - + + func test_ExpressibleByStringLiteral() { + let a: BitArray = "" + expectEqualElements(a, []) + + let b: BitArray = "1" + expectEqualElements(b, [true]) + + let c: BitArray = "001" + expectEqualElements(c, [true, false, false]) + + let d: BitArray = "10001" + expectEqualElements(d, [true, false, false, false, true]) + + let e: BitArray = """ + 111001110100010110100000000100110010010101001000000100110010001 + """ + expectEqualElements(e, [ + true, false, false, false, true, false, false, + true, true, false, false, true, false, false, + false, false, false, false, true, false, false, + true, false, true, false, true, false, false, + true, false, false, true, true, false, false, + true, false, false, false, false, false, false, + false, false, true, false, true, true, false, + true, false, false, false, true, false, true, + true, true, false, false, true, true, true, + ]) + } + + func test_literals() { + let cases: [(a: BitArray, b: BitArray)] = [ + ("", []), + ("0", [false]), + ("1", [true]), + ("1010", [false, true, false, true]), + ("0101", [true, false, true, false]), + ("111000", [false, false, false, true, true, true]), + ("000111", [true, true, true, false, false, false]), + ] + withEvery("i", in: cases.indices) { i in + let (a, b) = cases[i] + expectEqual(a, b) + } + } + + func test_LosslessStringConvertible() { + let cases: [(a: String, b: BitArray?)] = [ + ("", []), + ("0", [false]), + ("1", [true]), + ("1010", [false, true, false, true]), + ("0101", [true, false, true, false]), + ("111000", [false, false, false, true, true, true]), + ("000111", [true, true, true, false, false, false]), + ("_", nil), + ("00010101X", nil), + ("①⓪⓪①", nil), + ("2341", nil), + ("00 10 01", nil), + (" 01", nil), + ("01 ", nil), + ] + withEvery("i", in: cases.indices) { i in + let (a, b) = cases[i] + let bits = BitArray(a) + expectEqual(bits, b) + } + } + func test_Hashable() { // This is a silly test, but it does exercise hashing a bit. let classes: [[BitArray]] = [ @@ -628,7 +805,19 @@ final class BitArrayTests: CollectionTestCase { bits.reserveCapacity(2000) expectGreaterThanOrEqual(bits._capacity, 2000) } - + + func test_init_minimumCapacity() { + let b1 = BitArray(minimumCapacity: 0) + expectEqual(b1._capacity, 0) + + let cases = [0, 1, 100, 1000, 2000] + withEvery("capacity", in: cases) { capacity in + let bits = BitArray(minimumCapacity: capacity) + expectTrue(bits.isEmpty) + expectGreaterThanOrEqual(bits._capacity, capacity) + } + } + func test_bitwiseOr() { withSome("count", in: 0 ..< 512, maxSamples: 100) { count in withEvery("i", in: 0 ..< 10) { i in @@ -719,35 +908,35 @@ final class BitArrayTests: CollectionTestCase { func test_random() { var rng = AllOnesRandomNumberGenerator() for c in [0, 10, 64, 65, 77, 1200] { - let array = BitArray.random(count: c, using: &rng) + let array = BitArray.randomBits(count: c, using: &rng) expectEqual(array.count, c) expectEqualElements(array, repeatElement(true, count: c)) } - let a = Set((0..<10).map { _ in BitArray.random(count: 1000) }) + let a = Set((0..<10).map { _ in BitArray.randomBits(count: 1000) }) expectEqual(a.count, 10) } func test_description() { let a: BitArray = [] - expectEqual("\(a)", "0") + expectEqual("\(a)", "") let b: BitArray = [true, false, true, true, true] - expectEqual("\(b)", "10111") + expectEqual("\(b)", "11101") let c: BitArray = [false, false, false, false, true, true, true, false] - expectEqual("\(c)", "00001110") + expectEqual("\(c)", "01110000") } func test_debugDescription() { let a: BitArray = [] - expectEqual("\(String(reflecting: a))", "BitArray(0)") + expectEqual("\(String(reflecting: a))", "BitArray()") let b: BitArray = [true, false, true, true, true] - expectEqual("\(String(reflecting: b))", "BitArray(10111)") + expectEqual("\(String(reflecting: b))", "BitArray(11101)") let c: BitArray = [false, false, false, false, true, true, true, false] - expectEqual("\(String(reflecting: c))", "BitArray(00001110)") + expectEqual("\(String(reflecting: c))", "BitArray(01110000)") } func test_mirror() { From 5dc7a8970eabcf6aaa49529b5ef6401f5128637e Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Thu, 2 Mar 2023 10:59:03 -0800 Subject: [PATCH 019/113] build: add ARM64 to the architecture mappings for Windows Windows uses `ARM64` for `CMAKE_SYSTEM_PROCESSOR` which does not match the current spellings. --- cmake/modules/SwiftSupport.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/SwiftSupport.cmake b/cmake/modules/SwiftSupport.cmake index d3d40591..2a63a91c 100644 --- a/cmake/modules/SwiftSupport.cmake +++ b/cmake/modules/SwiftSupport.cmake @@ -17,7 +17,7 @@ See https://swift.org/LICENSE.txt for license information function(get_swift_host_arch result_var_name) if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") set("${result_var_name}" "x86_64" PARENT_SCOPE) - elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64") + elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64|ARM64") if(CMAKE_SYSTEM_NAME MATCHES Darwin) set("${result_var_name}" "arm64" PARENT_SCOPE) else() From 150a165d73f0a8b31b9a8280b4d429640f725679 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:27:52 -0800 Subject: [PATCH 020/113] Add experimental rope implementation --- Package.swift | 11 + .../BString/Basics/_BString+Builder.swift | 136 +++++ .../BString/Basics/_BString+Contents.swift | 312 ++++++++++ .../BString/Basics/_BString+Debugging.swift | 16 + .../BString/Basics/_BString+Index.swift | 96 ++++ .../BString/Basics/_BString+Ingester.swift | 159 ++++++ .../BString/Basics/_BString+Invariants.swift | 34 ++ .../BString/Basics/_BString+Iterators.swift | 168 ++++++ .../BString/Basics/_BString+Metrics.swift | 203 +++++++ .../BString/Basics/_BString+Path.swift | 85 +++ .../BString/Basics/_BString+Summary.swift | 69 +++ .../RopeModule/BString/Basics/_BString.swift | 25 + .../_BString+Chunk+Append and Insert.swift | 168 ++++++ .../BString/Chunk/_BString+Chunk+Breaks.swift | 66 +++ .../Chunk/_BString+Chunk+CordElement.swift | 151 +++++ .../BString/Chunk/_BString+Chunk+Counts.swift | 146 +++++ .../Chunk/_BString+Chunk+Description.swift | 67 +++ ...BString+Chunk+Indexing by Characters.swift | 106 ++++ .../_BString+Chunk+Indexing by UTF16.swift | 26 + .../Chunk/_BString+Chunk+Splitting.swift | 144 +++++ .../BString/Chunk/_BString+Chunk.swift | 114 ++++ .../Conformances/_BString+Comparisons.swift | 153 +++++ .../Conformances/_BString+Conformances.swift | 22 + .../Conformances/_BString+Hashing.swift | 37 ++ .../BString/Operations/_BString+Append.swift | 171 ++++++ .../Operations/_BString+Initializers.swift | 107 ++++ .../BString/Operations/_BString+Insert.swift | 78 +++ .../Operations/_BString+Managing Breaks.swift | 263 +++++++++ .../Operations/_BString+RemoveSubrange.swift | 42 ++ .../Operations/_BString+ReplaceSubrange.swift | 49 ++ .../BString/Operations/_BString+Split.swift | 30 + .../BigString/BigString+CharacterView.swift | 269 +++++++++ .../BigString/BigString+UTF16View.swift | 129 +++++ .../BigString/BigString+UTF8View.swift | 129 +++++ .../BigString+UnicodeScalarView.swift | 271 +++++++++ Sources/RopeModule/BigString/BigString.swift | 66 +++ .../Rope/Basics/_Rope+Builder.swift | 439 ++++++++++++++ .../Rope/Basics/_Rope+Debugging.swift | 90 +++ .../Rope/Basics/_Rope+Invariants.swift | 63 +++ .../RopeModule/Rope/Basics/_Rope+Node.swift | 499 ++++++++++++++++ .../Rope/Basics/_Rope+Storage.swift | 48 ++ .../Rope/Basics/_Rope+UnsafeHandle.swift | 188 ++++++ Sources/RopeModule/Rope/Basics/_Rope.swift | 56 ++ .../RopeModule/Rope/Basics/_RopeElement.swift | 39 ++ .../RopeModule/Rope/Basics/_RopeItem.swift | 71 +++ .../RopeModule/Rope/Basics/_RopeMetric.swift | 26 + .../RopeModule/Rope/Basics/_RopeSummary.swift | 55 ++ .../Rope/Conformances/_Rope+Collection.swift | 360 ++++++++++++ .../Rope/Conformances/_Rope+Sequence.swift | 103 ++++ .../Rope/Operations/_Rope+Append.swift | 71 +++ .../Rope/Operations/_Rope+Find.swift | 82 +++ .../Rope/Operations/_Rope+ForEachWhile.swift | 86 +++ .../Rope/Operations/_Rope+Insert.swift | 191 +++++++ .../Rope/Operations/_Rope+Join.swift | 115 ++++ .../Operations/_Rope+MutatingForEach.swift | 87 +++ .../Rope/Operations/_Rope+Remove.swift | 123 ++++ .../Operations/_Rope+RemoveSubrange.swift | 308 ++++++++++ .../Rope/Operations/_Rope+Split.swift | 136 +++++ .../Utilities/Optional Utilities.swift | 18 + .../Utilities/String Utilities.swift | 122 ++++ .../Utilities/String.Index+ABI.swift | 101 ++++ .../Utilities/_CharacterRecognizer.swift | 287 ++++++++++ Tests/RopeModuleTests/SampleStrings.swift | 153 +++++ .../SeedableRandomNumberGenerator.swift | 45 ++ Tests/RopeModuleTests/TestBString.swift | 368 ++++++++++++ Tests/RopeModuleTests/TestBigString.swift | 515 +++++++++++++++++ Tests/RopeModuleTests/TestRope.swift | 535 ++++++++++++++++++ .../xcschemes/RopeModule.xcscheme | 81 +++ 68 files changed, 9579 insertions(+) create mode 100644 Sources/RopeModule/BString/Basics/_BString+Builder.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString+Contents.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString+Debugging.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString+Index.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString+Ingester.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString+Invariants.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString+Iterators.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString+Metrics.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString+Path.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString+Summary.swift create mode 100644 Sources/RopeModule/BString/Basics/_BString.swift create mode 100644 Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift create mode 100644 Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift create mode 100644 Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift create mode 100644 Sources/RopeModule/BString/Chunk/_BString+Chunk+Counts.swift create mode 100644 Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift create mode 100644 Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift create mode 100644 Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift create mode 100644 Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift create mode 100644 Sources/RopeModule/BString/Chunk/_BString+Chunk.swift create mode 100644 Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift create mode 100644 Sources/RopeModule/BString/Conformances/_BString+Conformances.swift create mode 100644 Sources/RopeModule/BString/Conformances/_BString+Hashing.swift create mode 100644 Sources/RopeModule/BString/Operations/_BString+Append.swift create mode 100644 Sources/RopeModule/BString/Operations/_BString+Initializers.swift create mode 100644 Sources/RopeModule/BString/Operations/_BString+Insert.swift create mode 100644 Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift create mode 100644 Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift create mode 100644 Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift create mode 100644 Sources/RopeModule/BString/Operations/_BString+Split.swift create mode 100644 Sources/RopeModule/BigString/BigString+CharacterView.swift create mode 100644 Sources/RopeModule/BigString/BigString+UTF16View.swift create mode 100644 Sources/RopeModule/BigString/BigString+UTF8View.swift create mode 100644 Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift create mode 100644 Sources/RopeModule/BigString/BigString.swift create mode 100644 Sources/RopeModule/Rope/Basics/_Rope+Builder.swift create mode 100644 Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift create mode 100644 Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift create mode 100644 Sources/RopeModule/Rope/Basics/_Rope+Node.swift create mode 100644 Sources/RopeModule/Rope/Basics/_Rope+Storage.swift create mode 100644 Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift create mode 100644 Sources/RopeModule/Rope/Basics/_Rope.swift create mode 100644 Sources/RopeModule/Rope/Basics/_RopeElement.swift create mode 100644 Sources/RopeModule/Rope/Basics/_RopeItem.swift create mode 100644 Sources/RopeModule/Rope/Basics/_RopeMetric.swift create mode 100644 Sources/RopeModule/Rope/Basics/_RopeSummary.swift create mode 100644 Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift create mode 100644 Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+Append.swift create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+Find.swift create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+Insert.swift create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+Join.swift create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+Remove.swift create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+Split.swift create mode 100644 Sources/RopeModule/Utilities/Optional Utilities.swift create mode 100644 Sources/RopeModule/Utilities/String Utilities.swift create mode 100644 Sources/RopeModule/Utilities/String.Index+ABI.swift create mode 100644 Sources/RopeModule/Utilities/_CharacterRecognizer.swift create mode 100644 Tests/RopeModuleTests/SampleStrings.swift create mode 100644 Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift create mode 100644 Tests/RopeModuleTests/TestBString.swift create mode 100644 Tests/RopeModuleTests/TestBigString.swift create mode 100644 Tests/RopeModuleTests/TestRope.swift create mode 100644 Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme diff --git a/Package.swift b/Package.swift index 77ed5a92..c39935ed 100644 --- a/Package.swift +++ b/Package.swift @@ -53,6 +53,7 @@ let package = Package( .library(name: "HeapModule", targets: ["HeapModule"]), .library(name: "OrderedCollections", targets: ["OrderedCollections"]), .library(name: "HashTreeCollections", targets: ["HashTreeCollections"]), + .library(name: "RopeModule", targets: ["RopeModule"]), ], targets: [ .target( @@ -144,5 +145,15 @@ let package = Package( name: "HashTreeCollectionsTests", dependencies: ["HashTreeCollections", "_CollectionsTestSupport"], swiftSettings: settings), + + // BigString + .target( + name: "RopeModule", + dependencies: ["_CollectionsUtilities"], + swiftSettings: settings), + .testTarget( + name: "RopeModuleTests", + dependencies: ["RopeModule", "_CollectionsTestSupport"], + swiftSettings: settings), ] ) diff --git a/Sources/RopeModule/BString/Basics/_BString+Builder.swift b/Sources/RopeModule/BString/Basics/_BString+Builder.swift new file mode 100644 index 00000000..5a4fb631 --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString+Builder.swift @@ -0,0 +1,136 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + struct Builder { + typealias Chunk = _BString.Chunk + typealias Ingester = _BString.Ingester + typealias Rope = _BString.Rope + + var base: Rope.Builder + var suffixStartState: _CharacterRecognizer + var prefixEndState: _CharacterRecognizer + + init( + base: Rope.Builder, + prefixEndState: _CharacterRecognizer, + suffixStartState: _CharacterRecognizer + ) { + self.base = base + self.suffixStartState = suffixStartState + self.prefixEndState = prefixEndState + } + + init() { + self.base = Rope.Builder() + self.suffixStartState = _CharacterRecognizer() + self.prefixEndState = _CharacterRecognizer() + } + } +} + +extension _Rope<_BString.Chunk>.Builder { + func breakState() -> _CharacterRecognizer { + let chars = self.prefixSummary.characters + assert(self.isPrefixEmpty || chars > 0) + let metric = _BString.CharacterMetric() + var state = _CharacterRecognizer() + _ = self.forEachElementInPrefix(from: chars - 1, in: metric) { chunk, i in + if let i { + state = .init(partialCharacter: chunk.string[i...]) + } else { + state.consumePartialCharacter(chunk.string[...]) + } + return true + } + return state + } +} + +extension _BString.Builder { + mutating func append(_ str: __owned some StringProtocol) { + append(Substring(str)) + } + + mutating func append(_ str: __owned String) { + append(str[...]) + } + + mutating func append(_ str: __owned Substring) { + guard !str.isEmpty else { return } + var ingester = Ingester(str, startState: self.prefixEndState) + if var prefix = base.prefix._take() { + if let slice = ingester.nextSlice(maxUTF8Count: prefix.value.availableSpace) { + prefix.value._append(slice) + } + self.base.prefix = prefix + } + while let next = ingester.nextChunk() { + base.append(next) + } + self.prefixEndState = ingester.state + } + + mutating func append(_ newChunk: __owned Chunk) { + var state = _CharacterRecognizer() + append(newChunk, state: &state) + } + + mutating func append(_ newChunk: __owned Chunk, state: inout _CharacterRecognizer) { + var newChunk = newChunk + newChunk.resyncBreaksFromStartToEnd(old: &state, new: &self.prefixEndState) + self.base.append(newChunk) + } + + mutating func append(_ other: __owned _BString) { + var state = _CharacterRecognizer() + append(other.rope, state: &state) + } + + mutating func append(_ other: __owned Rope, state: inout _CharacterRecognizer) { + guard !other.isEmpty else { return } + var other = _BString(rope: other) + other.rope.resyncBreaksToEnd(old: &state, new: &self.prefixEndState) + self.base.append(other.rope) + } + + mutating func append(from ingester: inout Ingester) { + assert(ingester.state == self.prefixEndState) + if var prefix = base.prefix._take() { + if let first = ingester.nextSlice(maxUTF8Count: prefix.value.availableSpace) { + prefix.value._append(first) + } + base.prefix = prefix + } + + let suffixCount = base.suffix?.value.utf8Count ?? 0 + + while let chunk = ingester.nextWellSizedChunk(suffix: suffixCount) { + base.append(chunk) + } + precondition(ingester.isAtEnd) + self.prefixEndState = ingester.state + } +} + +extension _BString.Builder { + mutating func finalize() -> _BString { + // Resync breaks in suffix. + _ = base.mutatingForEachSuffix { chunk in + chunk.resyncBreaksFromStart(old: &suffixStartState, new: &prefixEndState) + } + // Roll it all up. + let rope = self.base.finalize() + let string = _BString(rope: rope) + string.invariantCheck() + return string + } +} diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift new file mode 100644 index 00000000..3fd8c807 --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -0,0 +1,312 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + var isEmpty: Bool { + rope.summary.isZero + } + + var startIndex: Index { + Index(_utf8Offset: 0) + } + + var endIndex: Index { + Index(_utf8Offset: utf8Count) + } +} + +extension _BString { + var characterCount: Int { rope.summary.characters } + var unicodeScalarCount: Int { rope.summary.unicodeScalars } + var utf16Count: Int { rope.summary.utf16 } + var utf8Count: Int { rope.summary.utf8 } +} + +extension _BString { + func distance( + from start: Index, + to end: Index, + in metric: some _StringMetric + ) -> Int { + guard !isEmpty else { + precondition(start == end && start == endIndex, "Invalid index") + return 0 + } + let a = path(to: Swift.min(start, end), preferEnd: false) + let b = path(to: Swift.max(start, end), preferEnd: true) + if a.path.rope == b.path.rope { + return metric.distance(from: a.path.chunk, to: b.path.chunk, in: a.chunk) + } + var d = 0 + d += rope.distance(from: a.path.rope, to: b.path.rope, in: metric) + d -= metric.distance(from: a.chunk.string.startIndex, to: a.path.chunk, in: a.chunk) + d += metric.distance(from: b.chunk.string.startIndex, to: b.path.chunk, in: b.chunk) + return start <= end ? d : -d + } + + func characterDistance(from start: Index, to end: Index) -> Int { + distance(from: start, to: end, in: CharacterMetric()) + } + + func unicodeScalarDistance(from start: Index, to end: Index) -> Int { + distance(from: start, to: end, in: UnicodeScalarMetric()) + } + + func utf16Distance(from start: Index, to end: Index) -> Int { + distance(from: start, to: end, in: UTF16Metric()) + } + + func utf8Distance(from start: Index, to end: Index) -> Int { + end._utf8Offset - start._utf8Offset + } +} + +extension _BString { + func _path( + _ i: Index, + offsetBy distance: Int, + in metric: some _StringMetric + ) -> (path: Path, chunk: Chunk) { + var (path, chunk) = path(to: i, preferEnd: false) + var d = distance + let r = metric.formIndex(&path.chunk, offsetBy: &d, in: chunk) + if r.found { + return (path, chunk) + } + + if r.forward { + assert(distance >= 0) + assert(path.chunk == chunk.string.endIndex) + d += metric.nonnegativeSize(of: chunk.summary) + rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false) + precondition(path.rope < rope.endIndex) + chunk = rope[path.rope] + path.chunk = metric.index(at: d, in: chunk) + return (path, chunk) + } + + assert(distance <= 0) + assert(path.chunk == chunk.string.startIndex) + rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false) + chunk = rope[path.rope] + path.chunk = metric.index(at: d, in: chunk) + return (path, chunk) + } + + func index( + _ i: Index, + offsetBy distance: Int, + in metric: some _StringMetric + ) -> Index { + var (path, chunk) = path(to: i, preferEnd: false) + let base = baseIndex(with: i, at: path.chunk) + var d = distance + let r = metric.formIndex(&path.chunk, offsetBy: &d, in: chunk) + if r.found { + return index(base: base, offsetBy: path.chunk) + } + + if r.forward { + assert(distance >= 0) + assert(path.chunk == chunk.string.endIndex) + d += metric.nonnegativeSize(of: chunk.summary) + rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false) + if path.rope == rope.endIndex { + return Index(_utf8Offset: self.utf8Count) + } + chunk = rope[path.rope] + path.chunk = metric.index(at: d, in: chunk) + return index(of: path) + } + + assert(distance <= 0) + assert(path.chunk == chunk.string.startIndex) + rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false) + chunk = rope[path.rope] + path.chunk = metric.index(at: d, in: chunk) + return index(of: path) + } + + func characterIndex(_ i: Index, offsetBy distance: Int) -> Index { + index(i, offsetBy: distance, in: CharacterMetric()) + } + + func unicodeScalarIndex(_ i: Index, offsetBy distance: Int) -> Index { + index(i, offsetBy: distance, in: UnicodeScalarMetric()) + } + + func utf16Index(_ i: Index, offsetBy distance: Int) -> Index { + index(i, offsetBy: distance, in: UTF16Metric()) + } + + func utf8Index(_ i: Index, offsetBy distance: Int) -> Index { + let offset = i._utf8Offset + distance + precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") + return Index(_utf8Offset: offset) + } +} + +extension _BString { + func characterIndex(after i: Index) -> Index { + index(i, offsetBy: 1, in: CharacterMetric()) + } + + func unicodeScalarIndex(after i: Index) -> Index { + index(i, offsetBy: 1, in: UnicodeScalarMetric()) + } + + func utf16Index(after i: Index) -> Index { + index(i, offsetBy: 1, in: UTF16Metric()) + } + + func utf8Index(after i: Index) -> Index { + let offset = i._utf8Offset + 1 + precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") + return Index(_utf8Offset: offset) + } +} + +extension _BString { + func characterIndex(before i: Index) -> Index { + index(i, offsetBy: -1, in: CharacterMetric()) + } + + func unicodeScalarIndex(before i: Index) -> Index { + index(i, offsetBy: -1, in: UnicodeScalarMetric()) + } + + func utf16Index(before i: Index) -> Index { + index(i, offsetBy: -1, in: UTF16Metric()) + } + + func utf8Index(before i: Index) -> Index { + let offset = i._utf8Offset - 1 + precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") + return Index(_utf8Offset: offset) + } +} + +extension _BString { + func characterIndex(roundingDown i: Index) -> Index { + let offset = i._utf8Offset - 1 + precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") + guard offset > 0, offset < utf8Count else { return Index(_utf8Offset: offset) } + + let (path, chunk) = path(to: i, preferEnd: true) + var base = baseIndex(with: i, at: path.chunk) + if chunk.hasBreaks { + let first = chunk.firstBreak + let last = chunk.lastBreak + if path.chunk == first || path.chunk == last { + return i + } + if path.chunk > chunk.lastBreak { + return base._advanceUTF8(by: chunk.string._utf8Offset(of: chunk.lastBreak)) + } + if path.chunk > chunk.firstBreak { + let j = chunk.string._index(roundingDown: path.chunk) + return base._advanceUTF8(by: chunk.string._utf8Offset(of: j)) + } + } + + var it = self.rope.makeIterator(from: path.rope) + while it.stepBackward() { + base = base._advanceUTF8(by: -it.current.utf8Count) + if it.current.hasBreaks { break } + } + return base._advanceUTF8(by: it.current.string._utf8Offset(of: it.current.lastBreak)) + } + + func unicodeScalarIndex(roundingDown i: Index) -> Index { + precondition(i <= endIndex, "Index out of bounds") + guard i > startIndex, i < endIndex else { return Index(_utf8Offset: i._utf8Offset) } + let (path, chunk) = path(to: i, preferEnd: true) + let j = chunk.string.unicodeScalars._index(roundingDown: path.chunk) + return i._advanceUTF8(by: j._utf8Offset - path.chunk._utf8Offset) + } + + func utf8Index(roundingDown i: Index) -> Index { + precondition(i <= endIndex, "Index out of bounds") + // Clear any UTF-16 offset + return Index(_utf8Offset: i._utf8Offset) + } + + func utf16Index(roundingDown i: Index) -> Index { + if i._utf16Delta > 0 { + precondition(i <= endIndex, "Index out of bounds") + return i + } + return unicodeScalarIndex(roundingDown: i) + } +} + +extension _BString { + func _character( + at start: Path, base: Index?, in chunk: Chunk + ) -> (character: Character, end: Path, base: Index?) { + let offset = chunk.string._utf8Offset(of: start.chunk) + let c = chunk.string[start.chunk] + let d = c.utf8.count + if offset + d < chunk.utf8Count { + return ( + character: c, + end: Path(start.rope, chunk.string._utf8Index(at: offset + d)), + base: base) + } + var s = String(c) + var base = base + var it = self.rope.makeIterator(from: start.rope) + while true { + base = base?._advanceUTF8(by: it.current.utf8Count) + guard it.stepForward() else { break } + let chunk = it.current + s.append(contentsOf: chunk.prefix) + if chunk.hasBreaks { break } + } + return (Character(s), Path(it.index, it.current.firstBreak), base) + } + + subscript(utf8 index: Index) -> UInt8 { + precondition(index < endIndex, "Index out of bounds") + let (path, chunk) = path(to: index, preferEnd: false) + return chunk.string.utf8[path.chunk] + } + + subscript(utf16 index: Index) -> UInt16 { + precondition(index < endIndex, "Index out of bounds") + let (path, chunk) = path(to: index, preferEnd: false) + return chunk.string.utf16[path.chunk] + } + + subscript(character index: Index) -> Character { + precondition(index < endIndex, "Index out of bounds") + let (path, chunk) = path(to: index, preferEnd: false) + let base = baseIndex(with: index, at: path.chunk) + return _character(at: path, base: base, in: chunk).character + } + + subscript(character offset: Int) -> Character { + let (path, chunk) = _path(startIndex, offsetBy: offset, in: CharacterMetric()) + return _character(at: path, base: nil, in: chunk).character + } + + subscript(unicodeScalar index: Index) -> Unicode.Scalar { + precondition(index < endIndex, "Index out of bounds") + let (path, chunk) = path(to: index, preferEnd: false) + return chunk.string.unicodeScalars[path.chunk] + } + + subscript(unicodeScalar offset: Int) -> Unicode.Scalar { + precondition(offset >= 0 && offset < unicodeScalarCount, "Offset out of bounds") + let (path, chunk) = _path(startIndex, offsetBy: offset, in: UnicodeScalarMetric()) + return chunk.string.unicodeScalars[path.chunk] + } +} diff --git a/Sources/RopeModule/BString/Basics/_BString+Debugging.swift b/Sources/RopeModule/BString/Basics/_BString+Debugging.swift new file mode 100644 index 00000000..bd31783d --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString+Debugging.swift @@ -0,0 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + func dump(heightLimit: Int = .max) { + rope.dump(heightLimit: heightLimit) + } +} diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift new file mode 100644 index 00000000..21e00106 --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -0,0 +1,96 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + internal struct Index { + // The layout is similar to (and somewhat compatible with) String.Index. + // ┌──────────┬────────────────┬───────────────────────┐ + // │ b63:b16 │ b15:b14 │ b13:b0 │ + // ├──────────┼────────────────┼───────────────────────┤ + // │ position │ transc. offset │ reserved │ + // └──────────┴────────────────┴───────────────────────┘ + + internal var _rawBits: UInt64 + + internal init(_raw: UInt64) { + self._rawBits = _raw + } + } +} + +extension _BString.Index { + @inline(__always) + internal var _orderingValue: UInt64 { + _rawBits &>> 14 + } +} + +extension _BString.Index: Equatable { + internal static func ==(left: Self, right: Self) -> Bool { + left._orderingValue == right._orderingValue + } +} + +extension _BString.Index: Comparable { + internal static func <(left: Self, right: Self) -> Bool { + left._orderingValue < right._orderingValue + } +} + +extension _BString.Index: Hashable { + internal func hash(into hasher: inout Hasher) { + hasher.combine(_orderingValue) + } +} + +extension _BString.Index: CustomStringConvertible { + internal var description: String { + let offset = _utf16Delta == 0 ? "" : "+\(_utf16Delta)" + return "\(_utf8Offset)[utf8]\(offset)" + } +} + +extension _BString.Index { + @inline(__always) + internal static func _bitsForUTF8Offset(_ utf8Offset: Int) -> UInt64 { + let v = UInt64(truncatingIfNeeded: UInt(bitPattern: utf8Offset)) + assert(v &>> 48 == 0) + return v &<< 16 + } + + @inline(__always) + internal static func _bitsForUTF16Delta(_ utf16Delta: Int) -> UInt64 { + let v = UInt64(truncatingIfNeeded: UInt(bitPattern: utf16Delta)) + assert(v == v & 1) + return (v & 1) &<< 14 + } + + internal init(_utf8Offset: Int) { + _rawBits = Self._bitsForUTF8Offset(_utf8Offset) + } + + internal init(_utf8Offset: Int, utf16Delta: Int) { + _rawBits = Self._bitsForUTF8Offset(_utf8Offset) + _rawBits |= Self._bitsForUTF16Delta(utf16Delta) + } + + internal var _utf8Offset: Int { + Int(truncatingIfNeeded: _rawBits &>> 16) + } + + internal var _utf16Delta: Int { + Int(truncatingIfNeeded: _orderingValue & 0x3) + } + + internal func _advanceUTF8(by delta: Int) -> Self { + Self(_utf8Offset: _utf8Offset + delta) + } +} diff --git a/Sources/RopeModule/BString/Basics/_BString+Ingester.swift b/Sources/RopeModule/BString/Basics/_BString+Ingester.swift new file mode 100644 index 00000000..38f2faf4 --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString+Ingester.swift @@ -0,0 +1,159 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + func ingester( + forInserting input: __owned Substring, + at index: Index, + allowForwardPeek: Bool + ) -> (ingester: Ingester, start: Path, end: Path) { + let hint = allowForwardPeek ? input.unicodeScalars.first : nil + let r = self._breakState(upTo: index, nextScalarHint: hint) + return (Ingester(input, startState: r.state), r.start, r.end) + } +} + +extension _BString { + struct Ingester { + typealias Chunk = _BString.Chunk + typealias Counts = _BString.Chunk.Counts + + var input: Substring + + /// The index of the beginning of the next chunk. + var start: String.Index + + /// Grapheme breaking state at the start of the next chunk. + var state: _CharacterRecognizer + + init(_ input: Substring) { + self.input = input + self.start = input.startIndex + self.state = _CharacterRecognizer() + } + + init(_ input: Substring, startState: __owned _CharacterRecognizer) { + self.input = input + self.start = input.startIndex + self.state = startState + } + + init(_ input: String) { + self.init(input[...]) + } + + init(_ input: S) { + self.init(Substring(input)) + } + + var isAtEnd: Bool { + start == input.endIndex + } + + var remainingUTF8: Int { + input.utf8.distance(from: start, to: input.endIndex) + } + + mutating func nextSlice( + maxUTF8Count: Int = Chunk.maxUTF8Count + ) -> Chunk.Slice? { + guard let range = input.base._nextSlice( + after: start, limit: input.endIndex, maxUTF8Count: maxUTF8Count) + else { + assert(start == input.endIndex) + return nil + } + if range.isEmpty { + return nil // Not enough room. + } + assert(range.lowerBound == start && range.upperBound <= input.endIndex) + start = range.upperBound + + var s = input[range] + let c8 = s.utf8.count + guard let r = state.firstBreak(in: s) else { + // Anomalous case -- chunk is entirely a continuation of a single character. + return ( + string: s, + characters: 0, + prefix: c8, + suffix: c8) + } + let first = r.lowerBound + s = s.suffix(from: r.upperBound) + + var characterCount = 1 + var last = first + while let r = state.firstBreak(in: s) { + last = r.lowerBound + s = s.suffix(from: r.upperBound) + characterCount += 1 + } + let prefixCount = input.utf8.distance(from: range.lowerBound, to: first) + let suffixCount = input.utf8.distance(from: last, to: range.upperBound) + return ( + string: input[range], + characters: characterCount, + prefix: prefixCount, + suffix: suffixCount) + } + + mutating func nextChunk(maxUTF8Count: Int = Chunk.maxUTF8Count) -> Chunk? { + guard let slice = nextSlice(maxUTF8Count: maxUTF8Count) else { return nil } + return Chunk(slice) + } + + static func desiredNextChunkSize(remaining: Int) -> Int { + if remaining <= Chunk.maxUTF8Count { + return remaining + } + if remaining >= Chunk.maxUTF8Count + Chunk.minUTF8Count { + return Chunk.maxUTF8Count + } + return remaining - Chunk.minUTF8Count + } + + mutating func nextWellSizedSlice(suffix: Int = 0) -> Chunk.Slice? { + let desired = Self.desiredNextChunkSize(remaining: remainingUTF8 + suffix) + return nextSlice(maxUTF8Count: desired) + } + + mutating func nextWellSizedChunk(suffix: Int = 0) -> Chunk? { + guard let slice = nextWellSizedSlice(suffix: suffix) else { return nil } + return Chunk(slice) + } + } +} + +extension String { + func _nextSlice( + after i: Index, + limit: Index, + maxUTF8Count: Int + ) -> Range? { + assert(maxUTF8Count >= 0) + assert(i._isScalarAligned) + guard i < limit else { return nil } + let end = self.utf8.index(i, offsetBy: maxUTF8Count, limitedBy: limit) ?? limit + let j = self.unicodeScalars._index(roundingDown: end) + return Range(uncheckedBounds: (i, j)) + } +} + +extension _BString.Chunk { + init(_ string: String) { + guard !string.isEmpty else { self.init(); return } + assert(string.utf8.count <= Self.maxUTF8Count) + var ingester = _BString.Ingester(string) + self = ingester.nextChunk()! + assert(ingester.isAtEnd) + } +} diff --git a/Sources/RopeModule/BString/Basics/_BString+Invariants.swift b/Sources/RopeModule/BString/Basics/_BString+Invariants.swift new file mode 100644 index 00000000..0360d819 --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString+Invariants.swift @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + func invariantCheck() { +#if DEBUG + rope.invariantCheck() + let allowUndersize = rope.isSingleton + + var state = _CharacterRecognizer() + for chunk in rope { + precondition(allowUndersize || !chunk.isUndersized, "Undersized chunk") + let (characters, prefix, suffix) = state.edgeCounts(consuming: chunk.string) + precondition( + chunk.prefixCount == prefix, + "Inconsistent position of first grapheme break in chunk") + precondition( + chunk.suffixCount == suffix, + "Inconsistent position of last grapheme break in chunk") + precondition( + chunk.characterCount == characters, + "Inconsistent character count in chunk") + } +#endif + } +} diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift new file mode 100644 index 00000000..fbbd6ef4 --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -0,0 +1,168 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + struct ChunkIterator { + var base: Rope.Iterator + + init(base: Rope.Iterator) { + self.base = base + } + } + + func makeChunkIterator() -> ChunkIterator { + ChunkIterator(base: rope.makeIterator()) + } +} + +extension _BString.ChunkIterator: IteratorProtocol { + typealias Element = String + + mutating func next() -> String? { + base.next()?.string + } +} + +extension _BString { + internal struct UTF8Iterator { + internal var _rope: Rope.Iterator + internal var _chunk: String.UTF8View.Iterator + + internal init(_base: Rope.Iterator) { + self._rope = _base + let str = self._rope.next()?.string ?? "" + self._chunk = str.utf8.makeIterator() + } + } + + internal func makeUTF8Iterator() -> UTF8Iterator { + UTF8Iterator(_base: self.rope.makeIterator()) + } +} + +extension _BString.UTF8Iterator: IteratorProtocol { + internal typealias Element = UInt8 + + internal mutating func next() -> UInt8? { + if let codeUnit = _chunk.next() { + return codeUnit + } + guard let chunk = _rope.next() else { return nil } + _chunk = chunk.string.utf8.makeIterator() + return _chunk.next()! + } +} + +extension _BString { + internal struct UTF16Iterator { + internal var _rope: Rope.Iterator + internal var _chunk: String.UTF16View.Iterator + + internal init(_base: Rope.Iterator) { + self._rope = _base + let str = self._rope.next()?.string ?? "" + self._chunk = str.utf16.makeIterator() + } + } + + internal func makeUTF16Iterator() -> UTF16Iterator { + UTF16Iterator(_base: self.rope.makeIterator()) + } +} + +extension _BString.UTF16Iterator: IteratorProtocol { + internal typealias Element = UInt16 + + internal mutating func next() -> UInt16? { + if let codeUnit = _chunk.next() { + return codeUnit + } + guard let chunk = _rope.next() else { return nil } + _chunk = chunk.string.utf16.makeIterator() + return _chunk.next()! + } +} + +extension _BString { + internal struct UnicodeScalarIterator { + internal var _rope: Rope.Iterator + internal var _chunk: String.UnicodeScalarView.Iterator + + internal init(_base: Rope.Iterator) { + self._rope = _base + let str = self._rope.next()?.string ?? "" + self._chunk = str.unicodeScalars.makeIterator() + } + } + + internal func makeUnicodeScalarIterator() -> UnicodeScalarIterator { + UnicodeScalarIterator(_base: self.rope.makeIterator()) + } +} + +extension _BString.UnicodeScalarIterator: IteratorProtocol { + internal typealias Element = Unicode.Scalar + + internal mutating func next() -> Unicode.Scalar? { + if let scalar = _chunk.next() { + return scalar + } + guard let chunk = _rope.next() else { return nil } + _chunk = chunk.string.unicodeScalars.makeIterator() + return _chunk.next()! + } +} + +extension _BString { + internal struct CharacterIterator { + internal var _base: _Rope.Iterator + internal var _str: Substring + + internal init(_base: _Rope.Iterator) { + self._base = _base + if let chunk = self._base.next() { + assert(chunk.firstBreak == chunk.string.startIndex) + self._str = chunk.wholeCharacters + } else { + self._str = "" + } + } + } + + internal func makeCharacterIterator() -> CharacterIterator { + CharacterIterator(_base: rope.makeIterator()) + } +} + +extension _BString.CharacterIterator: IteratorProtocol { + internal typealias Element = Character + + internal mutating func next() -> Character? { + guard !_str.isEmpty else { return nil } + + let j = _str.index(after: _str.startIndex) + var result = String(_str[.. Int + + func formIndex( + _ i: inout String.Index, + offsetBy distance: inout Int, + in chunk: _BString.Chunk + ) -> (found: Bool, forward: Bool) +} + +extension _BString { + internal struct CharacterMetric: _StringMetric { + typealias Element = _BString.Chunk + typealias Summary = _BString.Summary + + @inline(__always) + func size(of summary: Summary) -> Int { + summary.characters + } + + func distance( + from start: String.Index, + to end: String.Index, + in chunk: _BString.Chunk + ) -> Int { + chunk.characterDistance(from: start, to: end) + } + + func formIndex( + _ i: inout String.Index, + offsetBy distance: inout Int, + in chunk: _BString.Chunk + ) -> (found: Bool, forward: Bool) { + chunk.formCharacterIndex(&i, offsetBy: &distance) + } + + func index(at offset: Int, in chunk: _BString.Chunk) -> String.Index { + precondition(offset < chunk.characterCount) + return chunk.wholeCharacters._index(at: offset) + } + } + + internal struct UnicodeScalarMetric: _StringMetric { + @inline(__always) + func size(of summary: Summary) -> Int { + summary.unicodeScalars + } + + func distance( + from start: String.Index, + to end: String.Index, + in chunk: _BString.Chunk + ) -> Int { + chunk.string.unicodeScalars.distance(from: start, to: end) + } + + func formIndex( + _ i: inout String.Index, + offsetBy distance: inout Int, + in chunk: _BString.Chunk + ) -> (found: Bool, forward: Bool) { + guard distance != 0 else { + i = chunk.string.unicodeScalars._index(roundingDown: i) + return (true, false) + } + if distance > 0 { + let end = chunk.string.endIndex + while distance > 0, i < end { + chunk.string.unicodeScalars.formIndex(after: &i) + distance &-= 1 + } + return (distance == 0, true) + } + let start = chunk.string.startIndex + while distance < 0, i > start { + chunk.string.unicodeScalars.formIndex(before: &i) + distance &+= 1 + } + return (distance == 0, false) + } + + func index(at offset: Int, in chunk: _BString.Chunk) -> String.Index { + chunk.string.unicodeScalars.index(chunk.string.startIndex, offsetBy: offset) + } + } + + internal struct UTF8Metric: _StringMetric { + @inline(__always) + func size(of summary: Summary) -> Int { + summary.utf8 + } + + func distance( + from start: String.Index, + to end: String.Index, + in chunk: _BString.Chunk + ) -> Int { + chunk.string.utf8.distance(from: start, to: end) + } + + func formIndex( + _ i: inout String.Index, + offsetBy distance: inout Int, + in chunk: _BString.Chunk + ) -> (found: Bool, forward: Bool) { + // Here we make use of the fact that the UTF-8 view of native Swift strings + // have O(1) index distance & offset calculations. + let offset = chunk.string.utf8.distance(from: chunk.string.startIndex, to: i) + if distance >= 0 { + let rest = chunk.utf8Count - offset + if distance > rest { + i = chunk.string.endIndex + distance -= rest + return (false, true) + } + i = chunk.string.utf8.index(i, offsetBy: distance) + distance = 0 + return (true, true) + } + + if offset + distance < 0 { + i = chunk.string.startIndex + distance += offset + return (false, false) + } + i = chunk.string.utf8.index(i, offsetBy: distance) + distance = 0 + return (true, false) + } + + func index(at offset: Int, in chunk: _BString.Chunk) -> String.Index { + chunk.string.utf8.index(chunk.string.startIndex, offsetBy: offset) + } + } + + internal struct UTF16Metric: _StringMetric { + @inline(__always) + func size(of summary: Summary) -> Int { + summary.utf16 + } + + func distance( + from start: String.Index, + to end: String.Index, + in chunk: _BString.Chunk + ) -> Int { + chunk.string.utf16.distance(from: start, to: end) + } + + func formIndex( + _ i: inout String.Index, + offsetBy distance: inout Int, + in chunk: _BString.Chunk + ) -> (found: Bool, forward: Bool) { + if distance >= 0 { + if + distance <= chunk.utf16Count, + let r = chunk.string.utf16.index( + i, offsetBy: distance, limitedBy: chunk.string.endIndex + ) { + i = r + distance = 0 + return (true, true) + } + distance -= chunk.string.utf16.distance(from: i, to: chunk.string.endIndex) + i = chunk.string.endIndex + return (false, true) + } + + if + distance.magnitude <= chunk.utf16Count, + let r = chunk.string.utf16.index( + i, offsetBy: distance, limitedBy: chunk.string.endIndex + ) { + i = r + distance = 0 + return (true, true) + } + distance += chunk.string.utf16.distance(from: chunk.string.startIndex, to: i) + i = chunk.string.startIndex + return (false, false) + } + + func index(at offset: Int, in chunk: _BString.Chunk) -> String.Index { + chunk.string.utf16.index(chunk.string.startIndex, offsetBy: offset) + } + } +} diff --git a/Sources/RopeModule/BString/Basics/_BString+Path.swift b/Sources/RopeModule/BString/Basics/_BString+Path.swift new file mode 100644 index 00000000..abcb3730 --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString+Path.swift @@ -0,0 +1,85 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + struct Path { + var rope: Rope.Index + var _chunk: UInt16 + + init(startOf rope: Rope.Index) { + self.rope = rope + self._chunk = 0 + } + + init(_ rope: Rope.Index, _ chunk: String.Index) { + self.rope = rope + self._chunk = chunk._chunkData + } + + var chunk: String.Index { + get { + String.Index(_chunkData: _chunk) + } + set { + _chunk = newValue._chunkData + } + _modify { + var index = self.chunk + defer { + self.chunk = index + } + yield &index + } + } + } +} + +extension _BString.Path: CustomStringConvertible { + var description: String { + "\(rope).\(chunk._description)" + } +} + +extension _BString { + func path( + to i: Index, + preferEnd: Bool + ) -> (path: Path, chunk: Chunk) { + let r = rope.find(at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) + return r.node!.readLeaf { + let slot = r.index[height: 0] + let index = $0.children[slot].value.index(at: r.remaining, utf16Delta: i._utf16Delta) + return (Path(r.index, index), $0.children[slot].value) + } + } +} + +extension _BString { + func baseIndex( + with index: Index, + at chunkIndex: String.Index + ) -> Index { + Index(_utf8Offset: index._utf8Offset - chunkIndex._utf8Offset) + } + + func index(base: Index, offsetBy index: String.Index) -> Index { + assert(index._canBeUTF8) + return Index( + _utf8Offset: base._utf8Offset + index._utf8Offset, + utf16Delta: index._utf16Delta) + } + + func index(of path: Path) -> Index { + let position = rope.distance(from: rope.startIndex, to: path.rope, in: UTF8Metric()) + let base = Index(_utf8Offset: position) + return index(base: base, offsetBy: path.chunk) + } +} diff --git a/Sources/RopeModule/BString/Basics/_BString+Summary.swift b/Sources/RopeModule/BString/Basics/_BString+Summary.swift new file mode 100644 index 00000000..8720894d --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString+Summary.swift @@ -0,0 +1,69 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + struct Summary { + // FIXME: We only need 48 * 3 = 192 bits to represent a nonnegative value; pack these better + // (Unfortunately we also need to represent negative values right now.) + private(set) var characters: Int + private(set) var unicodeScalars: Int + private(set) var utf16: Int + private(set) var utf8: Int + + init() { + characters = 0 + unicodeScalars = 0 + utf16 = 0 + utf8 = 0 + } + + init(_ chunk: _BString.Chunk) { + self.utf8 = chunk.utf8Count + self.utf16 = Int(chunk.counts.utf16) + self.unicodeScalars = Int(chunk.counts.unicodeScalars) + self.characters = Int(chunk.counts.characters) + } + } +} + +extension _BString.Summary: CustomStringConvertible { + var description: String { + "❨\(utf8)⋅\(utf16)⋅\(unicodeScalars)⋅\(characters)❩" + } +} + +extension _BString.Summary: _RopeSummary { + @inline(__always) + static var maxNodeSize: Int { 10 } + + @inline(__always) + static var nodeSizeBitWidth: Int { 4 } + + @inline(__always) + static var zero: Self { Self() } + + @inline(__always) + var isZero: Bool { utf8 == 0 } + + mutating func add(_ other: _BString.Summary) { + characters += other.characters + unicodeScalars += other.unicodeScalars + utf16 += other.utf16 + utf8 += other.utf8 + } + + mutating func subtract(_ other: _BString.Summary) { + characters -= other.characters + unicodeScalars -= other.unicodeScalars + utf16 -= other.utf16 + utf8 -= other.utf8 + } +} diff --git a/Sources/RopeModule/BString/Basics/_BString.swift b/Sources/RopeModule/BString/Basics/_BString.swift new file mode 100644 index 00000000..056d6de0 --- /dev/null +++ b/Sources/RopeModule/BString/Basics/_BString.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 +// +//===----------------------------------------------------------------------===// + +/// The core of a B-tree based String implementation. +internal struct _BString: Sendable { + typealias Rope = _Rope + + var rope: Rope + + internal init() { + rope = Rope() + } + + internal init(rope: Rope) { + self.rope = rope + } +} diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift new file mode 100644 index 00000000..5aa80c8b --- /dev/null +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift @@ -0,0 +1,168 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString.Chunk { + mutating func append(_ other: __owned Self) { + self._append(other.string[...], other.counts) + } + + mutating func append(from ingester: inout _BString.Ingester) -> Self? { + let desired = _BString.Ingester.desiredNextChunkSize( + remaining: self.utf8Count + ingester.remainingUTF8) + if desired == self.utf8Count { + return nil + } + if desired > self.utf8Count { + if let slice = ingester.nextSlice(maxUTF8Count: desired - self.utf8Count) { + self._append(slice) + } + return nil + } + + // Split current chunk. + let cut = string.unicodeScalars._index(roundingDown: string._utf8Index(at: desired)) + var new = self.split(at: cut) + precondition(!self.isUndersized) + let slice = ingester.nextSlice()! + new._append(slice) + precondition(ingester.isAtEnd) + precondition(!new.isUndersized) + return new + } + + mutating func _append(_ other: Slice) { + let c = Counts(other) + _append(other.string, c) + } + + mutating func _append(_ str: __owned Substring, _ other: Counts) { + self.counts.append(other) + self.string += str + invariantCheck() + } + + mutating func _prepend(_ other: Slice) { + let c = Counts(other) + _prepend(other.string, c) + } + + mutating func _prepend(_ str: __owned Substring, _ other: Counts) { + let c = self.counts + self.counts = other + self.counts.append(c) + self.string = str + self.string + invariantCheck() + } +} + +extension _BString.Chunk { + mutating func _insert( + _ slice: Slice, + at index: String.Index, + old: inout _CharacterRecognizer, + new: inout _CharacterRecognizer + ) -> String.Index? { + let offset = string._utf8Offset(of: index) + let count = slice.string.utf8.count + precondition(utf8Count + count <= Self.maxUTF8Count) + + let parts = self.splitCounts(at: index) + self.counts = parts.left + self.counts.append(Counts(slice)) + self.counts.append(parts.right) + + string.insert(contentsOf: slice.string, at: index) + + let end = string._utf8Index(at: offset + count) + return resyncBreaks(startingAt: end, old: &old, new: &new) + } + + typealias States = (increment: Int, old: _CharacterRecognizer, new: _CharacterRecognizer) + + mutating func insertAll( + from ingester: inout _BString.Ingester, + at index: String.Index + ) -> States? { + let remaining = ingester.remainingUTF8 + precondition(self.utf8Count + remaining <= Self.maxUTF8Count) + var startState = ingester.state + guard let slice = ingester.nextSlice(maxUTF8Count: remaining) else { return nil } + var endState = ingester.state + assert(ingester.isAtEnd) + let offset = string._utf8Offset(of: index) + if let _ = self._insert(slice, at: index, old: &startState, new: &endState) { + return nil + } + return (self.utf8Count - offset, startState, endState) + } + + enum InsertResult { + case inline(States?) + case split(spawn: _BString.Chunk, endStates: States?) + case large + } + + mutating func insert( + from ingester: inout _BString.Ingester, + at index: String.Index + ) -> InsertResult { + let origCount = self.utf8Count + let rem = ingester.remainingUTF8 + guard rem > 0 else { return .inline(nil) } + let sum = origCount + rem + + let offset = string._utf8Offset(of: index) + if sum <= Self.maxUTF8Count { + let r = insertAll(from: &ingester, at: index) + return .inline(r) + } + + let desired = _BString.Ingester.desiredNextChunkSize(remaining: sum) + guard sum - desired + Self.maxSlicingError <= Self.maxUTF8Count else { return .large } + + if desired <= offset { + // Inserted text lies entirely within `spawn`. + let cut = string.unicodeScalars._index(roundingDown: string._utf8Index(at: desired)) + var spawn = split(at: cut) + let i = spawn.string._utf8Index(at: offset - self.utf8Count) + let r = spawn.insertAll(from: &ingester, at: i) + assert(r == nil || r?.increment == sum - offset) + return .split(spawn: spawn, endStates: r) + } + if desired >= offset + rem { + // Inserted text lies entirely within `self`. + let cut = string.unicodeScalars._index(roundingDown: string._utf8Index(at: desired - rem)) + assert(cut >= index) + var spawn = split(at: cut) + guard + var r = self.insertAll(from: &ingester, at: string._utf8Index(at: offset)), + nil == spawn.resyncBreaks(startingAt: spawn.string.startIndex, old: &r.old, new: &r.new) + else { + return .split(spawn: spawn, endStates: nil) + } + return .split(spawn: spawn, endStates: (sum - offset, r.old, r.new)) + } + // Inserted text is split across `self` and `spawn`. + var spawn = split(at: index) + var old = ingester.state + if let slice = ingester.nextSlice(maxUTF8Count: desired - offset) { + self._append(slice) + } + let slice = ingester.nextSlice()! + assert(ingester.isAtEnd) + var new = ingester.state + let stop = spawn._insert(slice, at: spawn.string.startIndex, old: &old, new: &new) + if stop != nil { + return .split(spawn: spawn, endStates: nil) + } + return .split(spawn: spawn, endStates: (sum - offset, old, new)) + } +} diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift new file mode 100644 index 00000000..d184f3a6 --- /dev/null +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift @@ -0,0 +1,66 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString.Chunk { + @inline(__always) + var hasBreaks: Bool { counts.hasBreaks } + + var firstBreak: String.Index { + get { + string._utf8Index(at: prefixCount) + } + set { + counts.prefix = string._utf8Offset(of: newValue) + } + } + + var lastBreak: String.Index { + get { + string._utf8Index(at: utf8Count - suffixCount) + } + set { + counts.suffix = utf8Count - string._utf8Offset(of: newValue) + } + } + + var prefix: Substring { string[.. String.Index? { + let index = string.unicodeScalars._index(roundingDown: index) + let first = firstBreak + guard index > first else { return nil } + let last = lastBreak + guard index <= last else { return last } + let w = string[first...] + let rounded = w._index(roundingDown: index) + guard rounded == index else { return rounded } + return w.index(before: rounded) + } + + func immediateBreakState( + upTo index: String.Index + ) -> (prevBreak: String.Index, state: _CharacterRecognizer)? { + guard let prev = nearestBreak(before: index) else { return nil } + let state = _CharacterRecognizer(partialCharacter: string[prev..= Self.minUTF8Count, "Undersized chunk") + + precondition(counts.utf8 == string.utf8.count, "UTF-8 count mismatch") + precondition(counts.utf16 == string.utf16.count, "UTF-16 count mismatch") + precondition(counts.unicodeScalars == string.unicodeScalars.count, "Scalar count mismatch") + + precondition(counts.prefix <= c, "Invalid prefix count") + precondition(counts.suffix <= c && counts.suffix > 0, "Invalid suffix count") + if Int(counts.prefix) + Int(counts.suffix) <= c { + let i = firstBreak + let j = lastBreak + precondition(i <= j, "Overlapping prefix and suffix") + let s = string[i...] + precondition(counts.characters == s.count, "Inconsistent character count") + precondition(j == s.index(before: s.endIndex), "Inconsistent suffix count") + } else { + // Anomalous case + precondition(counts.prefix == c, "Inconsistent prefix count (continuation)") + precondition(counts.suffix == c, "Inconsistent suffix count (continuation)") + precondition(counts.characters == 0, "Inconsistent character count (continuation)") + } +#endif + } + + mutating func rebalance(nextNeighbor right: inout Self) -> Bool { + if self.isEmpty { + swap(&self, &right) + return true + } + guard !right.isEmpty else { return true } + guard self.isUndersized || right.isUndersized else { return false } + let sum = self.utf8Count + right.utf8Count + let desired = _BString.Ingester.desiredNextChunkSize(remaining: sum) + + precondition(desired != self.utf8Count) + if desired < self.utf8Count { + let i = self.string._utf8Index(at: desired) + let j = self.string.unicodeScalars._index(roundingDown: i) + Self._redistributeData(&self, &right, splittingLeftAt: j) + } else { + let i = right.string._utf8Index(at: desired - self.utf8Count) + let j = right.string.unicodeScalars._index(roundingDown: i) + Self._redistributeData(&self, &right, splittingRightAt: j) + } + assert(right.isEmpty || (!self.isUndersized && !right.isUndersized)) + return right.isEmpty + } + + mutating func rebalance(prevNeighbor left: inout Self) -> Bool { + if self.isEmpty { + swap(&self, &left) + return true + } + guard !left.isEmpty else { return true } + guard left.isUndersized || self.isUndersized else { return false } + let sum = left.utf8Count + self.utf8Count + let desired = _BString.Ingester.desiredNextChunkSize(remaining: sum) + + precondition(desired != self.utf8Count) + if desired < self.utf8Count { + let i = self.string._utf8Index(at: self.utf8Count - desired) + let j = self.string.unicodeScalars._index(roundingDown: i) + let k = (i == j ? i : self.string.unicodeScalars.index(after: j)) + Self._redistributeData(&left, &self, splittingRightAt: k) + } else { + let i = left.string._utf8Index(at: left.utf8Count + self.utf8Count - desired) + let j = left.string.unicodeScalars._index(roundingDown: i) + let k = (i == j ? i : left.string.unicodeScalars.index(after: j)) + Self._redistributeData(&left, &self, splittingLeftAt: k) + } + assert(left.isEmpty || (!left.isUndersized && !self.isUndersized)) + return left.isEmpty + } + + mutating func split(at i: String.Index) -> Self { + assert(i == string.unicodeScalars._index(roundingDown: i)) + let c = splitCounts(at: i) + let new = Self(string[i...], c.right) + self = Self(string[.. right.string.startIndex) + guard i < right.string.endIndex else { + left.append(right) + right.clear() + return + } + let counts = right.splitCounts(at: i) + left._append(right.string[.. left.string.startIndex else { + left.append(right) + right.clear() + swap(&left, &right) + return + } + let counts = left.splitCounts(at: i) + right._prepend(left.string[i...], counts.right) + left = Self(left.string[..= 0 && characters <= unicodeScalars && unicodeScalars <= utf16) + self.utf8 = utf8 + self.utf16 = utf16 + self.unicodeScalars = unicodeScalars + self._characters = characters + self._prefix = prefix + self._suffix = suffix + } + + init( + utf8: Int, + utf16: Int, + unicodeScalars: Int, + characters: Int, + prefix: Int, + suffix: Int + ) { + assert(characters >= 0 && characters <= unicodeScalars && unicodeScalars <= utf16) + self.utf8 = UInt8(utf8) + self.utf16 = UInt8(utf16) + self.unicodeScalars = UInt8(unicodeScalars) + self._characters = UInt8(characters) + self._prefix = UInt8(prefix) + self._suffix = UInt8(suffix) + } + + init( + anomalousUTF8 utf8: Int, + utf16: Int, + unicodeScalars: Int + ) { + self.utf8 = UInt8(utf8) + self.utf16 = UInt8(utf16) + self.unicodeScalars = UInt8(unicodeScalars) + self._characters = 0 + self._prefix = self.utf8 + self._suffix = self.utf8 + } + + init(_ slice: Slice) { + let c = slice.string.utf8.count + precondition(c <= _BString.Chunk.maxUTF8Count) + self.init( + utf8: slice.string.utf8.count, + utf16: slice.string.utf16.count, + unicodeScalars: slice.string.unicodeScalars.count, + characters: slice.characters, + prefix: slice.prefix, + suffix: slice.suffix) + } + } +} + +extension _BString.Chunk.Counts { + var characters: Int { + get { Int(_characters) } + set { _characters = UInt8(newValue) } + } + + var prefix: Int { + get { Int(_prefix) } + set { _prefix = UInt8(newValue) } + } + + var suffix: Int { + get { Int(_suffix) } + set { _suffix = UInt8(newValue) } + } + + var hasBreaks: Bool { + _prefix < utf8 + } + + func hasSpaceToMerge(_ other: Self) -> Bool { + Int(utf8) + Int(other.utf8) <= _BString.Chunk.maxUTF8Count + } +} + +extension _BString.Chunk.Counts { + mutating func append(_ other: Self) { + assert(hasSpaceToMerge(other)) + + switch (self.hasBreaks, other.hasBreaks) { + case (true, true): + self._suffix = other._suffix + case (true, false): + self._suffix += other._suffix + case (false, true): + self._prefix += other._prefix + self._suffix = other._suffix + case (false, false): + self._prefix += other._prefix + self._suffix += other._suffix + } + self.utf8 += other.utf8 + self.utf16 += other.utf16 + self.unicodeScalars += other.unicodeScalars + self._characters += other._characters + } +} + diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift new file mode 100644 index 00000000..89ba9ec4 --- /dev/null +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift @@ -0,0 +1,67 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString.Chunk: CustomStringConvertible { + var description: String { + let counts = """ + ❨\(utf8Count)⋅\(utf16Count)⋅\(unicodeScalarCount)⋅\(characterCount)❩ + """._rpad(to: 17) + let d = _succinctContents(maxLength: 10) + return "Chunk(\(_identity)\(counts) \(d))" + } + + var _identity: String { +#if arch(arm64) || arch(x86_64) + // Let's use the second word of the string representation as the identity; it contains + // the String's storage reference (if any). + let b = unsafeBitCast(self.string, to: (UInt64, UInt64).self) + return "@" + String(b.1, radix: 16)._rpad(to: 17) +#else + return "" +#endif + } + + func _succinctContents(maxLength c: Int) -> String { + /// 4+"short"-1 + /// 0+"longer...tring"-1 + let pc = String(prefixCount)._lpad(to: 3) + let sc = String(suffixCount) + + let s = String(wholeCharacters) + if s.isEmpty { + return "\(pc)+...-\(sc)" + } + var result = "\(pc)+\"" + var state = _CharacterRecognizer(consuming: result) + + let i = result._appendQuotedProtectingLeft(s, with: &state, maxLength: c) + let j = s.index(s.endIndex, offsetBy: -c, limitedBy: string.startIndex) ?? string.startIndex + + if i < j { + result._appendProtectingRight("...", with: &state) + result._appendQuotedProtectingLeft(String(s[j...]), with: &state) + } else if i < s.endIndex { + let k = s._index(roundingDown: i) + if i == k { + result._appendQuotedProtectingLeft(String(s[i...]), with: &state) + } else if s.index(after: k) < s.endIndex { + result._appendProtectingRight("...", with: &state) + result._appendQuotedProtectingLeft(String(s[s.index(after: k)...]), with: &state) + } else { + let suffix = String(s[i...].unicodeScalars.suffix(3)) + result._appendProtectingRight("...", with: &state) + result._appendQuotedProtectingLeft(suffix, with: &state) + } + } + result._appendProtectingRight("\"-\(sc)", with: &state) + return result + } +} diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift new file mode 100644 index 00000000..a7a59264 --- /dev/null +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift @@ -0,0 +1,106 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension UInt8 { + /// Returns true if this is a leading code unit in the UTF-8 encoding of a Unicode scalar that + /// is outside the BMP. + var _isUTF8NonBMPLeadingCodeUnit: Bool { self >= 0b11110000 } +} + +extension _BString.Chunk { + func characterDistance(from start: String.Index, to end: String.Index) -> Int { + let firstBreak = self.firstBreak + let (start, a) = start < firstBreak ? (firstBreak, 1) : (start, 0) + let (end, b) = end < firstBreak ? (firstBreak, 1) : (end, 0) + let d = wholeCharacters.distance(from: start, to: end) + return d + a - b + } + + /// If this returns false, the next position is on the first grapheme break following this + /// chunk. + func formCharacterIndex(after i: inout String.Index) -> Bool { + if i >= lastBreak { + i = string.endIndex + return false + } + let first = firstBreak + if i < first { + i = first + return true + } + wholeCharacters.formIndex(after: &i) + return true + } + + /// If this returns false, the right position is `distance` steps from the first grapheme break + /// following this chunk if `distance` was originally positive. Otherwise the right position is + /// `-distance` steps from the first grapheme break preceding this chunk. + func formCharacterIndex( + _ i: inout String.Index, offsetBy distance: inout Int + ) -> (found: Bool, forward: Bool) { + if distance == 0 { + if i < firstBreak { + i = string.startIndex + return (false, false) + } + if i >= lastBreak { + i = lastBreak + return (true, false) + } + i = wholeCharacters._index(roundingDown: i) + return (true, false) + } + if distance > 0 { + if i >= lastBreak { + i = string.endIndex + distance -= 1 + return (false, true) + } + if i < firstBreak { + i = firstBreak + distance -= 1 + if distance == 0 { return (true, true) } + } + if + distance <= characterCount, + let r = wholeCharacters.index(i, offsetBy: distance, limitedBy: string.endIndex) + { + i = r + distance = 0 + return (i < string.endIndex, true) + } + distance -= wholeCharacters.distance(from: i, to: lastBreak) + 1 + i = string.endIndex + return (false, true) + } + if i <= firstBreak { + i = string.startIndex + if i == firstBreak { distance += 1 } + return (false, false) + } + if i > lastBreak { + i = lastBreak + distance += 1 + if distance == 0 { return (true, false) } + } + if + distance.magnitude <= characterCount, + let r = self.wholeCharacters.index(i, offsetBy: distance, limitedBy: firstBreak) + { + i = r + distance = 0 + return (true, false) + } + distance += self.wholeCharacters.distance(from: firstBreak, to: i) + i = string.startIndex + return (false, false) + } +} diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift new file mode 100644 index 00000000..a5a1f509 --- /dev/null +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift @@ -0,0 +1,26 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString.Chunk { + /// UTF-16 index lookup. + func index(at utf8Offset: Int, utf16Delta: Int) -> String.Index { + var index = string._utf8Index(at: utf8Offset) + if + utf16Delta != 0, + index < string.endIndex, + string.utf8[index]._isUTF8NonBMPLeadingCodeUnit + { + assert(utf16Delta == 1) + index = string.utf16.index(after: index) + } + return index + } +} diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift new file mode 100644 index 00000000..d4af04a9 --- /dev/null +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift @@ -0,0 +1,144 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString.Chunk { + func splitCounts(at i: String.Index) -> (left: Counts, right: Counts) { + precondition(i <= string.endIndex) + guard i < string.endIndex else { + return (self.counts, Counts()) + } + guard i > string.startIndex else { + return (Counts(), self.counts) + } + let i = string.unicodeScalars._index(roundingDown: i) + + let leftUTF16: Int + let leftScalars: Int + let rightUTF16: Int + let rightScalars: Int + if string._utf8Offset(of: i) <= utf8Count / 2 { + leftUTF16 = string.utf16.distance(from: string.startIndex, to: i) + rightUTF16 = self.utf16Count - leftUTF16 + leftScalars = string.unicodeScalars.distance(from: string.startIndex, to: i) + rightScalars = self.unicodeScalarCount - leftScalars + } else { + rightUTF16 = string.utf16.distance(from: i, to: string.endIndex) + leftUTF16 = self.utf16Count - rightUTF16 + rightScalars = string.unicodeScalars.distance(from: i, to: string.endIndex) + leftScalars = self.unicodeScalarCount - rightScalars + } + + let left = _counts(upTo: i, utf16: leftUTF16, scalars: leftScalars) + let right = _counts(from: i, utf16: rightUTF16, scalars: rightScalars) + + assert(left.utf8 + right.utf8 == self.counts.utf8) + assert(left.utf16 + right.utf16 == self.counts.utf16) + assert(left.unicodeScalars + right.unicodeScalars == self.counts.unicodeScalars) + assert(left.characters + right.characters == self.counts.characters) + return (left, right) + } + + func counts(upTo i: String.Index) -> Counts { + precondition(i <= string.endIndex) + let i = string.unicodeScalars._index(roundingDown: i) + guard i > string.startIndex else { return Counts() } + guard i < string.endIndex else { return self.counts } + + let utf16 = string.utf16.distance(from: string.startIndex, to: i) + let scalars = string.unicodeScalars.distance(from: string.startIndex, to: i) + return _counts(from: i, utf16: utf16, scalars: scalars) + } + + func _counts(upTo i: String.Index, utf16: Int, scalars: Int) -> Counts { + assert(i > string.startIndex && i < string.endIndex) + let s = string[.. lastBreak { + result._characters = self.counts._characters + result._prefix = self.counts._prefix + result._suffix = self.counts._suffix - (self.counts.utf8 - result.utf8) + } else { // i > firstBreak, i <= lastBreak + result._prefix = self.counts._prefix + let wholeChars = string[firstBreak ..< i] + assert(!wholeChars.isEmpty) + var state = _CharacterRecognizer() + let (characters, _, last) = state.consume(wholeChars)! + result.characters = characters + result.suffix = string.utf8.distance(from: last, to: i) + } + return result + } + + func counts(from i: String.Index) -> Counts { + precondition(i <= string.endIndex) + let i = string.unicodeScalars._index(roundingDown: i) + guard i > string.startIndex else { return self.counts } + guard i < string.endIndex else { return Counts() } + + let utf16 = string.utf16.distance(from: i, to: string.endIndex) + let scalars = string.unicodeScalars.distance(from: i, to: string.endIndex) + return _counts(from: i, utf16: utf16, scalars: scalars) + } + + func _counts(from i: String.Index, utf16: Int, scalars: Int) -> Counts { + assert(i > string.startIndex && i < string.endIndex) + let s = string[i...] + + var result = Counts( + utf8: s.utf8.count, + utf16: utf16, + unicodeScalars: scalars, + characters: 0, + prefix: 0, + suffix: 0) + + let firstBreak = self.firstBreak + let lastBreak = self.lastBreak + + if i > lastBreak { + result._characters = 0 + result._prefix = result.utf8 + result._suffix = result.utf8 + } else if i <= firstBreak { + result._characters = self.counts._characters + result.prefix = self.counts.prefix - self.string._utf8Offset(of: i) + result._suffix = self.counts._suffix + } else { // i > firstBreak, i <= lastBreak + result._suffix = self.counts._suffix + let prevBreak = string[firstBreak..= i) + result.characters = characters + 1 + result.prefix = string.utf8.distance(from: i, to: first) + } else { + result.characters = 1 + result.prefix = string.utf8.distance(from: i, to: lastBreak) + } + } + return result + } +} diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift new file mode 100644 index 00000000..f318912d --- /dev/null +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift @@ -0,0 +1,114 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + struct Chunk { + typealias Slice = (string: Substring, characters: Int, prefix: Int, suffix: Int) + typealias Path = _BString.Path + + var string: String + var counts: Counts + + init() { + self.string = "" + self.counts = Counts() + } + + init(_ string: String, _ counts: Counts) { + self.string = string + self.counts = counts + invariantCheck() + } + + init(_ string: Substring, _ counts: Counts) { + self.string = String(string) + self.counts = counts + invariantCheck() + } + + init(_ slice: Slice) { + self.string = String(slice.string) + var slice = slice + slice.string = self.string[...] + self.counts = Counts(slice) + } + } +} + +extension _BString.Chunk { + @inline(__always) + static var maxUTF8Count: Int { 255 } + + @inline(__always) + static var minUTF8Count: Int { maxUTF8Count / 2 - maxSlicingError } + + @inline(__always) + static var maxSlicingError: Int { 3 } +} + +extension _BString.Chunk { + @inline(__always) + mutating func take() -> Self { + let r = self + self = Self() + return r + } + + @inline(__always) + mutating func modify( + _ body: (inout Self) -> R + ) -> R { + body(&self) + } +} + + +extension _BString.Chunk { + @inline(__always) + var characterCount: Int { counts.characters } + + @inline(__always) + var unicodeScalarCount: Int { Int(counts.unicodeScalars) } + + @inline(__always) + var utf16Count: Int { Int(counts.utf16) } + + @inline(__always) + var utf8Count: Int { Int(counts.utf8) } + + @inline(__always) + var prefixCount: Int { counts.prefix } + + @inline(__always) + var suffixCount: Int { counts.suffix } + + var firstScalar: UnicodeScalar { string.unicodeScalars.first! } + var lastScalar: UnicodeScalar { string.unicodeScalars.last! } +} + +extension _BString.Chunk { + var availableSpace: Int { Swift.max(0, Self.maxUTF8Count - utf8Count) } + + mutating func clear() { + string = "" + counts = Counts() + } +} + +extension _BString.Chunk { + func hasSpaceToMerge(_ other: some StringProtocol) -> Bool { + utf8Count + other.utf8.count <= Self.maxUTF8Count + } + + func hasSpaceToMerge(_ other: Self) -> Bool { + utf8Count + other.utf8Count <= Self.maxUTF8Count + } +} diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift new file mode 100644 index 00000000..8b423e7d --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift @@ -0,0 +1,153 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + func isIdentical(to other: Self) -> Bool { + self.rope.isIdentical(to: other.rope) + } +} + +extension _BString { + internal func characterIsEqual(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 + // 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 true } + guard self.characterCount == other.characterCount else { return false } + // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. + var it1 = self.makeCharacterIterator() + var it2 = other.makeCharacterIterator() + var a: Character? = nil + var b: Character? = nil + repeat { + a = it1.next() + b = it2.next() + guard a == b else { return false } + } while a != nil + return true + } + + 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 true } + guard self.characterCount == other.characterCount else { 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 + } + } + } +} + +extension _BString { + /// Lexicographically compare the UTF-8 representations of `left` to `right`, returning a Boolean + /// value indicating whether `left` is equal to `right`. + internal func utf8IsEqual(to other: Self) -> Bool { + guard self.rope.summary == other.rope.summary else { return false } + if self.isIdentical(to: other) { return true } + + // 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()?[...] ?? "" + } + guard s1.isEmpty == s2.isEmpty else { return false } + if s1.isEmpty { break } + let c = Swift.min(s1.utf8.count, s2.utf8.count) + assert(c > 0) + let stop = s1.withUTF8 { b1 in + s2.withUTF8 { b2 in + for i in 0 ..< c { + guard b1[i] == b2[i] else { + return true + } + } + return false + } + } + if stop { return false } + s1 = s1.suffix(from: s1._utf8Index(at: c)) + s2 = s2.suffix(from: s2._utf8Index(at: c)) + } + 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)) + } + } +} diff --git a/Sources/RopeModule/BString/Conformances/_BString+Conformances.swift b/Sources/RopeModule/BString/Conformances/_BString+Conformances.swift new file mode 100644 index 00000000..fd6c0093 --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+Conformances.swift @@ -0,0 +1,22 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString: ExpressibleByStringLiteral { + internal init(stringLiteral value: String) { + self.init(value) + } +} + +extension _BString: CustomStringConvertible { + internal var description: String { + String(_from: self) + } +} diff --git a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift new file mode 100644 index 00000000..ceede27f --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + internal func hashCharacters(into hasher: inout Hasher) { + // 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. :-/ + var it = self.makeCharacterIterator() + while let character = it.next() { + let s = String(character) + s._withNFCCodeUnits { hasher.combine($0) } + } + hasher.combine(0xFF as UInt8) + } + + /// Feed the UTF-8 encoding of `self` into hasher, with a terminating byte. + internal func hashUTF8(into hasher: inout Hasher) { + for chunk in self.rope { + var string = chunk.string + string.withUTF8 { + hasher.combine(bytes: .init($0)) + } + hasher.combine(0xFF as UInt8) + } + } +} diff --git a/Sources/RopeModule/BString/Operations/_BString+Append.swift b/Sources/RopeModule/BString/Operations/_BString+Append.swift new file mode 100644 index 00000000..0806bb60 --- /dev/null +++ b/Sources/RopeModule/BString/Operations/_BString+Append.swift @@ -0,0 +1,171 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +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) { + if other.isEmpty { return } + if isEmpty { + self = Self(other) + return + } + var ingester = ingester(forInserting: other, at: endIndex, allowForwardPeek: true).ingester + + let last = rope.index(before: rope.endIndex) + if let final = rope[last].append(from: &ingester) { + precondition(!final.isUndersized) + rope.append(final) + return + } + + // Make a temp rope out of the rest of the chunks and then join the two trees together. + if !ingester.isAtEnd { + var builder = Rope.Builder() + while let chunk = ingester.nextWellSizedChunk() { + precondition(!chunk.isUndersized) + builder.append(chunk) + } + precondition(ingester.isAtEnd) + rope = Rope.join(rope, builder.finalize()) + } + } +} + +extension _BString { + var _firstUnicodeScalar: Unicode.Scalar { + assert(!isEmpty) + return rope.root.firstItem.value.string.unicodeScalars.first! + } + + mutating func append(contentsOf other: __owned _BString) { + guard !other.isEmpty else { return } + guard !self.isEmpty else { + self = other + return + } + + let hint = other._firstUnicodeScalar + var other = other.rope + var old = _CharacterRecognizer() + var new = self._breakState(upTo: endIndex, nextScalarHint: hint).state + _ = other.resyncBreaks(old: &old, new: &new) + _append(other) + } + + mutating func prepend(contentsOf other: __owned _BString) { + guard !other.isEmpty else { return } + guard !self.isEmpty else { + self = other + return + } + + let hint = self._firstUnicodeScalar + var old = _CharacterRecognizer() + var new = other._breakState(upTo: other.endIndex, nextScalarHint: hint).state + _ = self.rope.resyncBreaks(old: &old, new: &new) + + _prepend(other.rope) + } +} + +extension _BString { + var isUndersized: Bool { + utf8Count < Chunk.minUTF8Count + } +} + +extension _BString { + /// Note: This assumes `other` already has the correct break positions. + mutating func _append(_ other: __owned Chunk) { + assert(!other.isEmpty) + guard !self.isEmpty else { + self.rope.append(other) + return + } + guard self.isUndersized || other.isUndersized else { + self.rope.append(other) + return + } + var other = other + let last = self.rope.index(before: self.rope.endIndex) + if !self.rope[last].rebalance(nextNeighbor: &other) { + assert(!other.isUndersized) + self.rope.append(other) + } + } + + /// Note: This assumes `self` and `other` already have the correct break positions. + mutating func _prepend(_ other: __owned Chunk) { + assert(!other.isEmpty) + guard !self.isEmpty else { + self.rope.prepend(other) + return + } + guard self.isUndersized || other.isUndersized else { + self.rope.prepend(other) + return + } + var other = other + let first = self.rope.startIndex + if !self.rope[first].rebalance(prevNeighbor: &other) { + self.rope.prepend(other) + } + } + + /// Note: This assumes `other` already has the correct break positions. + mutating func _append(_ other: __owned Rope) { + guard !other.isEmpty else { return } + guard !self.rope.isEmpty else { + self.rope = other + return + } + if other.isSingleton { + self._append(other.first!) + return + } + if self.isUndersized { + assert(self.rope.isSingleton) + let chunk = self.rope.first! + self.rope = other + self._prepend(chunk) + return + } + self.rope = Rope.join(self.rope, other) + } + + /// Note: This assumes `self` and `other` already have the correct break positions. + mutating func _prepend(_ other: __owned Rope) { + guard !other.isEmpty else { return } + guard !self.isEmpty else { + self.rope = other + return + } + if other.isSingleton { + self._prepend(other.first!) + return + } + if self.isUndersized { + assert(self.rope.isSingleton) + let chunk = self.rope.first! + self.rope = other + self._append(chunk) + return + } + self.rope = Rope.join(other, self.rope) + } +} diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift new file mode 100644 index 00000000..4c0060af --- /dev/null +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -0,0 +1,107 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + internal init(_ input: some StringProtocol) { + var builder = Rope.Builder() + var ingester = Ingester(input) + while let chunk = ingester.nextWellSizedChunk() { + builder.append(chunk) + } + self.rope = builder.finalize() + } + + internal init(_ input: some Sequence) { + var builder = Builder() + var piece = "" + for character in input { + piece.append(character) + if piece.utf8.count >= Chunk.minUTF8Count { + builder.append(piece) + piece = "" + } + } + builder.append(piece) + self = builder.finalize() + } + + internal init(_ input: some Sequence) { + var builder = Builder() + var piece = "" + for scalar in input { + piece.unicodeScalars.append(scalar) + if piece.utf8.count >= Chunk.minUTF8Count { + builder.append(piece) + piece = "" + } + } + builder.append(piece) + self = builder.finalize() + } +} + +extension String { + internal init(_from big: _BString) { + self.init() + self.reserveCapacity(big.utf8Count) + for chunk in big.rope { + self.append(chunk.string) + } + } + + internal init(_from big: _BString, in range: Range<_BString.Index>) { + self.init() + guard range.lowerBound._utf8Offset < range.upperBound._utf8Offset else { + // We can safely ignore UTF-16 offsets, as we're rounding down to scalar boundaries + // anyway. + return + } + let start = big.path(to: range.lowerBound, preferEnd: false) + let end = big.path(to: range.upperBound, preferEnd: true) + + if start.path.rope == end.path.rope { + self += start.chunk.string[start.path.chunk ..< end.path.chunk] + return + } + + self += start.chunk.string[start.path.chunk...] + + var it = big.rope.makeIterator(from: start.path.rope) + while it.stepForward(), it.index < end.path.rope { + self += it.current.string + } + self += end.chunk.string[..= 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 + } + } +} diff --git a/Sources/RopeModule/BString/Operations/_BString+Insert.swift b/Sources/RopeModule/BString/Operations/_BString+Insert.swift new file mode 100644 index 00000000..e73045bb --- /dev/null +++ b/Sources/RopeModule/BString/Operations/_BString+Insert.swift @@ -0,0 +1,78 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +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( + contentsOf other: __owned Substring, + at index: Index + ) { + precondition(index <= endIndex, "Index out of bounds") + if other.isEmpty { return } + if index == endIndex { + self.append(contentsOf: other) + return + } + + // Note: we must disable the forward peeking optimization as we'll need to know the actual + // full grapheme breaking state of the ingester at the start of the insertion. + // (We'll use it to resync grapheme breaks in the parts that follow the insertion.) + var (ingester, _, path) = ingester(forInserting: other, at: index, allowForwardPeek: false) + let r = rope[path.rope].insert(from: &ingester, at: path.chunk) + switch r { + case let .inline(r): + assert(ingester.isAtEnd) + guard var r = r else { break } + let i = index._advanceUTF8(by: r.increment) + resyncBreaks(startingAt: i, old: &r.old, new: &r.new) + case let .split(spawn: spawn, endStates: r): + assert(ingester.isAtEnd) + rope.insert(spawn, at: rope.index(after: path.rope)) + guard var r = r else { break } + let i = index._advanceUTF8(by: r.increment) + resyncBreaks(startingAt: i, old: &r.old, new: &r.new) + case .large: + var builder = self._split(at: path, state: ingester.state) + builder.append(from: &ingester) + self = builder.finalize() + } + } +} + +extension _BString { + 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) + return + } + guard index > startIndex else { + self.prepend(contentsOf: other) + return + } + if other.rope.isSingleton { + // Fast path when `other` is tiny. + let chunk = other.rope.first! + insert(contentsOf: chunk.string, at: index) + return + } + var builder = self.split(at: index) + builder.append(other) + self = builder.finalize() + } +} diff --git a/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift b/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift new file mode 100644 index 00000000..da0b3a93 --- /dev/null +++ b/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift @@ -0,0 +1,263 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + func _breakState( + upTo end: Path, + in chunk: Chunk, + nextScalarHint: Unicode.Scalar? = nil + ) -> (prevBreak: Path, state: _CharacterRecognizer) { + guard end.rope > rope.startIndex || end._chunk > 0 else { + return (Path(startOf: rope.startIndex), _CharacterRecognizer()) + } + + if let next = nextScalarHint, end.chunk > chunk.string.startIndex { + let i = chunk.string.unicodeScalars.index(before: end.chunk) + let prev = chunk.string.unicodeScalars[i] + if _CharacterRecognizer.quickBreak(between: prev, and: next) == true { + return (end, _CharacterRecognizer()) + } + } + + if let r = chunk.immediateBreakState(upTo: end.chunk) { + return (Path(end.rope, r.prevBreak), r.state) + } + // Find chunk that includes the start of the character. + var it = rope.makeIterator(from: end.rope) + while it.stepBackward() { + if it.current.hasBreaks { break } + } + precondition(it.index < end.rope) + let prev = Path(it.index, it.current.lastBreak) + + // Collect grapheme breaking state. + var state = _CharacterRecognizer(partialCharacter: it.current.suffix) + while it.stepForward(), it.index < end.rope { + state.consumePartialCharacter(it.current.string[...]) + } + state.consumePartialCharacter(it.current.string[.. (start: Path, end: Path, state: _CharacterRecognizer) { + guard index > startIndex else { + let dummy = Path(startOf: rope.startIndex) + return (dummy, dummy, _CharacterRecognizer()) + } + let end = path(to: index, preferEnd: true) + let r = _breakState(upTo: end.path, in: end.chunk, nextScalarHint: nextScalarHint) + return (r.prevBreak, end.path, r.state) + } +} + +extension _BString { + /// - Returns: the position at which the grapheme breaks finally sync up with the originals. + /// (or nil if they never did). + @discardableResult + mutating func resyncBreaks( + startingAt index: Index, + old: inout _CharacterRecognizer, + new: inout _CharacterRecognizer + ) -> Path? { + guard index < endIndex else { return nil } + let p = path(to: index, preferEnd: false).path + var path = (rope: p.rope, chunk: p.chunk) + + let end = rope.mutatingForEach(from: &path.rope) { chunk in + let start = path.chunk + path.chunk = "".startIndex + return chunk.resyncBreaks(startingAt: start, old: &old, new: &new) + } + guard let end else { return nil } + path.chunk = end + return Path(path.rope, path.chunk) + } + + mutating func resyncBreaksToEnd( + startingAt index: Index, + old: inout _CharacterRecognizer, + new: inout _CharacterRecognizer + ) { + guard let _ = resyncBreaks(startingAt: index, old: &old, new: &new) else { return } + let state = _breakState(upTo: endIndex).state + old = state + new = state + } +} + +extension _BString.Rope { + mutating func resyncBreaks( + old: inout _CharacterRecognizer, + new: inout _CharacterRecognizer + ) -> Bool { + var index = startIndex + let r = self.mutatingForEach(from: &index) { + $0.resyncBreaksFromStart(old: &old, new: &new) + } + return r != nil + } + + mutating func _resyncBreaks( + old: inout _CharacterRecognizer, + new: inout _CharacterRecognizer + ) -> (path: Index, String.Index)? { + var index = startIndex + let r = self.mutatingForEach(from: &index) { + $0.resyncBreaksFromStart(old: &old, new: &new) + } + guard let r else { return nil } + return (index, r) + } + + mutating func resyncBreaksToEnd( + old: inout _CharacterRecognizer, + new: inout _CharacterRecognizer + ) { + guard let (index, i) = _resyncBreaks(old: &old, new: &new) else { return } + + let chars = self.summary.characters + if chars > 0 { + var it = makeIterator(from: endIndex) + while it.stepBackward() { + if it.current.hasBreaks { break } + if it.index == index { break } + } + if it.index > index || it.current.lastBreak > i { + new = it.current.immediateLastBreakState! + while it.stepForward() { + new.consumePartialCharacter(it.current.string[...]) + } + old = new + return + } + } + var it = makeIterator(from: index) + let suffix = it.current.string.unicodeScalars[i...].dropFirst() + new.consumePartialCharacter(suffix) + while it.stepForward() { + new.consumePartialCharacter(it.current.string[...]) + } + old = new + } +} + +extension _BString.Chunk { + /// Resyncronize chunk metadata with the (possibly) reshuffled grapheme + /// breaks after an insertion that ended at `index`. + /// + /// This assumes that the chunk's prefix and suffix counts have already + /// been adjusted to remain on Unicode scalar boundaries, and that they + /// are also in sync with the grapheme breaks up to `index`. If the + /// prefix ends after `index`, then this function may update it to address + /// the correct scalar. Similarly, the suffix count may be updated to + /// reflect the new position of the last grapheme break, if necessary. + mutating func resyncBreaks( + startingAt index: String.Index, + old: inout _CharacterRecognizer, + new: inout _CharacterRecognizer + ) -> String.Index? { + var i = index + let u = string.unicodeScalars + assert(u._index(roundingDown: i) == i) + + // FIXME: Rewrite in terms of `firstBreak(in:)`. + var first: String.Index? = nil + var last: String.Index? = nil + loop: + while i < u.endIndex { + let scalar = u[i] + let a = old.hasBreak(before: scalar) + let b = new.hasBreak(before: scalar) + if b { + first = first ?? i + last = i + } + switch (a, b) { + case (true, true): + break loop // Resync complete ✨ + case (false, false): + if old == new { break loop } + case (false, true): + counts._characters += 1 + case (true, false): + counts._characters -= 1 + } + u.formIndex(after: &i) + } + + // Grapheme breaks in `index...i` may have changed. Update `firstBreak` and `lastBreak` + // accordingly. + + assert((first == nil) == (last == nil)) + if index <= firstBreak { + if let first { + // We have seen the new first break. + firstBreak = first + } else if i >= firstBreak { + // The old firstBreak is no longer a break. + if i < lastBreak { + // The old lastBreak is still valid. Find the first break in i+1...endIndex. + let j = u.index(after: i) + var tmp = new + firstBreak = tmp.firstBreak(in: string[j...])!.lowerBound + } else { + // No breaks anywhere in the string. + firstBreak = u.endIndex + } + } + } + + if i >= lastBreak { + if let last { + // We have seen the new last break. + lastBreak = last + } else if firstBreak == u.endIndex { + // We already know there are no breaks anywhere in the string. + lastBreak = u.startIndex + } else { + // We have a `firstBreak`, but no break in `index...i`. + // Find last break in `firstBreak... String.Index? { + resyncBreaks(startingAt: string.startIndex, old: &old, new: &new) + } + + mutating func resyncBreaksFromStartToEnd( + old: inout _CharacterRecognizer, + new: inout _CharacterRecognizer + ) { + guard let i = resyncBreaks(startingAt: string.startIndex, old: &old, new: &new) else { + return + } + if i < lastBreak { + new = _CharacterRecognizer(partialCharacter: string[lastBreak...]) + } else { + assert(old == new) + let j = string.unicodeScalars.index(after: i) + new.consumePartialCharacter(string[j...]) + } + old = new + return + } +} diff --git a/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift new file mode 100644 index 00000000..308b05f0 --- /dev/null +++ b/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift @@ -0,0 +1,42 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + mutating func removeSubrange(_ bounds: Range) { + precondition(bounds.upperBound <= endIndex, "Index out of bounds") + if bounds.isEmpty { return } + let lower = bounds.lowerBound._utf8Offset + let upper = bounds.upperBound._utf8Offset + rope.removeSubrange(lower ..< upper, in: UTF8Metric()) + } +} + +extension _BString { + mutating func removeCharacter(at i: Index) -> Character { + let (start, chunk) = self.path(to: i, preferEnd: false) + let startBase = baseIndex(with: i, at: start.chunk) + let (character, end, endBase) = self._character(at: start, base: startBase, in: chunk) + let j = endBase!._advanceUTF8(by: end.chunk._utf8Offset) + self.removeSubrange(i ..< j) + return character + } + + mutating func removeUnicodeScalar(at i: Index) -> Unicode.Scalar { + let (path, chunk) = self.path(to: i, preferEnd: false) + assert(path.chunk < chunk.string.endIndex) + let base = baseIndex(with: i, at: path.chunk) + let scalar = chunk.string.unicodeScalars[path.chunk] + let end = chunk.string.unicodeScalars.index(after: path.chunk) + let j = index(base: base, offsetBy: end) + self.removeSubrange(i ..< j) + return scalar + } +} diff --git a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift new file mode 100644 index 00000000..bafec9ee --- /dev/null +++ b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift @@ -0,0 +1,49 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + 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) + return + } + var builder = _split(removing: range) + var ingester = Ingester(Substring(newElements), startState: builder.prefixEndState) + builder.append(from: &ingester) + self = builder.finalize() + } + + 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) + return + } + var builder = _split(removing: range) + builder.append(newElements) + self = builder.finalize() + } + + mutating func _split(removing range: Range) -> Builder { + let lower = range.lowerBound._utf8Offset + let upper = range.upperBound._utf8Offset + + // FIXME: Don't split the indices twice -- they are currently split once here and once in the + // builder initializer below. + let startState = _breakState(upTo: range.lowerBound).state + let endState = _breakState(upTo: range.upperBound).state + + let b = rope.builder(removing: lower ..< upper, in: UTF8Metric()) + return Builder(base: b, prefixEndState: startState, suffixStartState: endState) + } +} + diff --git a/Sources/RopeModule/BString/Operations/_BString+Split.swift b/Sources/RopeModule/BString/Operations/_BString+Split.swift new file mode 100644 index 00000000..0865685e --- /dev/null +++ b/Sources/RopeModule/BString/Operations/_BString+Split.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 +// +//===----------------------------------------------------------------------===// + +extension _BString { + mutating func split( + at index: Index + ) -> Builder { + let b = rope.builder(splittingAt: index._utf8Offset, in: UTF8Metric()) + let state = b.breakState() + let builder = Builder(base: b, prefixEndState: state, suffixStartState: state) + return builder + } + + mutating func _split( + at path: Path, + state: _CharacterRecognizer + ) -> Builder { + let b = rope.split(at: path.rope, path.chunk) + let builder = Builder(base: b, prefixEndState: state, suffixStartState: state) + return builder + } +} diff --git a/Sources/RopeModule/BigString/BigString+CharacterView.swift b/Sources/RopeModule/BigString/BigString+CharacterView.swift new file mode 100644 index 00000000..48ab9e4f --- /dev/null +++ b/Sources/RopeModule/BigString/BigString+CharacterView.swift @@ -0,0 +1,269 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension BigString { + public struct Index { + internal var _value: _BString.Index + + internal init(_ value: _BString.Index) { + self._value = value + } + } +} + +extension BigString.Index: CustomStringConvertible { + public var description: String { + "\(_value)" + } +} + +extension BigString.Index: Equatable { + public static func ==(left: Self, right: Self) -> Bool { + left._value == right._value + } +} + +extension BigString.Index: Comparable { + public static func <(left: Self, right: Self) -> Bool { + left._value < right._value + } +} + +extension BigString.Index: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(_value) + } +} + +extension BigString: Equatable { + public static func == (left: Self, right: Self) -> Bool { + left._guts.characterIsEqual(to: right._guts) + } +} + +extension BigString: Comparable { + public static func < (left: Self, right: Self) -> Bool { + left._guts.characterIsLess(than: right._guts) + } +} + +extension BigString: Hashable { + public func hash(into hasher: inout Hasher) { + _guts.hashCharacters(into: &hasher) + } +} + +extension BigString: Sequence { + public struct Iterator: IteratorProtocol { + public typealias Element = Character + + internal var _base: _BString.CharacterIterator + + internal init(_base: _BString.CharacterIterator) { + self._base = _base + } + + public mutating func next() -> Character? { + _base.next() + } + } + + public func makeIterator() -> Iterator { + Iterator(_base: _guts.makeCharacterIterator()) + } +} + +extension BigString: BidirectionalCollection { + public typealias Element = Character + + public var count: Int { + _guts.characterCount + } + + public var startIndex: Index { + Index(_guts.startIndex) + } + + public var endIndex: Index { + Index(_guts.endIndex) + } + + public func index(after i: Index) -> Index { + Index(_guts.characterIndex(after: i._value)) + } + + public func index(before i: Index) -> Index { + Index(_guts.characterIndex(before: i._value)) + } + + public func index(_ i: Index, offsetBy distance: Int) -> Index { + Index(_guts.characterIndex(i._value, offsetBy: distance)) + } + + public func distance(from start: Index, to end: Index) -> Int { + _guts.characterDistance(from: start._value, to: end._value) + } + + public subscript(position: Index) -> Character { + _guts[character: position._value] + } +} + +extension Range where Bound == BigString.Index { + var _base: Range<_BString.Index> { + Range<_BString.Index>(uncheckedBounds: (lowerBound._value, upperBound._value)) + } +} + +extension BigString: RangeReplaceableCollection { + 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 { + replaceSubrange(subrange, with: newElements) + } else if let newElements = newElements as? Substring { + replaceSubrange(subrange, with: newElements) + } else { + _guts.replaceSubrange(subrange._base, with: _BString(newElements)) + } + } + + public mutating func replaceSubrange( + _ subrange: Range, + with newElements: __owned String + ) { + _guts.replaceSubrange(subrange._base, with: newElements) + } + + public mutating func replaceSubrange( + _ subrange: Range, + with newElements: __owned Substring + ) { + _guts.replaceSubrange(subrange._base, with: newElements) + } + + public mutating func replaceSubrange( + _ subrange: Range, + with newElements: __owned BigString + ) { + _guts.replaceSubrange(subrange._base, with: newElements._guts) + } + + public mutating func reserveCapacity(_ n: Int) {} + + public init(_ elements: some Sequence) { + if let elements = elements as? Self { + self._guts = elements._guts + } else if let elements = elements as? String { + self._guts = _BString(elements) + } else if let elements = elements as? Substring { + self._guts = _BString(elements) + } else { + self._guts = _BString(elements) + } + } + + public init(_ elements: String) { + self._guts = _BString(elements) + } + + public init(_ elements: Substring) { + self._guts = _BString(elements) + } + + public init(_ elements: Self) { + self._guts = elements._guts + } + + public init(repeating repeatedValue: Character, count: Int) { + self._guts = _BString(repeating: _BString(String(repeatedValue)), count: count) + } + + public init(repeating repeatedValue: some StringProtocol, count: Int) { + self._guts = _BString(repeating: _BString(repeatedValue), count: count) + } + + public init(repeating repeatedValue: Self, count: Int) { + self._guts = _BString(repeating: repeatedValue._guts, count: count) + } + + public mutating func append(_ newElement: __owned Character) { + _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 { + self.append(contentsOf: newElements) + } else if let newElements = newElements as? Substring { + self.append(contentsOf: newElements) + } else { + _guts.append(contentsOf: _BString(newElements)) + } + } + + public mutating func append(contentsOf newElements: __owned String) { + _guts.append(contentsOf: newElements) + } + + public mutating func append(contentsOf newElements: __owned Substring) { + _guts.append(contentsOf: newElements) + } + + public mutating func append(contentsOf newElements: __owned Self) { + _guts.append(contentsOf: newElements._guts) + } + + public mutating func insert(_ newElement: __owned Character, 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 { + self.insert(contentsOf: newElements, at: i) + } else if let newElements = newElements as? Substring { + self.insert(contentsOf: newElements, at: i) + } else { + _guts.insert(contentsOf: _BString(newElements), at: i._value) + } + } + + public mutating func insert(contentsOf newElements: String, at i: Index) { + _guts.insert(contentsOf: newElements, at: i._value) + } + + public mutating func insert(contentsOf newElements: Substring, at i: Index) { + _guts.insert(contentsOf: newElements, at: i._value) + } + + public mutating func insert(contentsOf newElements: Self, at i: Index) { + _guts.insert(contentsOf: newElements._guts, at: i._value) + } + + @discardableResult + public mutating func remove(at i: Index) -> Character { + _guts.removeCharacter(at: i._value) + } + + public mutating func removeSubrange(_ bounds: Range) { + _guts.removeSubrange(bounds._base) + } + + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + _guts = _BString() + } +} diff --git a/Sources/RopeModule/BigString/BigString+UTF16View.swift b/Sources/RopeModule/BigString/BigString+UTF16View.swift new file mode 100644 index 00000000..5304cd51 --- /dev/null +++ b/Sources/RopeModule/BigString/BigString+UTF16View.swift @@ -0,0 +1,129 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension BigString { + public struct UTF16View { + internal var _guts: _BString + + internal init(_guts: _BString) { + self._guts = _guts + } + } + + public var utf16: UTF16View { + get { + UTF16View(_guts: _guts) + } + set { + _guts = newValue._guts + } + _modify { + var view = UTF16View(_guts: _guts) + self._guts = .init() + defer { + self._guts = view._guts + } + yield &view + } + } +} + +extension BigString { + public init(_ content: UTF16View) { + self._guts = content._guts + } +} + +extension BigString.UTF16View: CustomStringConvertible { + public var description: String { + var d = "<" + d += self.lazy + .map { String($0, radix: 16, uppercase: true)._lpad(to: 4, with: "0") } + .joined(separator: " ") + d += ">" + return d + } +} + +extension BigString.UTF16View: Equatable { + public static func ==(left: Self, right: Self) -> Bool { + left._guts.utf8IsEqual(to: right._guts) + } +} + +extension BigString.UTF16View: Comparable { + public static func <(left: Self, right: Self) -> Bool { + left._guts.utf8IsLess(than: right._guts) + } +} + +extension BigString.UTF16View: Hashable { + public func hash(into hasher: inout Hasher) { + _guts.hashUTF8(into: &hasher) + } +} + +extension BigString.UTF16View: Sequence { + public struct Iterator: IteratorProtocol { + public typealias Element = UInt16 + + internal var _base: _BString.UTF16Iterator + + internal init(_base: _BString.UTF16Iterator) { + self._base = _base + } + + public mutating func next() -> UInt16? { + _base.next() + } + } + + public func makeIterator() -> Iterator { + Iterator(_base: self._guts.makeUTF16Iterator()) + } +} + +extension BigString.UTF16View: BidirectionalCollection { + public typealias Index = BigString.Index + public typealias Element = UInt16 + + public var count: Int { + _guts.utf16Count + } + + public var startIndex: Index { + Index(_guts.startIndex) + } + + public var endIndex: Index { + Index(_guts.endIndex) + } + + public func index(after i: Index) -> Index { + Index(_guts.utf16Index(after: i._value)) + } + + public func index(before i: Index) -> Index { + Index(_guts.utf16Index(before: i._value)) + } + + public func index(_ i: Index, offsetBy distance: Int) -> Index { + Index(_guts.utf16Index(i._value, offsetBy: distance)) + } + + public func distance(from start: Index, to end: Index) -> Int { + _guts.utf16Distance(from: start._value, to: end._value) + } + + public subscript(position: Index) -> UInt16 { + _guts[utf16: position._value] + } +} diff --git a/Sources/RopeModule/BigString/BigString+UTF8View.swift b/Sources/RopeModule/BigString/BigString+UTF8View.swift new file mode 100644 index 00000000..fbb46a1b --- /dev/null +++ b/Sources/RopeModule/BigString/BigString+UTF8View.swift @@ -0,0 +1,129 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension BigString { + public struct UTF8View { + internal var _guts: _BString + + internal init(_guts: _BString) { + self._guts = _guts + } + } + + public var utf8: UTF8View { + get { + UTF8View(_guts: _guts) + } + set { + _guts = newValue._guts + } + _modify { + var view = UTF8View(_guts: _guts) + self._guts = .init() + defer { + self._guts = view._guts + } + yield &view + } + } +} + +extension BigString { + public init(_ content: UTF8View) { + self._guts = content._guts + } +} + +extension BigString.UTF8View: CustomStringConvertible { + public var description: String { + var d = "<" + d += self.lazy + .map { String($0, radix: 16, uppercase: true)._lpad(to: 2, with: "0") } + .joined(separator: " ") + d += ">" + return d + } +} + +extension BigString.UTF8View: Equatable { + public static func ==(left: Self, right: Self) -> Bool { + left._guts.utf8IsEqual(to: right._guts) + } +} + +extension BigString.UTF8View: Comparable { + public static func <(left: Self, right: Self) -> Bool { + left._guts.utf8IsLess(than: right._guts) + } +} + +extension BigString.UTF8View: Hashable { + public func hash(into hasher: inout Hasher) { + _guts.hashUTF8(into: &hasher) + } +} + +extension BigString.UTF8View: Sequence { + public struct Iterator: IteratorProtocol { + public typealias Element = UInt8 + + internal var _base: _BString.UTF8Iterator + + internal init(_base: _BString.UTF8Iterator) { + self._base = _base + } + + public mutating func next() -> UInt8? { + _base.next() + } + } + + public func makeIterator() -> Iterator { + Iterator(_base: self._guts.makeUTF8Iterator()) + } +} + +extension BigString.UTF8View: BidirectionalCollection { + public typealias Index = BigString.Index + public typealias Element = UInt8 + + public var count: Int { + _guts.utf8Count + } + + public var startIndex: Index { + Index(_guts.startIndex) + } + + public var endIndex: Index { + Index(_guts.endIndex) + } + + public func index(after i: Index) -> Index { + Index(_guts.utf8Index(after: i._value)) + } + + public func index(before i: Index) -> Index { + Index(_guts.utf8Index(before: i._value)) + } + + public func index(_ i: Index, offsetBy distance: Int) -> Index { + Index(_guts.utf8Index(i._value, offsetBy: distance)) + } + + public func distance(from start: Index, to end: Index) -> Int { + _guts.utf8Distance(from: start._value, to: end._value) + } + + public subscript(position: Index) -> UInt8 { + _guts[utf8: position._value] + } +} diff --git a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift new file mode 100644 index 00000000..65a3bdcb --- /dev/null +++ b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift @@ -0,0 +1,271 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension BigString { + public struct UnicodeScalarView { + var _guts: _BString + + init(_guts: _BString) { + self._guts = _guts + } + } + + public var unicodeScalars: UnicodeScalarView { + get { + UnicodeScalarView(_guts: _guts) + } + set { + _guts = newValue._guts + } + _modify { + var view = UnicodeScalarView(_guts: _guts) + self._guts = .init() + defer { + self._guts = view._guts + } + yield &view + } + } +} + +extension BigString { + public init(_ content: UnicodeScalarView) { + self._guts = content._guts + } +} + +extension BigString.UnicodeScalarView: ExpressibleByStringLiteral { + public init(stringLiteral value: String) { + self.init(_guts: _BString(value)) + } +} + +extension BigString.UnicodeScalarView: CustomStringConvertible { + public var description: String { + String(_from: _guts) + } +} + +extension BigString.UnicodeScalarView: Equatable { + public static func ==(left: Self, right: Self) -> Bool { + left._guts.utf8IsEqual(to: right._guts) + } +} + +extension BigString.UnicodeScalarView: Comparable { + public static func <(left: Self, right: Self) -> Bool { + left._guts.utf8IsLess(than: right._guts) + } +} + +extension BigString.UnicodeScalarView: Hashable { + public func hash(into hasher: inout Hasher) { + _guts.hashUTF8(into: &hasher) + } +} + +extension BigString.UnicodeScalarView: Sequence { + public struct Iterator: IteratorProtocol { + public typealias Element = Unicode.Scalar + + internal var _base: _BString.UnicodeScalarIterator + + internal init(_base: _BString.UnicodeScalarIterator) { + self._base = _base + } + + public mutating func next() -> Unicode.Scalar? { + _base.next() + } + } + + public func makeIterator() -> Iterator { + Iterator(_base: _guts.makeUnicodeScalarIterator()) + } +} + +extension BigString.UnicodeScalarView: BidirectionalCollection { + public typealias Element = Unicode.Scalar + public typealias Index = BigString.Index + + public var count: Int { + _guts.unicodeScalarCount + } + + public var startIndex: Index { + Index(_guts.startIndex) + } + + public var endIndex: Index { + Index(_guts.endIndex) + } + + public func index(after i: Index) -> Index { + Index(_guts.unicodeScalarIndex(after: i._value)) + } + + public func index(before i: Index) -> Index { + Index(_guts.unicodeScalarIndex(after: i._value)) + } + + public func index(_ i: Index, offsetBy distance: Int) -> Index { + Index(_guts.unicodeScalarIndex(i._value, offsetBy: distance)) + } + + public func distance(from start: Index, to end: Index) -> Int { + _guts.unicodeScalarDistance(from: start._value, to: end._value) + } + + public subscript(index: Index) -> Unicode.Scalar { + _guts[unicodeScalar: index._value] + } +} + +extension BigString.UnicodeScalarView: RangeReplaceableCollection { + 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)) + } + } + + public mutating func replaceSubrange( + _ subrange: Range, + with newElements: __owned String.UnicodeScalarView + ) { + _guts.replaceSubrange(subrange._base, with: String(newElements)) + } + + public mutating func replaceSubrange( + _ subrange: Range, + with newElements: __owned Substring.UnicodeScalarView + ) { + _guts.replaceSubrange(subrange._base, with: Substring(newElements)) + } + + public mutating func replaceSubrange( + _ subrange: Range, + with newElements: __owned BigString.UnicodeScalarView + ) { + _guts.replaceSubrange(subrange._base, with: newElements._guts) + } + + public mutating func reserveCapacity(_ n: Int) {} + + public init() { + _guts = .init() + } + + public init(_ elements: some Sequence) { + if let elements = elements as? 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) + } + } + + public init(_ elements: String.UnicodeScalarView) { + self._guts = _BString(elements) + } + + public init(_ elements: Substring.UnicodeScalarView) { + self._guts = _BString(elements) + } + + public init(_ elements: Self) { + self._guts = elements._guts + } + + public init(repeating scalar: Unicode.Scalar, count: Int) { + self._guts = _BString(repeating: _BString(String(scalar)), count: count) + } + + public mutating func append(_ newElement: __owned Element) { + _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 String.UnicodeScalarView) { + _guts.append(contentsOf: String(newElements)) + } + + public mutating func append(contentsOf newElements: __owned Substring.UnicodeScalarView) { + _guts.append(contentsOf: Substring(newElements)) + } + + public mutating func append(contentsOf newElements: __owned Self) { + _guts.append(contentsOf: newElements._guts) + } + + 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: String.UnicodeScalarView, at i: Index) { + _guts.insert(contentsOf: String(newElements), at: i._value) + } + + public mutating func insert(contentsOf newElements: Substring.UnicodeScalarView, at i: Index) { + _guts.insert(contentsOf: Substring(newElements), at: i._value) + } + + public mutating func insert(contentsOf newElements: Self, at i: Index) { + _guts.insert(contentsOf: newElements._guts, at: i._value) + } + + @discardableResult + public mutating func remove(at i: Index) -> Unicode.Scalar { + _guts.removeUnicodeScalar(at: i._value) + } + + public mutating func removeSubrange(_ bounds: Range) { + _guts.removeSubrange(bounds._base) + } + + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + _guts = _BString() + } +} diff --git a/Sources/RopeModule/BigString/BigString.swift b/Sources/RopeModule/BigString/BigString.swift new file mode 100644 index 00000000..dcc37cd8 --- /dev/null +++ b/Sources/RopeModule/BigString/BigString.swift @@ -0,0 +1,66 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +public struct BigString: Sendable { + internal var _guts: _BString + + internal init(_guts: _BString) { + self._guts = _guts + } + + public init() { + _guts = _BString() + } +} + +extension BigString: ExpressibleByStringLiteral { + public init(stringLiteral value: String) { + self.init(value) + } +} + +extension BigString: CustomStringConvertible, LosslessStringConvertible { + public var description: String { + String(_from: _guts) + } +} + +extension BigString: TextOutputStream { + public mutating func write(_ string: String) { + self.append(contentsOf: string) + } +} + +extension BigString { + public func _invariantCheck() { + _guts.invariantCheck() + } +} + +extension String { + public init(_ big: BigString) { + self.init(_from: big._guts) + } + + public init(_ big: BigString.SubSequence) { + self.init(_from: big.base._guts, in: big.startIndex._value ..< big.endIndex._value) + } +} + +extension String.UnicodeScalarView { + public init(_ big: BigString.UnicodeScalarView) { + self = String(_from: big._guts).unicodeScalars + } + + public init(_ big: BigString.UnicodeScalarView.SubSequence) { + self = String().unicodeScalars + } +} diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift new file mode 100644 index 00000000..c376a503 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift @@ -0,0 +1,439 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + init(_ items: some Sequence) { + if let items = items as? Self { + self = items + return + } + var builder = Builder() + for item in items { + builder.append(item) + } + self = builder.finalize() + } +} + +extension _Rope { + struct Builder { + typealias Rope = _Rope + + // ║ ║ + // ║ ║ ║ ║ + // ║ ║ ║ ║ ║ ║ + // ║ ║ ║ ║ ║ ║ ║ ║ + // ──╨─╨─╨─╨──╨──╨──╨─╨─╨─╨── + // →prefixTrees→ ↑ ↑ ←suffixTrees← + // prefix suffix + + private var prefixTrees: [_Rope] = [] + private var prefixLeaf: _Rope.Node? + var prefix: _Rope.Item? + + var suffix: _Rope.Item? + var suffixTrees: [_Rope] = [] + + var isPrefixEmpty: Bool { + if prefix != nil { return false } + if let seedling = self.prefixLeaf, !seedling.isEmpty { return false } + return prefixTrees.isEmpty + } + + var isSuffixEmpty: Bool { + if suffix != nil { return false } + return suffixTrees.isEmpty + } + + var prefixSummary: Summary { + var sum = Summary.zero + for sapling in prefixTrees { + sum.add(sapling.summary) + } + if let seedling = prefixLeaf { sum.add(seedling.summary) } + if let seed = prefix { sum.add(seed.summary) } + return sum + } + + var suffixSummary: Summary { + var sum = Summary.zero + if let item = suffix { sum.add(item.summary) } + for rope in suffixTrees { + sum.add(rope.summary) + } + return sum + } + + var lastPrefixItem: _Rope.Item { + get { + assert(!isPrefixEmpty) + if let prefix { return prefix } + if let prefixLeaf { return prefixLeaf.lastItem } + return prefixTrees.last!.root.lastItem + } + _modify { + assert(!isPrefixEmpty) + if prefix != nil { + yield &prefix! + } else if prefixLeaf?.isEmpty == false { + yield &prefixLeaf!.lastItem + } else { + yield &prefixTrees[prefixTrees.count - 1].root.lastItem + } + } + } + + var firstSuffixItem: _Rope.Item { + get { + assert(!isSuffixEmpty) + if let suffix { return suffix } + return suffixTrees[suffixTrees.count - 1].root.firstItem + } + _modify { + assert(!isSuffixEmpty) + if suffix != nil { + yield &suffix! + } else { + yield &suffixTrees[suffixTrees.count - 1].root.firstItem + } + } + } + + func forEachElementInPrefix( + from position: Int, + in metric: some _RopeMetric, + _ body: (Element, Element.Index?) -> Bool + ) -> Bool { + var position = position + var i = 0 + while i < prefixTrees.count { + let size = metric.size(of: prefixTrees[i].summary) + if position < size { break } + position -= size + i += 1 + } + if i < prefixTrees.count { + guard prefixTrees[i].forEachWhile(from: position, in: metric, body) else { return false } + i += 1 + while i < prefixTrees.count { + guard prefixTrees[i].forEachWhile({ body($0, nil) }) else { return false } + i += 1 + } + if let seedling = self.prefixLeaf { + guard seedling.forEachWhile({ body($0, nil) }) else { return false } + } + if let seed = self.prefix { + guard body(seed.value, nil) else { return false } + } + return true + } + + if let seedling = self.prefixLeaf { + let size = metric.size(of: seedling.summary) + if position < size { + guard seedling.forEachWhile(from: position, in: metric, body) else { return false } + if let seed = self.prefix { + guard body(seed.value, nil) else { return false } + } + return true + } + position -= size + } + if let seed = self.prefix { + let i = metric.index(at: position, in: seed.value) + guard body(seed.value, i) else { return false} + } + return true + } + + mutating func mutatingForEachSuffix( + _ body: (inout Element) -> R? + ) -> R? { + if self.suffix != nil, + let r = body(&self.suffix!.value) { + return r + } + for i in stride(from: suffixTrees.count - 1, through: 0, by: -1) { + if let r = self.suffixTrees[i].mutatingForEach(body) { + return r + } + } + return nil + } + + mutating func append(_ item: __owned Element) { + append(_Rope.Item(item)) + } + + mutating func append(_ item: __owned _Rope.Item) { + guard !item.isEmpty else { return } + guard var seed = self.prefix._take() else { + self.prefix = item + return + } + var item = item + if seed.rebalance(nextNeighbor: &item) { + self.prefix = seed + return + } + _append(seed) + self.prefix = item + } + + mutating func _append(_ item: __owned _Rope.Item) { + assert(self.prefix == nil) + assert(!item.isUndersized) + var seedling = self.prefixLeaf._take() ?? .createLeaf() + seedling._appendItem(item) + if seedling.isFull { + self._append(seedling) + } else { + self.prefixLeaf = seedling + } + invariantCheck() + } + + mutating func append(_ rope: __owned Rope) { + guard rope._root != nil else { return } + append(rope.root) + } + + mutating func append(_ node: __owned Rope.Node) { + defer { invariantCheck() } + var node = node + if node.height == 0 { + if node.childCount == 1 { + append(node.firstItem) + return + } + if let seed = self.prefix._take() { + if let spawn = node.prepend(seed) { + append(node) + append(spawn) + return + } + } + if var seedling = self.prefixLeaf._take() { + if seedling.rebalance(nextNeighbor: &node), !seedling.isFull { + self.prefixLeaf = seedling + return + } + self._append(seedling) + } + + if node.isFull { + self._append(node) + } else { + self.prefixLeaf = node + } + return + } + + if var seed = self.prefix._take() { + if !seed.isUndersized || !node.firstItem.rebalance(prevNeighbor: &seed) { + self._append(seed) + } + } + if let seedling = self.prefixLeaf._take() { + _append(seedling) + } + _append(node) + } + + mutating func _append(_ rope: __owned Rope.Node) { + assert(self.prefix == nil && self.prefixLeaf == nil) + var new = rope + while !prefixTrees.isEmpty { + // Join previous saplings together until they grow at least as deep as the new one. + var previous = prefixTrees.removeLast() + while previous.height < new.height { + if prefixTrees.isEmpty { + previous.append(new) + prefixTrees.append(previous) + return + } + previous.prepend(prefixTrees.removeLast()) + } + + if previous.height == new.height { + if previous.root.rebalance(nextNeighbor: &new) { + new = previous.root + } else { + new = .createInner(children: previous.root, new) + } + continue + } + + if new.isFull, !previous.root.isFull, previous.height == new.height + 1 { + // Graft node under the last sapling, as a new child branch. + previous.root._appendNode(new) + new = previous.root + continue + } + + // The new seedling can be appended to the line and we're done. + prefixTrees.append(previous) + break + } + prefixTrees.append(Rope(root: new)) + } + + mutating func prependSuffix(_ item: __owned Item) { + guard !item.isEmpty else { return } + if var suffixItem = self.suffix._take() { + var item = item + if !(suffixItem.isUndersized && item.rebalance(nextNeighbor: &suffixItem)) { + if suffixTrees.isEmpty { + suffixTrees.append(Rope(root: .createLeaf(suffixItem))) + } else { + suffixTrees[suffixTrees.count - 1].prepend(suffixItem.value) + } + } + } + self.suffix = item + } + + mutating func prependSuffix(_ rope: __owned Rope) { + assert(suffix == nil) + assert(suffixTrees.isEmpty || rope.height <= suffixTrees.last!.height) + suffixTrees.append(rope) + } + + mutating func prependSuffix(_ rope: __owned Rope.Node) { + prependSuffix(_Rope(root: rope)) + } + + mutating func append(slots: Range, in node: __owned Rope.Node) { + assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) + let c = slots.count + guard c > 0 else { return } + if c == 1 { + if node.isLeaf { + let item = node.readLeaf { $0.children[slots.lowerBound] } + append(item) + } else { + let child = node.readInner { $0.children[slots.lowerBound] } + append(child) + } + return + } + let copy = node.copy(slots: slots) + append(copy) + } + + mutating func prependSuffix(slots: Range, in node: __owned Rope.Node) { + assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) + let c = slots.count + guard c > 0 else { return } + if c == 1 { + if node.isLeaf { + let item = node.readLeaf { $0.children[slots.lowerBound] } + prependSuffix(item) + } else { + let child = node.readInner { $0.children[slots.lowerBound] } + prependSuffix(child) + } + return + } + let copy = node.copy(slots: slots) + prependSuffix(copy) + } + + + mutating func finalize() -> Rope { + // Integrate prefix & suffix chunks. + if let suffixItem = self.suffix._take() { + append(suffixItem) + } + if var seed = self.prefix._take() { + if !seed.isUndersized { + _append(seed) + } else if !self.isPrefixEmpty { + if !self.lastPrefixItem.rebalance(nextNeighbor: &seed) { + _append(seed) + } + } else if !self.isSuffixEmpty { + if !self.firstSuffixItem.rebalance(prevNeighbor: &seed) { + _append(seed) + } + } else { + // We only have the seed; allow undersized chunk + return Rope(root: .createLeaf(seed)) + } + } + assert(self.prefix == nil && self.suffix == nil) + while let sapling = suffixTrees.popLast() { + append(sapling) + } + // Merge all saplings, the seedling and the seed into a single rope. + if let seed = self.prefix._take() { + _append(seed) + } + var rope = Rope(root: prefixLeaf._take()) + while let sapling = prefixTrees.popLast() { + rope.prepend(sapling) + } + assert(prefixLeaf == nil && prefixTrees.isEmpty && suffixTrees.isEmpty) + rope.invariantCheck() + return rope + } + + func invariantCheck() { +#if DEBUG + var h = UInt8.max + for sapling in prefixTrees { + precondition(sapling.height <= h) + sapling.invariantCheck() + h = sapling.height + } + if let seedling = self.prefixLeaf { + precondition(seedling.height == 0) + precondition(!seedling.isFull) + seedling.invariantCheck(depth: 0, height: 0) + } + h = 0 + for sapling in suffixTrees.reversed() { + precondition(sapling.height >= h) + sapling.invariantCheck() + h = sapling.height + } +#endif + + } + + func dump(heightLimit: Int = Int.max) { + for i in self.prefixTrees.indices { + print("Sapling \(i):") + self.prefixTrees[i].dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") + } + if let seedling = self.prefixLeaf { + print("Seedling:") + seedling.dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") + } + if let seed = self.prefix { + print("Seed:") + print(" \(seed)") + } + print("---") + var i = 0 + if let suffix = self.suffix { + print("Suffix \(i):") + i += 1 + print(" \(suffix)") + } + for suffix in self.suffixTrees.reversed() { + print("Suffix \(i)") + i += 1 + suffix.dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") + } + } + } +} diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift b/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift new file mode 100644 index 00000000..27543b48 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift @@ -0,0 +1,90 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +private func _addressString(for pointer: UnsafeRawPointer) -> String { + let address = UInt(bitPattern: pointer) + return "0x\(String(address, radix: 16))" +} + +private func _addressString(for object: AnyObject) -> String { + _addressString(for: Unmanaged.passUnretained(object).toOpaque()) +} + +private func _addressString(for object: Unmanaged) -> String { + _addressString(for: object.toOpaque()) +} + +extension _Rope { + var nodeCount: Int { _root?.nodeCount ?? 0 } +} + +extension _Rope.Node { + var nodeCount: Int { + guard !isLeaf else { return 1 } + return readInner { $0.children.reduce(into: 1) { $0 += $1.nodeCount } } + } +} + +extension _Rope { + internal func dump( + heightLimit: Int = .max, + firstPrefix: String = "", + restPrefix: String = "" + ) { + guard _root != nil else { + print("") + return + } + root.dump(heightLimit: heightLimit, firstPrefix: firstPrefix, restPrefix: restPrefix) + } +} + +extension _Rope.Node: CustomStringConvertible { + var description: String { + """ + \(height > 0 ? "Inner@\(height)" : "Leaf")(\ + at: \(_addressString(for: object)), \ + summary: \(summary), \ + childCount: \(childCount)/\(Summary.maxNodeSize)) + """ + } +} + +extension _Rope.Node { + internal func dump( + heightLimit: Int = .max, + firstPrefix: String = "", + restPrefix: String = "" + ) { + print("\(firstPrefix)\(description)") + + guard heightLimit > 0 else { return } + + if height > 0 { + readInner { + let c = $0.children + for slot in 0 ..< c.count { + c[slot].dump( + heightLimit: heightLimit - 1, + firstPrefix: "\(restPrefix)\(slot): ", + restPrefix: "\(restPrefix) ") + } + } + } else { + readLeaf { + let c = $0.children + for slot in 0 ..< c.count { + print("\(restPrefix)\(slot): \(c[slot])") + } + } + } + } +} diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift b/Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift new file mode 100644 index 00000000..3d398f0e --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + func invariantCheck() { +#if DEBUG + _root?.invariantCheck(depth: 0, height: root.height, recursive: true) +#endif + } +} + +extension _Rope.Node { + func invariantCheck(depth: UInt8, height: UInt8, recursive: Bool = true) { +#if DEBUG + precondition(height == self.height, "Mismatching rope height") + if isLeaf { + precondition(self.childCount <= Summary.maxNodeSize, "Oversized leaf") + precondition(height == 0, "Leaf with height > 0") + precondition(depth == 0 || self.childCount >= Summary.minNodeSize, "Undersized leaf") + + let sum: Summary = readLeaf { + $0.children.reduce(into: .zero) { $0.add($1.summary) } + } + precondition(self.summary == sum, "Mismatching summary") + + guard recursive else { return } + readLeaf { leaf in + for child in leaf.children { + child.value.invariantCheck() + } + } + return + } + + precondition(self.childCount <= Summary.maxNodeSize, "Oversized node") + if depth == 0 { + precondition(self.childCount > 1, "Undersize root node") + } else { + precondition(self.childCount >= Summary.minNodeSize, "Undersized internal node") + } + + let sum: Summary = readInner { + $0.children.reduce(into: .zero) { $0.add($1.summary) } + } + precondition(self.summary == sum, "Mismatching summary") + + guard recursive else { return } + readInner { h in + for child in h.children { + child.invariantCheck(depth: depth + 1, height: height - 1, recursive: true) + } + } +#endif + } +} diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Node.swift b/Sources/RopeModule/Rope/Basics/_Rope+Node.swift new file mode 100644 index 00000000..c4df69e0 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_Rope+Node.swift @@ -0,0 +1,499 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + struct Node: _RopeItem { + typealias Element = _Rope.Element + typealias Summary = _Rope.Summary + typealias Index = _Rope.Index + typealias Item = _Rope.Item + typealias Storage = _Rope.Storage + typealias UnsafeHandle = _Rope.UnsafeHandle + + var object: AnyObject + var summary: Summary + + init(leaf: Storage, summary: Summary? = nil) { + self.object = leaf + self.summary = .zero + self.summary = readLeaf { handle in + handle.children.reduce(into: .zero) { $0.add($1.summary) } + } + } + + init(inner: Storage, summary: Summary? = nil) { + assert(inner.header.height > 0) + self.object = inner + self.summary = .zero + self.summary = readInner { handle in + handle.children.reduce(into: .zero) { $0.add($1.summary) } + } + } + } +} + +extension _Rope.Node { + var _headerPtr: UnsafePointer<_RopeStorageHeader> { + let p = _getUnsafePointerToStoredProperties(object) + .assumingMemoryBound(to: _RopeStorageHeader.self) + return .init(p) + } + + var header: _RopeStorageHeader { + _headerPtr.pointee + } + + @inline(__always) + var height: UInt8 { header.height } + + @inline(__always) + var isLeaf: Bool { height == 0 } + + @inline(__always) + var asLeaf: Storage { + assert(height == 0) + return unsafeDowncast(object, to: Storage.self) + } + + @inline(__always) + var asInner: Storage { + assert(height > 0) + return unsafeDowncast(object, to: Storage.self) + } + + @inline(__always) + var childCount: Int { header.childCount } + + var isEmpty: Bool { childCount == 0 } + var isSingleton: Bool { isLeaf && childCount == 1 } + var isUndersized: Bool { childCount < Summary.minNodeSize } + var isFull: Bool { childCount == Summary.maxNodeSize } +} + +extension _Rope.Node { + static func createLeaf() -> Self { + Self(leaf: .create(height: 0), summary: Summary.zero) + } + + static func createLeaf(_ item: __owned Item) -> Self { + var leaf = createLeaf() + leaf._appendItem(item) + return leaf + } + + static func createInner(height: UInt8) -> Self { + Self(inner: .create(height: height), summary: .zero) + } + + static func createInner(children left: __owned Self, _ right: __owned Self) -> Self { + assert(left.height == right.height) + var new = createInner(height: left.height + 1) + new.summary = left.summary + new.summary.add(right.summary) + new.updateInner { h in + h._appendChild(left) + h._appendChild(right) + } + return new + } +} + +extension _Rope.Node { + @inline(__always) + mutating func isUnique() -> Bool { + isKnownUniquelyReferenced(&object) + } + + mutating func ensureUnique() { + guard !isKnownUniquelyReferenced(&object) else { return } + self = copy() + } + + @inline(never) + func copy() -> Self { + if isLeaf { + return Self(leaf: readLeaf { $0.copy() }, summary: self.summary) + } + return Self(inner: readInner { $0.copy() }, summary: self.summary) + } + + @inline(never) + func copy(slots: Range) -> Self { + if isLeaf { + let (object, summary) = readLeaf { $0.copy(slots: slots) } + return Self(leaf: object, summary: summary) + } + let (object, summary) = readInner { $0.copy(slots: slots) } + return Self(inner: object, summary: summary) + } + + @inline(__always) + func readLeaf( + _ body: (UnsafeHandle) -> R + ) -> R { + asLeaf.withUnsafeMutablePointers { h, p in + let handle = UnsafeHandle(isMutable: false, header: h, start: p) + return body(handle) + } + } + + @inline(__always) + mutating func updateLeaf( + _ body: (UnsafeHandle) -> R + ) -> R { + asLeaf.withUnsafeMutablePointers { h, p in + let handle = UnsafeHandle(isMutable: true, header: h, start: p) + return body(handle) + } + } + + @inline(__always) + func readInner( + _ body: (UnsafeHandle) -> R + ) -> R { + asInner.withUnsafeMutablePointers { h, p in + let handle = UnsafeHandle(isMutable: false, header: h, start: p) + return body(handle) + } + } + + @inline(__always) + mutating func updateInner( + _ body: (UnsafeHandle) -> R + ) -> R { + asInner.withUnsafeMutablePointers { h, p in + let handle = UnsafeHandle(isMutable: true, header: h, start: p) + return body(handle) + } + } +} + +extension _Rope.Node { + mutating func _insertItem(_ item: __owned Item, at slot: Int) { + assert(isLeaf) + ensureUnique() + self.summary.add(item.summary) + updateLeaf { $0._insertChild(item, at: slot) } + } + + mutating func _insertNode(_ node: __owned Self, at slot: Int) { + assert(!isLeaf) + assert(self.height == node.height + 1) + ensureUnique() + self.summary.add(node.summary) + updateInner { $0._insertChild(node, at: slot) } + } +} + +extension _Rope.Node { + mutating func _appendItem(_ item: __owned Item) { + assert(isLeaf) + ensureUnique() + self.summary.add(item.summary) + updateLeaf { $0._appendChild(item) } + } + + mutating func _appendNode(_ node: __owned Self) { + assert(!isLeaf) + ensureUnique() + self.summary.add(node.summary) + updateInner { $0._appendChild(node) } + } +} + +extension _Rope.Node { + mutating func _removeItem(at slot: Int) -> (removed: Item, delta: Summary) { + assert(isLeaf) + ensureUnique() + let item = updateLeaf { $0._removeChild(at: slot) } + let delta = item.summary + self.summary.subtract(delta) + return (item, delta) + } + + mutating func _removeNode(at slot: Int) -> Self { + assert(!isLeaf) + ensureUnique() + let result = updateInner { $0._removeChild(at: slot) } + self.summary.subtract(result.summary) + return result + } +} + +extension _Rope.Node { + mutating func split(keeping desiredCount: Int) -> Self { + assert(desiredCount >= 0 && desiredCount <= childCount) + var new = isLeaf ? Self.createLeaf() : Self.createInner(height: height) + guard desiredCount < childCount else { return new } + guard desiredCount > 0 else { + swap(&self, &new) + return new + } + ensureUnique() + new.prependChildren(movingFromSuffixOf: &self, count: childCount - desiredCount) + assert(childCount == desiredCount) + return new + } +} + +extension _Rope.Node { + mutating func rebalance(nextNeighbor right: inout _Rope.Node) -> Bool { + assert(self.height == right.height) + if self.isEmpty { + swap(&self, &right) + return true + } + guard self.isUndersized || right.isUndersized else { return false } + let c = self.childCount + right.childCount + let desired = ( + c <= Summary.maxNodeSize ? c + : c / 2 >= Summary.minNodeSize ? c / 2 + : Summary.minNodeSize + ) + Self.redistributeChildren(&self, &right, to: desired) + return right.isEmpty + } + + mutating func rebalance(prevNeighbor left: inout Self) -> Bool { + guard left.rebalance(nextNeighbor: &self) else { return false } + swap(&self, &left) + return true + } + + /// Shift children between `left` and `right` such that the number of children in `left` + /// becomes `target`. + internal static func redistributeChildren( + _ left: inout Self, + _ right: inout Self, + to target: Int + ) { + assert(left.height == right.height) + assert(target >= 0 && target <= Summary.maxNodeSize) + left.ensureUnique() + right.ensureUnique() + + let lc = left.childCount + let rc = right.childCount + let target = Swift.min(target, lc + rc) + let d = target - lc + if d == 0 { return } + + if d > 0 { + left.appendChildren(movingFromPrefixOf: &right, count: d) + } else { + right.prependChildren(movingFromSuffixOf: &left, count: -d) + } + } + + mutating func appendChildren(movingFromPrefixOf other: inout Self, count: Int) { + assert(self.height == other.height) + let delta: Summary + if isLeaf { + delta = self.updateLeaf { dst in + other.updateLeaf { src in + dst._appendChildren(movingFromPrefixOf: src, count: count) + } + } + } else { + delta = self.updateInner { dst in + other.updateInner { src in + dst._appendChildren(movingFromPrefixOf: src, count: count) + } + } + } + self.summary.add(delta) + other.summary.subtract(delta) + } + + mutating func prependChildren(movingFromSuffixOf other: inout Self, count: Int) { + assert(self.height == other.height) + let delta: Summary + if isLeaf { + delta = self.updateLeaf { dst in + other.updateLeaf { src in + dst._prependChildren(movingFromSuffixOf: src, count: count) + } + } + } else { + delta = self.updateInner { dst in + other.updateInner { src in + dst._prependChildren(movingFromSuffixOf: src, count: count) + } + } + } + self.summary.add(delta) + other.summary.subtract(delta) + } +} + +extension _Rope.Node { + var startIndex: Index { + var i = Index(height: self.height) + descendToFirstItem(under: &i) + return i + } + + var lastIndex: Index { + var i = Index(height: self.height) + descendToLastItem(under: &i) + return i + } + + func isAtEnd(_ i: Index) -> Bool { + i[height: self.height] == childCount + } + + func descendToFirstItem(under i: inout Index) { + i.clear(below: self.height + 1) + } + + func descendToLastItem(under i: inout Index) { + let h = self.height + let slot = self.childCount - 1 + i[height: h] = slot + if h > 0 { + readInner { $0.children[slot].descendToLastItem(under: &i) } + } + } + + func formSuccessor(of i: inout Index) -> Bool { + let h = self.height + var slot = i[height: h] + if h == 0 { + slot += 1 + guard slot < childCount else { return false } + i[height: h] = slot + return true + } + let success = readInner { $0.children[slot].formSuccessor(of: &i) } + if success { return true } + slot += 1 + guard slot < childCount else { return false } + i[height: h] = slot + i.clear(below: h) + return true + } + + func formPredecessor(of i: inout Index) -> Bool { + let h = self.height + var slot = i[height: h] + if h == 0 { + guard slot > 0 else { return false } + i[height: h] = slot - 1 + return true + } + return readInner { + let c = $0.children + if slot < c.count, c[slot].formPredecessor(of: &i) { + return true + } + guard slot > 0 else { return false } + slot -= 1 + i[height: h] = slot + c[slot].descendToLastItem(under: &i) + return true + } + } + + var lastItem: Item { + get { + self[lastIndex] + } + _modify { + assert(childCount > 0) + var state = _prepareModifyLast() + defer { + _ = _finalizeModify(&state) + } + yield &state.value + } + } + + var firstItem: Item { + get { + self[startIndex] + } + _modify { + yield &self[startIndex] + } + } + + subscript(i: Index) -> Item { + get { + let h = height + let slot = i[height: h] + precondition(slot < childCount, "Index out of bounds") + guard h == 0 else { + return readInner { $0.children[slot][i] } + } + return readLeaf { $0.children[slot] } + } + @inline(__always) + _modify { + var state = _prepareModify(at: i) + defer { + _ = _finalizeModify(&state) + } + yield &state.value + } + } + + struct ModifyState { + var index: Index + var value: Item + var summary: Summary + } + + mutating func _prepareModify(at i: Index) -> ModifyState { + ensureUnique() + let h = height + let slot = i[height: h] + precondition(slot < childCount, "Index out of bounds") + guard h == 0 else { + return updateInner { $0.mutableChildren[slot]._prepareModify(at: i) } + } + let value = updateLeaf { $0.mutableChildren.moveElement(from: slot) } + return ModifyState(index: i, value: value, summary: value.summary) + } + + mutating func _prepareModifyLast() -> ModifyState { + var i = Index(height: height) + return _prepareModifyLast(&i) + } + + mutating func _prepareModifyLast(_ i: inout Index) -> ModifyState { + ensureUnique() + let h = height + let slot = self.childCount - 1 + i[height: h] = slot + guard h == 0 else { + return updateInner { $0.mutableChildren[slot]._prepareModifyLast(&i) } + } + let value = updateLeaf { $0.mutableChildren.moveElement(from: slot) } + return ModifyState(index: i, value: value, summary: value.summary) + } + + mutating func _finalizeModify(_ state: inout ModifyState) -> Summary { + assert(isUnique()) + let h = height + let slot = state.index[height: h] + assert(slot < childCount, "Index out of bounds") + guard h == 0 else { + let delta = updateInner { $0.mutableChildren[slot]._finalizeModify(&state) } + summary.add(delta) + return delta + } + let delta = state.value.summary.subtracting(state.summary) + updateLeaf { $0.mutableChildren.initializeElement(at: slot, to: state.value) } + summary.add(delta) + return delta + } +} diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Storage.swift b/Sources/RopeModule/Rope/Basics/_Rope+Storage.swift new file mode 100644 index 00000000..20996192 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_Rope+Storage.swift @@ -0,0 +1,48 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +struct _RopeStorageHeader { + var _childCount: UInt16 + let height: UInt8 + + init(height: UInt8) { + self._childCount = 0 + self.height = height + } + + var childCount: Int { + get { + numericCast(_childCount) + } + set { + _childCount = numericCast(newValue) + } + } +} + +extension _Rope { + final class Storage>: ManagedBuffer<_RopeStorageHeader, Child> { + typealias Summary = Element.Summary + typealias UnsafeHandle = _Rope.UnsafeHandle + + static func create(height: UInt8) -> Storage { + let object = create(minimumCapacity: Summary.maxNodeSize) { _ in .init(height: height) } + return unsafeDowncast(object, to: Storage.self) + } + + deinit { + withUnsafeMutablePointers { h, p in + p.deinitialize(count: h.pointee.childCount) + h.pointee._childCount = .max + } + } + } +} diff --git a/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift b/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift new file mode 100644 index 00000000..4932182b --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift @@ -0,0 +1,188 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + struct UnsafeHandle> { + typealias Summary = _Rope.Summary + typealias Element = _Rope.Element + + let _header: UnsafeMutablePointer<_RopeStorageHeader> + let _start: UnsafeMutablePointer +#if DEBUG + let _isMutable: Bool +#endif + + init( + isMutable: Bool, + header: UnsafeMutablePointer<_RopeStorageHeader>, + start: UnsafeMutablePointer + ) { + self._header = header + self._start = start +#if DEBUG + self._isMutable = isMutable +#endif + } + + @inline(__always) + func assertMutable() { +#if DEBUG + assert(_isMutable) +#endif + } + } +} + +extension _Rope.UnsafeHandle { + @inline(__always) + var capacity: Int { Summary.maxNodeSize } + + @inline(__always) + var height: UInt8 { _header.pointee.height } + + var childCount: Int { + get { _header.pointee.childCount } + nonmutating set { + assertMutable() + _header.pointee.childCount = newValue + } + } + + var children: UnsafeBufferPointer { + UnsafeBufferPointer(start: _start, count: childCount) + } + + func child(at slot: Int) -> Child? { + assert(slot >= 0) + guard slot < childCount else { return nil } + return (_start + slot).pointee + } + + var mutableChildren: UnsafeMutableBufferPointer { + assertMutable() + return UnsafeMutableBufferPointer(start: _start, count: childCount) + } + + func mutableChildPtr(at slot: Int) -> UnsafeMutablePointer { + assertMutable() + assert(slot >= 0 && slot < childCount) + return _start + slot + } + + var mutableBuffer: UnsafeMutableBufferPointer { + assertMutable() + return UnsafeMutableBufferPointer(start: _start, count: capacity) + } + + func copy() -> _Rope.Storage { + let new = _Rope.Storage.create(height: self.height) + let c = self.childCount + new.header.childCount = c + new.withUnsafeMutablePointerToElements { target in + target.initialize(from: self._start, count: c) + } + return new + } + + func copy(slots: Range) -> (object: _Rope.Storage, summary: Summary) { + assert(slots.lowerBound >= 0 && slots.upperBound <= childCount) + let object = _Rope.Storage.create(height: self.height) + let c = slots.count + let summary = object.withUnsafeMutablePointers { h, p in + h.pointee.childCount = c + p.initialize(from: self._start + slots.lowerBound, count: slots.count) + return UnsafeBufferPointer(start: p, count: c)._sum() + } + return (object, summary) + } + + func _insertChild(_ child: __owned Child, at slot: Int) { + assertMutable() + assert(childCount < capacity) + assert(slot >= 0 && slot <= childCount) + (_start + slot + 1).moveInitialize(from: _start + slot, count: childCount - slot) + (_start + slot).initialize(to: child) + childCount += 1 + } + + func _appendChild(_ child: __owned Child) { + assertMutable() + assert(childCount < capacity) + (_start + childCount).initialize(to: child) + childCount += 1 + } + + func _removeChild(at slot: Int) -> Child { + assertMutable() + assert(slot >= 0 && slot < childCount) + let result = (_start + slot).move() + (_start + slot).moveInitialize(from: _start + slot + 1, count: childCount - slot) + childCount -= 1 + return result + } + + func _removePrefix(_ n: Int) -> Summary { + assertMutable() + assert(n <= childCount) + var delta = Summary.zero + let c = mutableChildren + for i in 0 ..< n { + let child = c.moveElement(from: i) + delta.add(child.summary) + } + childCount -= n + _start.moveInitialize(from: _start + n, count: childCount) + return delta + } + + func _removeSuffix(_ n: Int) -> Summary { + assertMutable() + assert(n <= childCount) + var delta = Summary.zero + let c = mutableChildren + for i in childCount - n ..< childCount { + let child = c.moveElement(from: i) + delta.add(child.summary) + } + childCount -= n + return delta + } + + func _appendChildren(movingFromPrefixOf src: Self, count: Int) -> Summary { + assertMutable() + src.assertMutable() + assert(self.height == src.height) + guard count > 0 else { return .zero } + assert(count >= 0 && count <= src.childCount) + assert(count <= capacity - self.childCount) + + (_start + childCount).moveInitialize(from: src._start, count: count) + src._start.moveInitialize(from: src._start + count, count: src.childCount - count) + childCount += count + src.childCount -= count + return children.suffix(count)._sum() + } + + func _prependChildren(movingFromSuffixOf src: Self, count: Int) -> Summary { + assertMutable() + src.assertMutable() + assert(self.height == src.height) + guard count > 0 else { return .zero } + assert(count >= 0 && count <= src.childCount) + assert(count <= capacity - childCount) + + (_start + count).moveInitialize(from: _start, count: childCount) + _start.moveInitialize(from: src._start + src.childCount - count, count: count) + childCount += count + src.childCount -= count + return children.prefix(count)._sum() + } +} diff --git a/Sources/RopeModule/Rope/Basics/_Rope.swift b/Sources/RopeModule/Rope/Basics/_Rope.swift new file mode 100644 index 00000000..a83a4b60 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_Rope.swift @@ -0,0 +1,56 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// An ordered data structure of `Element` values that organizes itself into a tree. +/// The rope is augmented by the commutative group specified by `Element.Summary`, enabling +/// quick lookup operations. +struct _Rope { + var _root: Node? + + init() { + self._root = nil + } + + init(root: Node?) { + self._root = root + } + + var root: Node { + get { _root.unsafelyUnwrapped } + @inline(__always) _modify { yield &_root! } + } + + init(_ value: Element) { + self._root = .createLeaf(Item(value)) + } +} + +extension _Rope: Sendable where Element: Sendable {} + +extension _Rope { + mutating func ensureUnique() { + guard _root != nil else { return } + root.ensureUnique() + } +} + +extension _Rope { + var isSingleton: Bool { + guard _root != nil else { return false } + return root.isSingleton + } +} + +extension _Rope { + func isIdentical(to other: Self) -> Bool { + self._root?.object === other._root?.object + } +} diff --git a/Sources/RopeModule/Rope/Basics/_RopeElement.swift b/Sources/RopeModule/Rope/Basics/_RopeElement.swift new file mode 100644 index 00000000..27477331 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_RopeElement.swift @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The element type of an augmented tree. +protocol _RopeElement { + /// The commutative group that is used to augment the tree. + associatedtype Summary: _RopeSummary + associatedtype Index: Comparable + + /// Returns the summary of `self`. + var summary: Summary { get } + + var isEmpty: Bool { get } + var isUndersized: Bool { get } + + /// Check the consistency of `self`. + func invariantCheck() + + mutating func rebalance(nextNeighbor right: inout Self) -> Bool + mutating func rebalance(prevNeighbor left: inout Self) -> Bool + mutating func split(at index: Index) -> Self +} + +extension _RopeElement { + mutating func rebalance(prevNeighbor left: inout Self) -> Bool { + guard left.rebalance(nextNeighbor: &self) else { return false } + swap(&self, &left) + return true + } +} + diff --git a/Sources/RopeModule/Rope/Basics/_RopeItem.swift b/Sources/RopeModule/Rope/Basics/_RopeItem.swift new file mode 100644 index 00000000..5fcfc469 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_RopeItem.swift @@ -0,0 +1,71 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// An internal protocol describing a summarizable entity that isn't a full `_RopeElement`. +/// +/// Used as an implementation detail to increase code reuse across internal nodes and leaf nodes. +/// (Ideally `_Rope.Node` would just conform to the full `_RopeElement` protocol on its own, but +/// while that's an obvious refactoring idea, it hasn't happened yet.) +internal protocol _RopeItem { + associatedtype Summary: _RopeSummary + + var summary: Summary { get } +} + +extension Sequence where Element: _RopeItem { + func _sum() -> Element.Summary { + self.reduce(into: .zero) { $0.add($1.summary) } + } +} + +extension _Rope: _RopeItem { + typealias Summary = Element.Summary + var summary: Summary { + guard _root != nil else { return .zero } + return root.summary + } +} + +extension _Rope { + /// A trivial wrapper around a rope's Element type, giving it `_RopeItem` conformance without + /// having to make the protocol public. + internal struct Item { + var value: Element + init(_ value: Element) { self.value = value } + } +} + +extension _Rope.Item: _RopeItem { + typealias Summary = _Rope.Summary + var summary: Summary { value.summary } +} + +extension _Rope.Item: CustomStringConvertible { + var description: String { + "\(value)" + } +} + +extension _Rope.Item { + var isEmpty: Bool { value.isEmpty } + var isUndersized: Bool { value.isUndersized } + mutating func rebalance(nextNeighbor right: inout Self) -> Bool { + value.rebalance(nextNeighbor: &right.value) + } + mutating func rebalance(prevNeighbor left: inout Self) -> Bool { + value.rebalance(prevNeighbor: &left.value) + } + + typealias Index = Element.Index + mutating func split(at index: Index) -> Self { + Self(self.value.split(at: index)) + } +} diff --git a/Sources/RopeModule/Rope/Basics/_RopeMetric.swift b/Sources/RopeModule/Rope/Basics/_RopeMetric.swift new file mode 100644 index 00000000..a4ea5717 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_RopeMetric.swift @@ -0,0 +1,26 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +protocol _RopeMetric: Sendable { + associatedtype Element: _RopeElement + + func size(of summary: Element.Summary) -> Int + func index(at offset: Int, in element: Element) -> Element.Index +} + +extension _RopeMetric { + @inline(__always) + func nonnegativeSize(of summary: Element.Summary) -> Int { + let r = size(of: summary) + assert(r >= 0) + return r + } +} diff --git a/Sources/RopeModule/Rope/Basics/_RopeSummary.swift b/Sources/RopeModule/Rope/Basics/_RopeSummary.swift new file mode 100644 index 00000000..4af962b2 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_RopeSummary.swift @@ -0,0 +1,55 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// A commutative group that is used to augment a tree, enabling quick lookup operations. +protocol _RopeSummary: Equatable, Sendable { + static var maxNodeSize: Int { get } + static var nodeSizeBitWidth: Int { get } + + /// The identity element of the group. + static var zero: Self { get } + + /// Returns a Boolean value that indicates whether `self` is the identity element. + var isZero: Bool { get } + + /// A commutative and associative operation that combines two instances. + /// + /// (As is usually the case, this operation is not necessarily closed over `Self` in practice -- + /// e.g., some results may not be representable.) + mutating func add(_ other: Self) + + /// A (potentially partial) subtraction function that undoes a previous combination of the given + /// element to `self`. + /// + /// The inverse of any instance can be calculated by subtracting it from the `zero` instance. + /// (However, conforming types are free to require that `subtract` only be called on values + /// that "include" the given `other`.) + mutating func subtract(_ other: Self) +} + +extension _RopeSummary { + @inline(__always) + static var minNodeSize: Int { maxNodeSize / 2 } +} + +extension _RopeSummary { + func adding(_ other: Self) -> Self { + var c = self + c.add(other) + return c + } + + func subtracting(_ other: Self) -> Self { + var c = self + c.subtract(other) + return c + } +} diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift new file mode 100644 index 00000000..a6368fcb --- /dev/null +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift @@ -0,0 +1,360 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope: BidirectionalCollection { + var height: UInt8 { _root?.height ?? 0 } + + var isEmpty: Bool { + guard _root != nil else { return true } + return root.childCount == 0 + } + + var startIndex: Index { Index(height: height) } + + var endIndex: Index { + guard let root = _root else { return startIndex } + var i = Index(height: height) + i[height: height] = root.childCount + return i + } + + func index(after i: Index) -> Index { + var i = i + formIndex(after: &i) + return i + } + + func index(before i: Index) -> Index { + var i = i + formIndex(before: &i) + return i + } + + func formIndex(after i: inout Index) { + precondition(i < endIndex, "Can't move after endIndex") + if !root.formSuccessor(of: &i) { + i = endIndex + } + } + + func formIndex(before i: inout Index) { + precondition(i > startIndex, "Can't move before startIndex") + let success = root.formPredecessor(of: &i) + precondition(success, "Invalid index") + } + + subscript(i: Index) -> Element { + get { root[i].value } + @inline(__always) _modify { yield &root[i].value } + } +} + +extension _Rope { + struct Index { + typealias Summary = _Rope.Summary + + var _height: UInt8 + var _path: UInt64 + + init(height: UInt8) { + self._height = height + self._path = 0 + assert(Int(_height + 1) * Summary.nodeSizeBitWidth < UInt64.bitWidth) + } + } +} + +extension _Rope.Index: Equatable { + static func ==(left: Self, right: Self) -> Bool { + left._height == right._height && left._path == right._path + } +} +extension _Rope.Index: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(_height) + hasher.combine(_path) + } +} + +extension _Rope.Index: Comparable { + static func <(left: Self, right: Self) -> Bool { + (left._height, left._path) < (right._height, right._path) + } +} + +extension _Rope.Index: CustomStringConvertible { + var description: String { + var r = "<" + for h in stride(from: _height, through: 0, by: -1) { + r += "\(self[height: h])" + if h > 0 { r += ", " } + } + r += ">" + return r + } +} + +extension _Rope.Index { + subscript(height height: UInt8) -> Int { + get { + assert(height <= self._height) + let shift = Int(height) * Summary.nodeSizeBitWidth + let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1 + return numericCast((_path &>> shift) & mask) + } + set { + assert(height <= self._height) + assert(newValue >= 0 && newValue <= Summary.maxNodeSize) + let shift = Int(height) * Summary.nodeSizeBitWidth + let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1 + _path &= ~(mask &<< shift) + _path |= numericCast(newValue) &<< shift + } + } + + func isEmpty(below height: UInt8) -> Bool { + let shift = Int(height) * Summary.nodeSizeBitWidth + assert(shift + Summary.nodeSizeBitWidth < UInt64.bitWidth) + let mask: UInt64 = (1 &<< shift) - 1 + return (_path & mask) == 0 + } + + mutating func clear(below height: UInt8) { + let shift = Int(height) * Summary.nodeSizeBitWidth + assert(shift + Summary.nodeSizeBitWidth < UInt64.bitWidth) + let mask: UInt64 = (1 &<< shift) - 1 + _path &= ~mask + } +} + +extension _Rope { + func count(in metric: some _RopeMetric) -> Int { + guard _root != nil else { return 0 } + return root.count(in: metric) + } +} + +extension _Rope.Node { + func count(in metric: some _RopeMetric) -> Int { + metric.nonnegativeSize(of: self.summary) + } +} + +extension _Rope { + func distance(from start: Index, to end: Index, in metric: some _RopeMetric) -> Int { + if start == end { return 0 } + precondition(_root != nil, "Invalid index") + if start < end { + return root.distance(from: start, to: end, in: metric) + } + return -root.distance(from: end, to: start, in: metric) + } +} + +extension _Rope.Node { + func distanceFromStart(to index: Index, in metric: some _RopeMetric) -> Int { + let slot = index[height: height] + precondition(slot <= childCount, "Invalid index") + if slot == childCount { + precondition(index.isEmpty(below: height), "Invalid index") + return metric.nonnegativeSize(of: self.summary) + } + if height == 0 { + return readLeaf { + $0.children[..) -> Int { + let d = metric.nonnegativeSize(of: self.summary) - self.distanceFromStart(to: index, in: metric) + assert(d >= 0) + return d + } + + func distance(from start: Index, to end: Index, in metric: some _RopeMetric) -> Int { + assert(start < end) + let a = start[height: height] + let b = end[height: height] + precondition(a < childCount, "Invalid index") + precondition(b <= childCount, "Invalid index") + assert(a <= b) + if b == childCount { + precondition(end.isEmpty(below: height), "Invalid index") + return distanceToEnd(from: start, in: metric) + } + if height == 0 { + assert(a < b) + return readLeaf { + $0.children[a.., + preferEnd: Bool + ) { + if _root == nil { + precondition(distance == 0, "Position out of bounds") + return + } + if distance <= 0 { + distance = -distance + let success = root.seekBackward( + from: &i, by: &distance, in: metric, preferEnd: preferEnd) + precondition(success, "Position out of bounds") + return + } + if root.seekForward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) { + return + } + precondition(distance == 0, "Position out of bounds") + i = endIndex + } + + func index( + _ i: Index, offsetBy distance: Int, in metric: some _RopeMetric, preferEnd: Bool + ) -> (index: Index, remainder: Int) { + var i = i + var distance = distance + formIndex(&i, offsetBy: &distance, in: metric, preferEnd: preferEnd) + return (i, distance) + } +} + +extension _Rope.Node { + func seekForward( + from i: inout Index, + by distance: inout Int, + in metric: some _RopeMetric, + preferEnd: Bool + ) -> Bool { + assert(distance >= 0) + var slot = i[height: height] + precondition(slot < childCount, "Invalid index") + + if height == 0 { + return readLeaf { + let c = $0.children + while slot < c.count { + let d = metric.nonnegativeSize(of: c[slot].summary) + if preferEnd ? d >= distance : d > distance { + i[height: 0] = slot + return true + } + distance &-= d + slot &+= 1 + } + return false + } + } + + return readInner { + let c = $0.children + if c[slot].seekForward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) { + return true + } + slot &+= 1 + while slot < c.count { + let d = metric.size(of: c[slot].summary) + if preferEnd ? d >= distance : d > distance { + i[height: $0.height] = slot + i.clear(below: $0.height) + let success = c[slot].seekForward( + from: &i, by: &distance, in: metric, preferEnd: preferEnd) + precondition(success) + return true + } + distance &-= d + slot &+= 1 + } + return false + } + } + + func seekBackward( + from i: inout Index, + by distance: inout Int, + in metric: some _RopeMetric, + preferEnd: Bool + ) -> Bool { + assert(distance >= 0) + guard distance > 0 || preferEnd else { return true } + var slot = i[height: height] + precondition(slot <= childCount, "Invalid index") + + if height == 0 { + return readLeaf { + let c = $0.children + slot &-= 1 + while slot >= 0 { + let d = metric.nonnegativeSize(of: c[slot].summary) + if preferEnd ? d > distance : d >= distance { + i[height: 0] = slot + distance = d &- distance + return true + } + distance &-= d + slot &-= 1 + } + return false + } + } + + return readInner { + let c = $0.children + if slot < childCount, + c[slot].seekBackward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) { + return true + } + slot -= 1 + while slot >= 0 { + let d = metric.size(of: c[slot].summary) + if preferEnd ? d > distance : d >= distance { + i[height: $0.height] = slot + i.clear(below: $0.height) + distance = d - distance + let success = c[slot].seekForward( + from: &i, by: &distance, in: metric, preferEnd: preferEnd) + precondition(success) + return true + } + distance -= d + slot -= 1 + } + return false + } + } +} diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift new file mode 100644 index 00000000..107a2e59 --- /dev/null +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift @@ -0,0 +1,103 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope: Sequence { + func makeIterator() -> Iterator { + Iterator(self, from: self.startIndex) + } + + func makeIterator(from start: Index) -> Iterator { + Iterator(self, from: start) + } + + struct Iterator: IteratorProtocol { + private let rope: _Rope + private(set) var index: Index + private var leaf: Node? + + init(_ rope: _Rope, from start: Index) { + self.rope = rope + self.index = start + self.leaf = start == rope.endIndex ? nil : rope._leaf(at: start) + } + + var isAtEnd: Bool { + leaf == nil + } + + var isAtStart: Bool { + index == rope.startIndex + } + + var current: Element { + leaf!.readLeaf { $0.children[index[height: 0]].value } + } + + func withCurrent(_ body: (Element) -> R) -> R { + leaf!.readLeaf { body($0.children[index[height: 0]].value) } + } + + mutating func stepForward() -> Bool { + guard let leaf = self.leaf else { return false } + self.leaf = nil + if leaf.formSuccessor(of: &index) { + self.leaf = leaf + } else if rope.root.formSuccessor(of: &index) { + self.leaf = rope._leaf(at: index) + } else { + self.leaf = leaf + return false + } + return true + } + + mutating func stepBackward() -> Bool { + guard let leaf = self.leaf else { + guard !rope.isEmpty else { return false } + self.index = rope.index(before: rope.endIndex) + self.leaf = rope._leaf(at: index) + return true + } + self.leaf = nil + if leaf.formPredecessor(of: &index) { + self.leaf = leaf + } else if rope.root.formPredecessor(of: &index) { + self.leaf = rope._leaf(at: index) + } else { + self.leaf = leaf + return false + } + return true + } + + mutating func next() -> Element? { + guard !isAtEnd else { return nil } + let item = self.current + if !stepForward() { leaf = nil; index = rope.endIndex } + return item + } + } +} + +extension _Rope { + func _leaf(at index: Index) -> Node? { + assert(index._height == root.height) + var node = root + while true { + let h = node.height + let slot = index[height: h] + guard slot < node.childCount else { return nil } + if h == 0 { break } + node = node.readInner { $0.child(at: slot)! } + } + return node + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Append.swift b/Sources/RopeModule/Rope/Operations/_Rope+Append.swift new file mode 100644 index 00000000..96a0421e --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+Append.swift @@ -0,0 +1,71 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + mutating func append(_ item: __owned Element) { + if _root == nil { + _root = .createLeaf(Item(item)) + return + } + if let spawn = root.append(Item(item)) { + _root = .createInner(children: root, spawn) + } + } +} + +extension _Rope.Node { + mutating func append(_ item: __owned Item) -> Self? { + var item = item + if item.isUndersized, !self.isEmpty, self.lastItem.rebalance(nextNeighbor: &item) { + return nil + } + ensureUnique() + if height > 0 { + var summary = self.summary + let spawn = updateInner { + let p = $0.mutableChildPtr(at: $0.childCount - 1) + summary.subtract(p.pointee.summary) + let spawn = p.pointee.append(item) + summary.add(p.pointee.summary) + return spawn + } + self.summary = summary + guard let spawn = spawn else { return nil } + +#if true // Compress existing nodes if possible. + updateInner { + let c = $0.mutableChildren + let s = c[c.count - 2].childCount + c[c.count - 1].childCount + if s <= Summary.maxNodeSize { + Self.redistributeChildren(&c[c.count - 2], &c[c.count - 1], to: s) + let removed = $0._removeChild(at: c.count - 1) + assert(removed.childCount == 0) + } + } +#endif + guard isFull else { + _appendNode(spawn) + return nil + } + + var spawn2 = split(keeping: childCount / 2) + spawn2._appendNode(spawn) + return spawn2 + } + guard isFull else { + _appendItem(item) + return nil + } + var spawn = split(keeping: childCount / 2) + spawn._appendItem(item) + return spawn + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift new file mode 100644 index 00000000..4627b6de --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift @@ -0,0 +1,82 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + func find( + at position: Int, + in metric: some _RopeMetric, + preferEnd: Bool + ) -> (index: Index, node: Node?, remaining: Int) { + let wholeSize = _root == nil ? 0 : metric.size(of: root.summary) + precondition(position >= 0 && position <= wholeSize, "Position out of bounds") + guard preferEnd || position < wholeSize else { + return (endIndex, nil, position) + } + var position = position + var node = root + var index = Index(height: node.height) + while node.height > 0 { + node = node.readInner { + let r = $0.findSlot(at: position, in: metric, preferEnd: preferEnd) + position = r.remaining + index[height: $0.height] = r.slot + return $0.children[r.slot] + } + } + let r = node.readLeaf { $0.findSlot(at: position, in: metric, preferEnd: preferEnd) } + index[height: 0] = r.slot + return (index, node, r.remaining) + } +} + +extension _Rope.UnsafeHandle { + func findSlot( + at position: Int, + in metric: some _RopeMetric, + preferEnd: Bool = true + ) -> (slot: Int, remaining: Int) { + var remaining = position + var size = 0 + for slot in 0 ..< childCount { + size = metric.size(of: children[slot].summary) + let next = remaining - size + let adjustment = (preferEnd ? 0 : 1) + if next + adjustment <= 0 { + return (slot, remaining) + } + remaining = next + } + precondition(remaining == 0, "Position out of bounds") + return preferEnd ? (childCount - 1, remaining + size) : (childCount, 0) + } + + func findSlot( + from p: (slot: Int, remaining: Int), + offsetBy distance: Int, + in metric: some _RopeMetric, + preferEnd: Bool = true + ) -> (slot: Int, remaining: Int) { + assert(p.slot >= 0 && p.slot < childCount) + assert(p.remaining >= 0 && p.remaining <= metric.size(of: children[p.slot].summary)) + assert(distance >= 0) + let adjustment = (preferEnd ? 0 : 1) + var d = p.remaining + distance + var slot = p.slot + while slot < childCount { + let size = metric.size(of: children[slot].summary) + if d + adjustment <= size { break } + d -= size + slot += 1 + } + assert(slot < childCount || d == 0) + return (slot, d) + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift b/Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift new file mode 100644 index 00000000..aae7ca11 --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift @@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + func forEachWhile( + _ body: (Element) -> Bool + ) -> Bool { + guard _root != nil else { return true } + return root.forEachWhile(body) + } + + func forEachWhile( + from position: Int, + in metric: some _RopeMetric, + _ body: (Element, Element.Index?) -> Bool + ) -> Bool { + guard _root != nil else { + precondition(position == 0, "Position out of bounds") + return true + } + return root.forEachWhile(from: position, in: metric, body) + } +} + +extension _Rope.Node { + func forEachWhile( + _ body: (Element) -> Bool + ) -> Bool { + if isLeaf { + return readLeaf { + let c = $0.children + for i in 0 ..< c.count { + guard body(c[i].value) else { return false } + } + return true + } + } + return readInner { + let c = $0.children + for i in 0 ..< c.count { + guard c[i].forEachWhile(body) else { return false } + } + return true + } + } + + func forEachWhile( + from position: Int, + in metric: some _RopeMetric, + _ body: (Element, Element.Index?) -> Bool + ) -> Bool { + if isLeaf { + return readLeaf { + let c = $0.children + var (slot, rem) = $0.findSlot(at: position, in: metric, preferEnd: false) + let i = metric.index(at: rem, in: c[slot].value) + if !body(c[slot].value, i) { return false } + slot += 1 + while slot < c.count { + if !body(c[slot].value, nil) { return false } + slot += 1 + } + return true + } + } + return readInner { + let c = $0.children + var (slot, rem) = $0.findSlot(at: position, in: metric, preferEnd: false) + if !c[slot].forEachWhile(from: rem, in: metric, body) { return false } + slot += 1 + while slot < c.count { + if !c[slot].forEachWhile({ body($0, nil) }) { return false } + slot += 1 + } + return true + } + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift b/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift new file mode 100644 index 00000000..d18a2eda --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift @@ -0,0 +1,191 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + mutating func prepend(_ item: __owned Element) { + insert(item, at: startIndex) + } + + mutating func insert( + _ item: __owned Element, + at index: Index + ) { + if index == endIndex { + append(item) + return + } + if let spawn = root.insert(Item(item), at: index) { + _root = .createInner(children: root, spawn) + } + } + + mutating func insert( + _ item: __owned Element, + at position: Int, + in metric: some _RopeMetric + ) { + if position == metric.size(of: summary) { + append(item) + return + } + if let spawn = root.insert(Item(item), at: position, in: metric) { + _root = .createInner(children: root, spawn) + } + } +} + +extension _Rope.Node { + mutating func prepend(_ item: __owned Item) -> Self? { + insert(item, at: startIndex) + } + + mutating func insert( + _ item: __owned Item, + at index: Index + ) -> Self? { + ensureUnique() + let h = height + let slot = index[height: h] + if h > 0 { + precondition(slot < childCount, "Index out of bounds") + return _innerInsert(at: slot) { $0.insert(item, at: index) } + } + precondition(slot <= childCount, "Index out of bounds") + return _leafInsert(item, at: slot) + } + + mutating func insert( + _ item: __owned Item, + at position: Int, + in metric: some _RopeMetric + ) -> Self? { + ensureUnique() + if height > 0 { + let (slot, remaining) = readInner { + $0.findSlot(at: position, in: metric, preferEnd: false) + } + return _innerInsert(at: slot) { $0.insert(item, at: remaining, in: metric) } + } + let (slot, remaining) = readLeaf { + $0.findSlot(at: position, in: metric, preferEnd: false) + } + precondition(remaining == 0, "Inserted element doesn't fall on an element boundary") + return _leafInsert(item, at: slot) + } +} + +extension _Rope.Node { + mutating func _innerInsert( + at slot: Int, + with body: (inout Self) -> Self? + ) -> Self? { + assert(slot < childCount) + var summary = self.summary + let spawn = updateInner { + let p = $0.mutableChildPtr(at: slot) + summary.subtract(p.pointee.summary) + let spawn = body(&p.pointee) + summary.add(p.pointee.summary) + return spawn + } + self.summary = summary + guard let spawn = spawn else { return nil } + return _applySpawn(spawn, of: slot) + } + + mutating func _applySpawn(_ spawn: __owned Self, of slot: Int) -> Self? { + var spawn = spawn + var nextSlot = slot + 1 +#if true // Compress existing nodes if possible. + if slot > 0 { + // Try merging remainder into previous child. + updateInner { + let c = $0.mutableChildren + let s = c[slot - 1].childCount + c[slot].childCount + guard s <= Summary.maxNodeSize else { return } + Self.redistributeChildren(&c[slot - 1], &c[slot], to: s) + let removed = $0._removeChild(at: slot) + assert(removed.childCount == 0) + nextSlot -= 1 + } + } + if nextSlot < childCount { + // Try merging new spawn into subsequent child. + let merged: Summary? = updateInner { + let c = $0.mutableChildren + let s = spawn.childCount + c[nextSlot].childCount + guard s <= Summary.maxNodeSize else { return nil } + let summary = spawn.summary + Self.redistributeChildren(&spawn, &c[nextSlot], to: 0) + assert(spawn.childCount == 0) + return summary + } + if let merged = merged { + self.summary.add(merged) + return nil + } + } +#endif + guard isFull else { + _insertNode(spawn, at: nextSlot) + return nil + } + var spawn2 = split(keeping: childCount / 2) + if nextSlot < childCount { + _insertNode(spawn, at: nextSlot) + } else { + spawn2._insertNode(spawn, at: nextSlot - childCount) + } + return spawn2 + } +} + +extension _Rope.Node { + mutating func _leafInsert(_ item: __owned Item, at slot: Int) -> Self? { + assert(slot <= childCount) + var item = item + if item.isUndersized, childCount > 0, _rebalanceBeforeInsert(&item, at: slot) { + return nil + } + + guard isFull else { + _insertItem(item, at: slot) + return nil + } + var spawn = split(keeping: childCount / 2) + if slot <= childCount { + _insertItem(item, at: slot) + } else { + spawn._insertItem(item, at: slot - childCount) + } + return spawn + } + + mutating func _rebalanceBeforeInsert(_ item: inout Item, at slot: Int) -> Bool { + assert(item.isUndersized) + let r = updateLeaf { (h) -> (merged: Bool, delta: Summary) in + if slot > 0 { + let p = h.mutableChildPtr(at: slot - 1) + let sum = p.pointee.summary + let merged = p.pointee.rebalance(nextNeighbor: &item) + let delta = p.pointee.summary.subtracting(sum) + return (merged, delta) + } + let p = h.mutableChildPtr(at: slot) + let sum = p.pointee.summary + let merged = p.pointee.rebalance(prevNeighbor: &item) + let delta = p.pointee.summary.subtracting(sum) + return (merged, delta) + } + self.summary.add(r.delta) + return r.merged + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Join.swift b/Sources/RopeModule/Rope/Operations/_Rope+Join.swift new file mode 100644 index 00000000..ca337d43 --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+Join.swift @@ -0,0 +1,115 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + mutating func append(_ other: __owned Self) { + self = _Rope.join(self, other) + } + + mutating func prepend(_ other: __owned Self) { + self = _Rope.join(other, self) + } + + mutating func append(_ other: __owned Node) { + append(Self(root: other)) + } + + mutating func prepend(_ other: __owned Node) { + prepend(Self(root: other)) + } + + /// Concatenate `left` and `right` by linking up the two trees. + static func join(_ left: __owned Self, _ right: __owned Self) -> Self { + guard !right.isEmpty else { return left } + guard !left.isEmpty else { return right } + + var left = left.root + var right = right.root + + left.ensureUnique() + right.ensureUnique() + + if left.height >= right.height { + let r = left._graftBack(&right) + guard let remainder = r.remainder else { return Self(root: left) } + assert(left.height == remainder.height) + let root = Node.createInner(children: left, remainder) + return Self(root: root) + + } + let r = right._graftFront(&left) + guard let remainder = r.remainder else { return Self(root: right) } + assert(right.height == remainder.height) + let root = Node.createInner(children: remainder, right) + return Self(root: root) + } +} + +extension _Rope.Node { + mutating func _graftFront(_ scion: inout Self) -> (remainder: Self?, delta: Summary) { + assert(self.height >= scion.height) + guard self.height > scion.height else { + assert(self.height == scion.height) + let d = scion.summary + if self.rebalance(prevNeighbor: &scion) { + return (nil, d) + } + assert(!scion.isEmpty) + return (scion, d.subtracting(scion.summary)) + } + + var (remainder, delta) = self.updateInner { h in + h.mutableChildren[0]._graftFront(&scion) + } + self.summary.add(delta) + guard let remainder = remainder else { return (nil, delta) } + assert(self.height == remainder.height + 1) + assert(!remainder.isUndersized) + guard self.isFull else { + delta.add(remainder.summary) + self._insertNode(remainder, at: 0) + return (nil, delta) + } + var splinter = self.split(keeping: self.childCount / 2) + + swap(&self, &splinter) + delta.subtract(splinter.summary) + splinter._insertNode(remainder, at: 0) + return (splinter, delta) + } + + mutating func _graftBack(_ scion: inout Self) -> (remainder: Self?, delta: Summary) { + assert(self.height >= scion.height) + guard self.height > scion.height else { + assert(self.height == scion.height) + let origSum = self.summary + let emptied = self.rebalance(nextNeighbor: &scion) + return (emptied ? nil : scion, self.summary.subtracting(origSum)) + } + + var (remainder, delta) = self.updateInner { h in + h.mutableChildren[h.childCount - 1]._graftBack(&scion) + } + self.summary.add(delta) + guard let remainder = remainder else { return (nil, delta) } + assert(self.height == remainder.height + 1) + assert(!remainder.isUndersized) + guard self.isFull else { + delta.add(remainder.summary) + self._appendNode(remainder) + return (nil, delta) + } + var splinter = self.split(keeping: self.childCount / 2) + delta.subtract(splinter.summary) + splinter._appendNode(remainder) + return (splinter, delta) + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift b/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift new file mode 100644 index 00000000..1243c39a --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift @@ -0,0 +1,87 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + @inline(__always) + @discardableResult + mutating func mutatingForEach( + _ body: (inout Element) -> R? + ) -> R? { + var i = startIndex + return mutatingForEach(from: &i, body) + } + + @inline(__always) + @discardableResult + mutating func mutatingForEach( + from index: inout Index, + _ body: (inout Element) -> R? + ) -> R? { + var r: R? = nil + let completed = _mutatingForEach(from: &index) { + r = body(&$0) + return r == nil + } + assert(completed == (r == nil)) + return r + } + + mutating func _mutatingForEach( + from index: inout Index, + _ body: (inout Element) -> Bool + ) -> Bool { + guard _root != nil else { return true } + return root.mutatingForEach(from: &index, body: body).continue + } +} + +extension _Rope.Node { + mutating func mutatingForEach( + from index: inout Index, + body: (inout Element) -> Bool + ) -> (continue: Bool, delta: Summary) { + ensureUnique() + let h = height + var slot = index[height: h] + precondition(slot <= childCount, "Index out of bounds") + guard slot < childCount else { return (true, .zero) } + var delta = Summary.zero + defer { self.summary.add(delta) } + if h > 0 { + let r = updateInner { + let c = $0.mutableChildren + while slot < c.count { + let (r, d) = c[slot].mutatingForEach(from: &index, body: body) + delta.add(d) + guard r else { return false } + slot += 1 + index.clear(below: h) + index[height: h] = slot + } + return true + } + return (r, delta) + } + let r = updateLeaf { + let c = $0.mutableChildren + while slot < c.count { + let sum = c[slot].summary + let r = body(&c[slot].value) + delta.add(c[slot].summary.subtracting(sum)) + guard r else { return false } + slot += 1 + index[height: h] = slot + } + return true + } + return (r, delta) + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift new file mode 100644 index 00000000..96ce7809 --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift @@ -0,0 +1,123 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + mutating func remove(at index: Index) -> Element { + let old = root.remove(at: index).removed + if root.isEmpty { + _root = nil + } else if root.childCount == 1, root.height > 0 { + root = root.readInner { $0.children.first! } + } + return old.value + } +} + +extension _Rope.Node { + mutating func remove( + at index: Index + ) -> (removed: Item, delta: Summary, needsFixing: Bool) { + ensureUnique() + let slot = index[height: height] + precondition(slot < childCount, "Invalid index") + guard height > 0 else { + let r = _removeItem(at: slot) + return (r.removed, r.delta, self.isUndersized) + } + let r = updateInner { $0.mutableChildren[slot].remove(at: index) } + self.summary.subtract(r.delta) + if r.needsFixing { + fixDeficiency(at: slot) + } + return (r.removed, r.delta, self.isUndersized) + } +} + +extension _Rope { + mutating func remove( + at position: Int, + in metric: some _RopeMetric + ) -> Element { + let old = root.remove(at: position, in: metric).removed + if root.isEmpty { + _root = nil + } else if root.childCount == 1, root.height > 0 { + root = root.readInner { $0.children.first! } + } + return old.value + } +} + +extension _Rope.Node { + mutating func remove( + at position: Int, + in metric: some _RopeMetric + ) -> (removed: Item, delta: Summary, needsFixing: Bool) { + ensureUnique() + guard height > 0 else { + let (slot, remaining) = readLeaf { + $0.findSlot(at: position, in: metric, preferEnd: false) + } + precondition(remaining == 0, "Element to be removed doesn't fall on an element boundary") + let r = _removeItem(at: slot) + return (r.removed, r.delta, self.isUndersized) + } + let (slot, r) = updateInner { + let (slot, remaining) = $0.findSlot(at: position, in: metric, preferEnd: false) + return (slot, $0.mutableChildren[slot].remove(at: remaining, in: metric)) + } + self.summary.subtract(r.delta) + if r.needsFixing { + fixDeficiency(at: slot) + } + return (r.removed, r.delta, self.isUndersized) + } +} + +extension _Rope.Node { + mutating func fixDeficiency(at slot: Int) { + assert(isUnique()) + updateInner { + let c = $0.mutableChildren + assert(c[slot].isUndersized) + guard c.count > 1 else { return } + let prev = slot - 1 + let prevSum = prev >= 0 ? c[prev].childCount + c[slot].childCount : 0 + if prev >= 0, prevSum <= Summary.maxNodeSize { + Self.redistributeChildren(&c[prev], &c[slot], to: prevSum) + assert(c[slot].isEmpty) + _ = $0._removeChild(at: slot) + return + } + + let next = slot + 1 + let nextSum = next < c.count ? c[slot].childCount + c[next].childCount : 0 + if next < c.count, nextSum <= Summary.maxNodeSize { + Self.redistributeChildren(&c[slot], &c[next], to: nextSum) + assert(c[next].isEmpty) + _ = $0._removeChild(at: next) + return + } + if prev >= 0 { + assert(c[prev].childCount > Summary.minNodeSize) + Self.redistributeChildren(&c[prev], &c[slot], to: prevSum / 2) + assert(!c[prev].isUndersized) + assert(!c[slot].isUndersized) + return + } + assert(next < c.count) + assert(c[next].childCount > Summary.minNodeSize) + Self.redistributeChildren(&c[slot], &c[next], to: nextSum / 2) + assert(!c[slot].isUndersized) + assert(!c[next].isUndersized) + } + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift b/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift new file mode 100644 index 00000000..47aabed5 --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift @@ -0,0 +1,308 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + mutating func removeSubrange( + _ bounds: Range, + in metric: some _RopeMetric + ) { + precondition( + bounds.lowerBound >= 0 && bounds.upperBound <= count(in: metric), + "Position out of bounds") + guard !bounds.isEmpty else { return } + // FIXME: Add fast path for tiny removals + var builder = builder(removing: bounds, in: metric) + self = builder.finalize() + } + + mutating func replaceSubrange( + _ bounds: Range, + in metric: some _RopeMetric, + with newElements: __owned some Collection + ) { + // FIXME: Implement insert(contentsOf:at:in:) and dispatch to it when bounds.isEmpty. + // FIXME: Add fast path for replacing tiny ranges with tiny data. + // FIXME: Add special cases if newElements is itself a _Rope etc. + var builder = builder(removing: bounds, in: metric) + for item in newElements { + builder.append(item) + } + self = builder.finalize() + } + + mutating func builder( + removing bounds: Range, + in metric: some _RopeMetric + ) -> Builder { + let size = metric.size(of: summary) + precondition(bounds.lowerBound >= 0 && bounds.upperBound <= size, "Position out of bounds") + + guard !bounds.isEmpty else { + return builder(splittingAt: bounds.lowerBound, in: metric) + } + + var builder = Builder() + var node = root + _root = nil + var lower = bounds.lowerBound + var upper = bounds.upperBound + while !node.isLeaf { + let (l, u) = node.readInner { + let l = $0.findSlot(at: lower, in: metric, preferEnd: false) + let u = $0.findSlot(from: l, offsetBy: upper - lower, in: metric, preferEnd: true) + return (l, u) + } + if l.slot < u.slot { + node._removeSubrange(from: l, to: u, in: metric, into: &builder) + return builder + } + assert(l.slot == u.slot) + node._innerSplit(at: l.slot, into: &builder) + lower = l.remaining + upper = u.remaining + } + + let (l, u) = node.readLeaf { + let l = $0.findSlot(at: lower, in: metric, preferEnd: false) + let u = $0.findSlot(from: l, offsetBy: bounds.count, in: metric, preferEnd: true) + return (l, u) + } + if l.slot < u.slot { + node._removeSubrange(from: l, to: u, in: metric, into: &builder) + return builder + } + assert(l.slot == u.slot) + var item = node._leafSplit(at: l.slot, into: &builder) + let i2 = metric.index(at: u.remaining, in: item.value) + builder.prependSuffix(Item(item.value.split(at: i2))) + let i1 = metric.index(at: l.remaining, in: item.value) + _ = item.split(at: i1) + builder.append(item.value) + return builder + } +} + +extension _Rope.Node { + __consuming func _removeSubrange( + from start: (slot: Int, remaining: Int), + to end: (slot: Int, remaining: Int), + in metric: some _RopeMetric, + into builder: inout _Rope.Builder + ) { + assert(start.slot >= 0 && start.slot < end.slot && end.slot < childCount) + assert(start.remaining >= 0) + assert(end.remaining >= 0) + + builder.append(slots: 0 ..< start.slot, in: self) + if end.slot < childCount { + builder.prependSuffix(slots: end.slot + 1 ..< childCount, in: self) + } + + guard isLeaf else { + // Extract children on boundaries. + let (lower, upper) = readInner { ($0.children[start.slot], $0.children[end.slot]) } + + // Descend a lever lower. + lower.removeSuffix(from: start.remaining, in: metric, into: &builder) + upper.removePrefix(upTo: end.remaining, in: metric, into: &builder) + return + } + // Extract items on boundaries. + var (lower, upper) = readLeaf { ($0.children[start.slot], $0.children[end.slot]) } + + let i1 = metric.index(at: start.remaining, in: lower.value) + let i2 = metric.index(at: end.remaining, in: upper.value) + _ = lower.split(at: i1) + builder.append(lower) + builder.prependSuffix(upper.split(at: i2)) + } + + __consuming func removeSuffix( + from position: Int, + in metric: some _RopeMetric, + into builder: inout _Rope.Builder + ) { + + var node = self + var position = position + while true { + guard position > 0 else { return } + guard position < metric.size(of: node.summary) else { + builder.append(node) + return + } + + guard !node.isLeaf else { break } + + let r = node.readInner { $0.findSlot(at: position, in: metric) } + position = r.remaining + node._innerRemoveSuffix(descending: r.slot, into: &builder) + } + let r = node.readLeaf { $0.findSlot(at: position, in: metric, preferEnd: false) } + var item = node._leafRemoveSuffix(returning: r.slot, into: &builder) + let i = metric.index(at: r.remaining, in: item.value) + _ = item.split(at: i) + builder.append(item) + } + + __consuming func removePrefix( + upTo position: Int, + in metric: some _RopeMetric, + into builder: inout _Rope.Builder + ) { + var node = self + var position = position + while true { + guard position > 0 else { + builder.prependSuffix(node) + return + } + guard position < metric.size(of: node.summary) else { return } + + guard !node.isLeaf else { break } + + let r = node.readInner { $0.findSlot(at: position, in: metric) } + position = r.remaining + node._innerRemovePrefix(descending: r.slot, into: &builder) + } + let r = node.readLeaf { $0.findSlot(at: position, in: metric) } + var item = node._leafRemovePrefix(returning: r.slot, into: &builder) + let i = metric.index(at: r.remaining, in: item.value) + builder.prependSuffix(item.split(at: i)) + } + + mutating func _innerRemoveSuffix( + descending slot: Int, + into builder: inout _Rope.Builder + ) { + assert(!self.isLeaf) + assert(slot >= 0 && slot <= childCount) + + if slot == 0 { + self = readInner { $0.children[0] } + return + } + if slot == 1 { + let (remaining, new) = readInner { + let c = $0.children + return (c[0], c[1]) + } + builder.append(remaining) + self = new + return + } + + ensureUnique() + if slot < childCount - 1 { + let delta = updateInner { $0._removeSuffix($0.childCount - slot - 1) } + self.summary.subtract(delta) + } + var n = _removeNode(at: slot) + swap(&self, &n) + assert(n.childCount > 1) + builder.append(n) + } + + __consuming func _leafRemoveSuffix( + returning slot: Int, + into builder: inout _Rope.Builder + ) -> Item { + assert(self.isLeaf) + assert(slot >= 0 && slot < childCount) + + if slot == 0 { + return readLeaf { $0.children[0] } + } + if slot == 1 { + let (remaining, new) = readLeaf { + let c = $0.children + return (c[0], c[1]) + } + builder.append(remaining) + return new + } + + var n = self + n.ensureUnique() + if slot < n.childCount - 1 { + let delta = n.updateLeaf { $0._removeSuffix($0.childCount - slot - 1) } + n.summary.subtract(delta) + } + let item = n._removeItem(at: slot).removed + builder.append(n) + return item + } + + mutating func _innerRemovePrefix( + descending slot: Int, + into builder: inout _Rope.Builder + ) { + assert(!self.isLeaf) + assert(slot >= 0 && slot < childCount) + + if slot == childCount - 1 { + self = readInner { $0.children[$0.childCount - 1] } + return + } + if slot == childCount - 2 { + let (new, remaining) = readInner { + let c = $0.children + return (c[$0.childCount - 2], c[$0.childCount - 1]) + } + builder.prependSuffix(remaining) + self = new + return + } + + ensureUnique() + var (delta, n) = updateInner { + let n = $0.children[slot] + let delta = $0._removePrefix(slot + 1) + return (delta, n) + } + self.summary.subtract(delta) + assert(self.childCount > 1) + swap(&self, &n) + builder.prependSuffix(n) + } + + __consuming func _leafRemovePrefix( + returning slot: Int, + into builder: inout _Rope.Builder + ) -> Item { + assert(self.isLeaf) + assert(slot >= 0 && slot <= childCount) + + if slot == childCount - 1 { + return readLeaf { $0.children[$0.childCount - 1] } + } + if slot == childCount - 2 { + let (new, remaining) = readLeaf { + let c = $0.children + return (c[$0.childCount - 2], c[$0.childCount - 1]) + } + builder.prependSuffix(remaining) + return new + } + + var n = self + n.ensureUnique() + let (delta, item) = n.updateLeaf { + let n = $0.children[slot] + let delta = $0._removePrefix(slot + 1) + return (delta, n) + } + n.summary.subtract(delta) + assert(n.childCount > 1) + builder.prependSuffix(n) + return item + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Split.swift b/Sources/RopeModule/Rope/Operations/_Rope+Split.swift new file mode 100644 index 00000000..b7b21ee9 --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+Split.swift @@ -0,0 +1,136 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + mutating func builder( + splittingAt position: Int, + in metric: some _RopeMetric + ) -> Builder { + var builder = Builder() + + var position = position + var node = root + _root = nil + while !node.isLeaf { + let r = node.readInner { $0.findSlot(at: position, in: metric) } + position = r.remaining + node._innerSplit(at: r.slot, into: &builder) + } + + let r = node.readLeaf { $0.findSlot(at: position, in: metric) } + var item = node._leafSplit(at: r.slot, into: &builder) + let index = metric.index(at: r.remaining, in: item.value) + let suffix = item.split(at: index) + builder.prependSuffix(suffix) + builder.append(item.value) + return builder + } + + mutating func split(at index: Index) -> (builder: Builder, item: Element) { + precondition(index < endIndex) + var builder = Builder() + + var node = root + _root = nil + while !node.isLeaf { + let slot = index[height: node.height] + precondition(slot < node.childCount, "Index out of bounds") + node._innerSplit(at: slot, into: &builder) + } + + let slot = index[height: node.height] + precondition(slot < node.childCount, "Index out of bounds") + let item = node._leafSplit(at: slot, into: &builder) + return (builder, item.value) + } + + mutating func split(at ropeIndex: Index, _ itemIndex: Element.Index) -> Builder { + var (builder, item) = self.split(at: ropeIndex) + let suffix = item.split(at: itemIndex) + if !suffix.isEmpty { + builder.prependSuffix(_Rope.Item(suffix)) + } + if !item.isEmpty { + builder.append(item) + } + return builder + } +} + +extension _Rope.Node { + mutating func _innerSplit( + at slot: Int, + into builder: inout _Rope.Builder + ) { + assert(!self.isLeaf) + assert(slot >= 0 && slot < childCount) + ensureUnique() + + var slot = slot + if slot == childCount - 2 { + builder.prependSuffix(_removeNode(at: childCount - 1)) + } + if slot == 1 { + builder.append(_removeNode(at: 0)) + slot -= 1 + } + + var n = _removeNode(at: slot) + swap(&self, &n) + + guard n.childCount > 0 else { return } + if slot == 0 { + builder.prependSuffix(n) + return + } + if slot == n.childCount { + builder.append(n) + return + } + let suffix = n.split(keeping: slot) + builder.append(n) + builder.prependSuffix(suffix) + } + + __consuming func _leafSplit( + at slot: Int, + into builder: inout _Rope.Builder + ) -> Item { + var n = self + n.ensureUnique() + + assert(n.isLeaf) + assert(slot >= 0 && slot < n.childCount) + + var slot = slot + if slot == n.childCount - 2 { + builder.prependSuffix(n._removeItem(at: childCount - 1).removed) + } + if slot == 1 { + builder.append(n._removeItem(at: 0).removed.value) + slot -= 1 + } + + let item = n._removeItem(at: slot).removed + + guard n.childCount > 0 else { return item } + if slot == 0 { + builder.prependSuffix(n) + } else if slot == n.childCount { + builder.append(n) + } else { + let suffix = n.split(keeping: slot) + builder.append(n) + builder.prependSuffix(suffix) + } + return item + } +} diff --git a/Sources/RopeModule/Utilities/Optional Utilities.swift b/Sources/RopeModule/Utilities/Optional Utilities.swift new file mode 100644 index 00000000..fc64884f --- /dev/null +++ b/Sources/RopeModule/Utilities/Optional Utilities.swift @@ -0,0 +1,18 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension Optional { + mutating func _take() -> Self { + let r = self + self = nil + return r + } +} diff --git a/Sources/RopeModule/Utilities/String Utilities.swift b/Sources/RopeModule/Utilities/String Utilities.swift new file mode 100644 index 00000000..0b1fe136 --- /dev/null +++ b/Sources/RopeModule/Utilities/String Utilities.swift @@ -0,0 +1,122 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension StringProtocol { + @inline(__always) + var _indexOfLastCharacter: Index { + guard !isEmpty else { return endIndex } + return index(before: endIndex) + } + + @inline(__always) + func _index(at offset: Int) -> Index { + self.index(self.startIndex, offsetBy: offset) + } + + @inline(__always) + func _utf8Index(at offset: Int) -> Index { + self.utf8.index(startIndex, offsetBy: offset) + } + + @inline(__always) + func _utf8ClampedIndex(at offset: Int) -> Index { + self.utf8.index(startIndex, offsetBy: offset, limitedBy: endIndex) ?? endIndex + } + + @inline(__always) + func _utf8Offset(of index: Index) -> Int { + self.utf8.distance(from: startIndex, to: index) + } + + @inline(__always) + var _lastCharacter: (index: Index, utf8Length: Int) { + let i = _indexOfLastCharacter + let length = utf8.distance(from: i, to: endIndex) + return (i, length) + } +} + +extension String { + internal func _lpad(to width: Int, with pad: Character = " ") -> String { + let c = self.count + if c >= width { return self } + return String(repeating: pad, count: width - c) + self + } + + internal func _rpad(to width: Int, with pad: Character = " ") -> String { + let c = self.count + if c >= width { return self } + return self + String(repeating: pad, count: width - c) + } +} + +extension String { + @discardableResult + mutating func _appendQuotedProtectingLeft( + _ str: String, + with state: inout _CharacterRecognizer, + maxLength: Int = Int.max + ) -> String.Index { + guard !str.isEmpty else { return str.endIndex } + let startUTF8 = self.utf8.count + var i = str.unicodeScalars.startIndex + var needsBreak = true + while i < str.endIndex { + let us = str.unicodeScalars[i] + var scalar = us.escaped(asASCII: false) + if needsBreak { + var t = state + if let r = t.firstBreak(in: scalar[...]), r.lowerBound == scalar.startIndex { + } else { + scalar = us.escaped(asASCII: true) + } + } + needsBreak = (scalar != String(us)) + self.append(scalar) + _ = state.consume(scalar[...]) + + str.unicodeScalars.formIndex(after: &i) + + let start = self._utf8Index(at: startUTF8) + if self.distance(from: start, to: self.endIndex) >= maxLength { + break + } + } + return i + } + + mutating func _appendProtectingRight(_ str: String, with state: inout _CharacterRecognizer) { + var suffix = str + while !self.isEmpty { + guard let first = suffix.unicodeScalars.first else { return } + self.unicodeScalars.append(first) + let i = self.index(before: self.endIndex) + if self.unicodeScalars.distance(from: i, to: self.endIndex) == 1 { + self.unicodeScalars.append(contentsOf: suffix.unicodeScalars.dropFirst()) + break + } + self.unicodeScalars.removeLast() + let last = self.unicodeScalars.removeLast() + suffix.insert(contentsOf: last.escaped(asASCII: true), at: suffix.startIndex) + } + } + + /// A representation of the string that is suitable for debugging. + /// This implementation differs from `String.debugDescription` by properly quoting + /// continuation characters after the opening quotation mark and similar meta-characters. + var _properDebugDescription: String { + var result = "\"" + var state = _CharacterRecognizer(consuming: result) + result._appendQuotedProtectingLeft(self, with: &state) + result._appendProtectingRight("\"", with: &state) + return result + } +} diff --git a/Sources/RopeModule/Utilities/String.Index+ABI.swift b/Sources/RopeModule/Utilities/String.Index+ABI.swift new file mode 100644 index 00000000..839e21a0 --- /dev/null +++ b/Sources/RopeModule/Utilities/String.Index+ABI.swift @@ -0,0 +1,101 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +// Bits of String.Index that are ABI but aren't exposed by public API. +extension String.Index { + @inline(__always) + var _rawBits: UInt64 { + unsafeBitCast(self, to: UInt64.self) + } + + @inline(__always) + var _encodedOffset: Int { + Int(truncatingIfNeeded: _rawBits &>> 16) + } + + @inline(__always) + var _transcodedOffset: Int { + Int(truncatingIfNeeded: (_rawBits &>> 14) & 0x3) + } + + @inline(__always) + static var __scalarAlignmentBit: UInt64 { 0x1 } + + @inline(__always) + static var __characterAlignmentBit: UInt64 { 0x2 } + + @inline(__always) + static var __utf8Bit: UInt64 { 0x4 } + + @inline(__always) + static var __utf16Bit: UInt64 { 0x8 } + + + @inline(__always) + var _encodingBits: UInt64 { + _rawBits & (Self.__utf8Bit | Self.__utf16Bit) + } + + @inline(__always) + var _canBeUTF8: Bool { + // The only way an index cannot be UTF-8 is it has only the UTF-16 flag set. + _encodingBits != Self.__utf16Bit + } + + var _isScalarAligned: Bool { + 0 != _rawBits & Self.__scalarAlignmentBit + } + + var _isCharacterAligned: Bool { + 0 != _rawBits & Self.__characterAlignmentBit + } + + var _characterAligned: String.Index { + let r = _rawBits | Self.__characterAlignmentBit | Self.__scalarAlignmentBit + return unsafeBitCast(r, to: String.Index.self) + } +} + +extension String.Index { + @inline(__always) + var _utf8Offset: Int { + assert(_canBeUTF8) + return _encodedOffset + } + + @inline(__always) + var _utf16Delta: Int { + assert(_canBeUTF8) + let r = _transcodedOffset + assert(r <= 1) + return r + } + + @inline(__always) + init(_rawBits: UInt64) { + self = unsafeBitCast(_rawBits, to: String.Index.self) + } + + @inline(__always) + init(_utf8Offset: Int) { + self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | Self.__utf8Bit) + } + + @inline(__always) + var _chunkData: UInt16 { + UInt16(_rawBits &>> 14) + } + + @inline(__always) + init(_chunkData: UInt16) { + self.init(_rawBits: UInt64(_chunkData) &<< 14) + } +} diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift new file mode 100644 index 00000000..da1b9d1e --- /dev/null +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -0,0 +1,287 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// CR and LF are common special cases in grapheme breaking logic +private var _CR: UInt8 { return 0x0d } +private var _LF: UInt8 { return 0x0a } + +internal func _hasGraphemeBreakBetween( + _ lhs: Unicode.Scalar, _ rhs: Unicode.Scalar +) -> Bool { + + // CR-LF is a special case: no break between these + if lhs == Unicode.Scalar(_CR) && rhs == Unicode.Scalar(_LF) { + return false + } + + // Whether the given scalar, when it appears paired with another scalar + // satisfying this property, has a grapheme break between it and the other + // scalar. + func hasBreakWhenPaired(_ x: Unicode.Scalar) -> Bool { + // TODO: This doesn't generate optimal code, tune/re-write at a lower + // level. + // + // NOTE: Order of case ranges affects codegen, and thus performance. All + // things being equal, keep existing order below. + switch x.value { + // Unified CJK Han ideographs, common and some supplemental, amongst + // others: + // U+3400 ~ U+A4CF + case 0x3400...0xa4cf: return true + + // Repeat sub-300 check, this is beneficial for common cases of Latin + // characters embedded within non-Latin script (e.g. newlines, spaces, + // proper nouns and/or jargon, punctuation). + // + // NOTE: CR-LF special case has already been checked. + case 0x0000...0x02ff: return true + + // Non-combining kana: + // U+3041 ~ U+3096 + // U+30A1 ~ U+30FC + case 0x3041...0x3096: return true + case 0x30a1...0x30fc: return true + + // Non-combining modern (and some archaic) Cyrillic: + // U+0400 ~ U+0482 (first half of Cyrillic block) + case 0x0400...0x0482: return true + + // Modern Arabic, excluding extenders and prependers: + // U+061D ~ U+064A + case 0x061d...0x064a: return true + + // Precomposed Hangul syllables: + // U+AC00 ~ U+D7AF + case 0xac00...0xd7af: return true + + // Common general use punctuation, excluding extenders: + // U+2010 ~ U+2029 + case 0x2010...0x2029: return true + + // CJK punctuation characters, excluding extenders: + // U+3000 ~ U+3029 + case 0x3000...0x3029: return true + + // Full-width forms: + // U+FF01 ~ U+FF9D + case 0xFF01...0xFF9D: return true + + default: return false + } + } + return hasBreakWhenPaired(lhs) && hasBreakWhenPaired(rhs) +} + +// FIXME: This has terrible performance. +// FIXME: Replace with Unicode._CharacterRecognizer once it gets into a build. +struct _CharacterRecognizer { + private var string: String + + init() { + string = "" + } + + init(first: Unicode.Scalar) { + string = String(first) + } + + static func quickBreak( + between scalar1: Unicode.Scalar, + and scalar2: Unicode.Scalar + ) -> Bool? { + if scalar1 == Unicode.Scalar(_CR) && scalar2 == Unicode.Scalar(_LF) { return false } + if _hasGraphemeBreakBetween(scalar1, scalar2) { return true } + return nil + } + + mutating func hasBreak( + before next: Unicode.Scalar + ) -> Bool { + let next = String(next) + guard !string.isEmpty else { + string = next + return true + } + string.append(next) + let i = string.index(after: string.startIndex) + if i == string.endIndex { return false } + string = next + return true + } +} + +extension _CharacterRecognizer: Equatable { + static func ==(left: Self, right: Self) -> Bool { + left.string.utf8.elementsEqual(right.string.utf8) + } +} + +extension _CharacterRecognizer { + mutating func firstBreak( + in str: Substring + ) -> Range? { + guard !str.isEmpty else { return nil } + let c = self.string.utf8.count + if c == 0 { + // Report a break before the first scalar at start + let lower = str.startIndex + let upper = str.unicodeScalars.index(after: lower) + self.string = String(str.unicodeScalars[lower]) + return lower ..< upper + } + + self.string += str + let i = self.string.index(after: self.string.startIndex) + if i == self.string.endIndex { return nil } + + // Keep first scalar following break; discard everything else. + let offset = self.string._utf8Offset(of: i) + precondition(offset >= c) + self.string = String(self.string.unicodeScalars[i]) + let scalarWidth = self.string.utf8.count + + let lower = str._utf8Index(at: offset - c) + let upper = str._utf8Index(at: offset - c + scalarWidth) + return lower ..< upper + } +} +extension _CharacterRecognizer { + init(partialCharacter: Substring.UnicodeScalarView) { + self.init() + var it = partialCharacter.makeIterator() + guard let first = it.next() else { return } + _ = hasBreak(before: first) + while let next = it.next() { + let b = hasBreak(before: next) + assert(!b) + } + } + + init(partialCharacter: Substring) { + self.init(partialCharacter: partialCharacter.unicodeScalars) + } + + mutating func consumePartialCharacter(_ s: Substring) { + for scalar in s.unicodeScalars { + let b = hasBreak(before: scalar) + assert(!b) + } + } + + mutating func consumePartialCharacter(_ s: Substring.UnicodeScalarView) { + for scalar in s { + let b = hasBreak(before: scalar) + assert(!b) + } + } + + mutating func consumeUntilFirstBreak( + in s: Substring.UnicodeScalarView, + from i: inout String.Index + ) -> String.Index? { + while i < s.endIndex { + defer { s.formIndex(after: &i) } + if hasBreak(before: s[i]) { + return i + } + } + return nil + } + + init(consuming str: some StringProtocol) { + self.init() + _ = self.consume(str) + } + + mutating func consume( + _ s: some StringProtocol + ) -> (characters: Int, firstBreak: String.Index, lastBreak: String.Index)? { + consume(Substring(s)) + } + + mutating func consume( + _ s: Substring + ) -> (characters: Int, firstBreak: String.Index, lastBreak: String.Index)? { + consume(s.unicodeScalars) + } + + mutating func consume( + _ s: Substring.UnicodeScalarView + ) -> (characters: Int, firstBreak: String.Index, lastBreak: String.Index)? { + var i = s.startIndex + guard let first = consumeUntilFirstBreak(in: s, from: &i) else { + return nil + } + var characters = 1 + var last = first + while let next = consumeUntilFirstBreak(in: s, from: &i) { + characters += 1 + last = next + } + return (characters, first, last) + } + + mutating func consume( + _ chunk: _BString.Chunk, upTo index: String.Index + ) -> (firstBreak: String.Index, prevBreak: String.Index)? { + let index = chunk.string.unicodeScalars._index(roundingDown: index) + let first = chunk.firstBreak + guard index > first else { + consumePartialCharacter(chunk.string[.. (characters: Int, prefixCount: Int, suffixCount: Int) { + let c = s.utf8.count + guard let (chars, first, last) = consume(s[...]) else { + return (0, c, c) + } + let prefix = s._utf8Offset(of: first) + let suffix = c - s._utf8Offset(of: last) + return (chars, prefix, suffix) + } +} + +extension String { + // FIXME: Remove once the stdlib entry point gets into a build. + func _index(roundingDown i: Index) -> Index { + guard i < endIndex else { return endIndex } + guard !i._isCharacterAligned else { return i } + return index(before: index(after: i)) + } +} + +extension Substring { + // FIXME: Remove once the stdlib entry point gets into a build. + func _index(roundingDown i: Index) -> Index { + index(i, offsetBy: 0) + } + + func _nextBreak(onOrAfter i: Index) -> Index { + let nearestDown = _index(roundingDown: i) + guard nearestDown != i else { return nearestDown } + return index(after: nearestDown) + } +} + +extension String.UnicodeScalarView { + // FIXME: Remove once the stdlib entry point gets into a build. + func _index(roundingDown i: Index) -> Index { + index(i, offsetBy: 0) + } +} diff --git a/Tests/RopeModuleTests/SampleStrings.swift b/Tests/RopeModuleTests/SampleStrings.swift new file mode 100644 index 00000000..086c3261 --- /dev/null +++ b/Tests/RopeModuleTests/SampleStrings.swift @@ -0,0 +1,153 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +let sampleString = + #""" + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + 一种强大但极易学习的编程语言。 + Swift 是一种强大直观的编程语言,适用于 iOS、iPadOS、macOS、Apple tvOS 和 watchOS。\# + 编写 Swift 代码的过程充满了乐趣和互动。Swift 语法简洁,但表现力强,更包含了开发者喜爱的现代功能。\# + Swift 代码从设计上保证安全,并能开发出运行快如闪电的软件。 + + パワフルなプログラミング言語でありながら、簡単に習得することができます。 + Swiftは、iOS、iPadOS、macOS、tvOS、watchOS向けのパワフルで直感的なプログラミング言語です。\# + Swiftのコーディングはインタラクティブで楽しく、構文はシンプルでいて表現力に富んでいます。\# + さらに、デベロッパが求める最新の機能も備えています。安全性を重視しつつ非常に軽快に動作す\# + るソフトウェアを作り出すことができます。それがSwiftです。 + + 손쉽게 학습할 수 있는 강력한 프로그래밍 언어. + Swift는 iOS, iPadOS, macOS, tvOS 및 watchOS를 위한 강력하고 직관적인 프로그래밍 언어입니다. \# + Swift 코드 작성은 대화식으로 재미있고, 구문은 간결하면서도 표현력이 풍부하며, Swift에는 개발자들이 \# + 좋아하는 첨단 기능이 포함되어 있습니다. Swift 코드는 안전하게 설계되었으며 빛의 속도로 빠르게 실행되는 \# + 소프트웨어를 제작할 수 있습니다. + + 🪙 A 🥞 short 🍰 piece 🫘 of 🌰 text 👨‍👨‍👧‍👧 with 👨‍👩‍👦 some 🚶🏽 emoji 🇺🇸🇨🇦 characters 🧈 + some🔩times 🛺 placed 🎣 in 🥌 the 🆘 mid🔀dle 🇦🇶or🏁 around 🏳️‍🌈 a 🍇 w🍑o🥒r🥨d + + ⌘⏎ ⌃⇧⌥⌘W + ¯\_(ツ)_/¯ + ಠ_ಠ + + 🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦\# + 🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦\# + 🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦 + + Unicode is such fun! + U̷n̷i̷c̷o̴d̴e̷ ̶i̸s̷ ̸s̵u̵c̸h̷ ̸f̵u̷n̴!̵ + U̴̡̲͋̾n̵̻̳͌ì̶̠̕c̴̭̈͘ǫ̷̯͋̊d̸͖̩̈̈́ḛ̴́ ̴̟͎͐̈i̴̦̓s̴̜̱͘ ̶̲̮̚s̶̙̞͘u̵͕̯̎̽c̵̛͕̜̓h̶̘̍̽ ̸̜̞̿f̵̤̽ṷ̴͇̎͘ń̷͓̒!̷͍̾̚ + U̷̢̢̧̨̼̬̰̪͓̞̠͔̗̼̙͕͕̭̻̗̮̮̥̣͉̫͉̬̲̺͍̺͊̂ͅn̶̨̢̨̯͓̹̝̲̣̖̞̼̺̬̤̝̊̌́̑̋̋͜͝ͅḭ̸̦̺̺͉̳͎́͑c̵̛̘̥̮̙̥̟̘̝͙̤̮͉͔̭̺̺̅̀̽̒̽̏̊̆͒͌̂͌̌̓̈́̐̔̿̂͑͠͝͝ͅö̶̱̠̱̤̙͚͖̳̜̰̹̖̣̻͎͉̞̫̬̯͕̝͔̝̟̘͔̙̪̭̲́̆̂͑̌͂̉̀̓́̏̎̋͗͛͆̌̽͌̄̎̚͝͝͝͝ͅd̶̨̨̡̡͙̟͉̱̗̝͙͍̮͍̘̮͔͑e̶̢͕̦̜͔̘̘̝͈̪̖̺̥̺̹͉͎͈̫̯̯̻͑͑̿̽͂̀̽͋́̎̈́̈̿͆̿̒̈́̽̔̇͐͛̀̓͆̏̾̀̌̈́̆̽̕ͅ ̷̢̳̫̣̼̙̯̤̬̥̱͓̹͇̽̄̄̋̿̐̇̌̒̾̑̆̈́̏͐̒̈̋̎͐̿̽̆̉͋͊̀̍͘̕̕̕͝͠͠͝ͅͅì̸̢̧̨̨̮͇̤͍̭̜̗̪̪͖̭͇͔̜̗͈̫̩͔̗͔̜̖̲̱͍̗̱̩͍̘̜̙̩͔̏̋̓̊́́̋̐̌͊͘̕͠s̶̨̢̧̥̲̖̝̩͖̱͋́͑͐̇̐̔̀̉͒͒́̐̉̔͘͠͠ ̵̧̛͕̦̭̣̝̩͕̠͎̮͓͉̟̠̘͎͋͗͆̋̌̓̃̏̊̔̾̒̿s̸̟͚̪̘̰̮͉̖̝̅̓͛̏̆ư̵͍̙̠͍̜͖͔̮̠̦̤̣̯̘̲͍͂͌̌̅̍͌̈́̆̋̎͋̓̍͆̃̑͌͘̕͜ͅç̸̟̗͉̟̤̙̹͓̖͇̳̈́̍̏͐̓̓̈̆̉̈͆̍ͅh̵̛̛̹̪͇͓̤̺̟͙̣̰͓̺̩̤̘̫͔̺͙͌́̑̓͗̏͆́͊̈́̋̿͒̐̀́̌͜͜͝ ̴̗͓͚͖̣̥͛́̓͐͂͛̐͑̈́͗̂̈͠f̶̡̩̟̤̭̩̱̥͈̼̥̳͕̣͓̱̰͎̖̦͎̦̻̫͉̝̗̝͚̎͌͑̾̿̊̉͆̉̏̅̔̓̈́̀͐̚͘ͅư̷̦̮͖͙̺̱̼̜̺̤͎̜͐͐̊̊̈͋̔̓̍͊̇̊̈́̈͑̐̎̿̑̋͋̀̅̓͛̚͜n̷̡̨͉̠̖̙͎̳̠̦̼̻̲̳̿̀̓̍͋̎͆̓̇̾̅͊̐͘͘̕!̷̡̨̧̢̡̡̼̹̭̝̝̭̫̫̥̰̤̪̦̤̼̖̖̳̰̲͙͕̖̬̳̪͖̹̮͐͐͊̈́̐͑͛̾̈͊̊͋͑̉͒̈̿̈̃̑͋͐́͊̀͝͠͝͠ + Ų̷̧̧̧̧̡̢̨̨̢̢̢̧̡̨̨̧̢̡̡̢̨̨̮̜͈̳̮͔̺͚̹͉͍̫̪͖͙͙̳͖͖̦̮̜̫̗̣̙̪͇̩̻̬̖̝̻̰͙̖̙̭̤͎̠͇̹̦̤̟̦͎̹̝̗̫͔̳̣̦͍̹͈̺̮͈͈̬̭̘͕̟͉̮̟͖̦̥͇̠̙̳̲̝̦͖̻̪̺̬̫͈͈̘͍͚͖̝̥̙͖̪͔̫̣̘͙͓̱̠̲̯̦͓͖͚͎͉͖̘̺͕͇̱̺̗̙̮̮̹̯̤̮̺͓̘̫͕̞̮͕̠̗͍̦̣̮͙͉͈̭̜̭̘̼̼̖̮̘̝͈̌̑͋͂̈́̐̄̂̆̊̈̅͆͋̔͗̍͒̆̐̒̽͑̋́͛͗̓̃̽͋̒͑̈́̕̕̚̕̕͜͜͝͠͝͠͝ͅͅņ̴̡̢̡̢̢̨̛̛̛̛̛̛̛̻̬̲̰̗̭͕̯͇̩̦̮̫̭̰̪͉̹̭͇̣̦͕̹̗̭̬͓͕͍̯͇͕̩̱̲͍̟̙͓̣̖̱͍̟͚͔̞̪͕̣̺̻̭̖̤̜͈̰̻̘̹̝̝̮̗͔̯̻̻͍͕̬͇͓̲̗̟̭̰̬̳͈̼̤̙̱̻̜͍̪̣̈̉̉͑̇̇͐̆̆̀̋̄̂̿͒͐͒͛̒̍͆̿͐͊̂̿̐̇̋̄̈̂̓̅̇̈́̾̒̔̍̈́͐̋͊̑͐͆̈́̿́̽͛́̊̏̓̾̇̈́̀̃͐̃̈́́͒̏̀͑̑̅̈́̇͂̓̐̒́̾̈́͗̋̅̀́͋̍͑͒̌̔̈́̆̂̉͌̈́̑̾̑̽̓̓̏̄͋̽̒̓͌̊̂̀͑̂͑̌͋̓͐̈̃̾̏̃̏͑̋̒̈̀̔͐̓̋̉̐̐͋͆̂̈́̒͊̏̓̔͌̈̾͗͑͂̾͆͑̂̍̂͗͆̄̊̐̏̈́͂̌͐̃̐͌̊̀͗̐͑̔͋͒̊̋̒̐̄͐̏̓͌̃̌͋̔̎̈̆̍̃̿́̇̉̀́̊̅̌̏̆̆͛̔͋̈̽̂͂̇̓́͛͗̔̍̃̈̽͑͐̿̽̉̓̎̔͗̊͂̽͘̕̚̕͘̕̕͘̚͘̚̕̚̚̚͘̚͜͜͝͝͠͝͝͠͝͝͝͝͝͝͝͝͝͝͠͝ͅͅͅi̴̧̡̢̡̧̢̢̢̧̡̧̢̡̹̤̗̭̭̭̪̳̮͉̦̪͉͈̦̗̣̼̻̜̰̳̯͕̩̘̙̯̼͉̖͕̰͓͚͙̠̫̞̰̰̪͖̹̬̥̣̞̯̳̘̙͖̪̗̼̹̝̣͕̯̺̱͉̻̖͓͙̘̗̖̠̫̥̻̱̖͇̬͇̹͕͍̗̻̝̻͕̫̱̻͈̫͕̜̼͎̮̘̫̮̭͉̜͔͈̻͕͍̠̞͔̪̳͕̰͈͖͇͍͇͎͕̙̟͔͔͇̭̥̠͇̖͎͙̖̫͚͇͕̮̳̯̟̺̺̪̪̙̣̥̰̜̺̥̭̦̤̲͓̮̦̹͙̼͓̼̮̙̮̠͎͍͖̇͐͐͐̿́͊̃̀͋̔͑̓͂͌͗̋̇̎͛͊̋̔̓̇̚͜ͅč̷̨̡̡̨̫̗̠̥̫̩͕͉͉͇̮͉̲͎̭̝̬͚̜̮̼̰̭̞̘̠̘̰̹͈̯̫̟͓͙̻̤̰͈̌͂̓͐̑̌̏̊͂͂̉͌̐̇̎͋̍̉̑̃̇̃̎̓͋͛̑͊̾͊̔̍̄͂͘͘͝͝͠ǫ̴̡̧̨̧̧̢̢̧̧̢̨̢̨̡̧̨̡̡̨̨̨̡̡̨̡̨̨̨̧̧̡̛̛̤͚̖̫̰̣̣͍̱̜͈̻̙̲̙͚͚̖͕̠̼̲͚̯͚̳̻͇̘̲̦͕̦̜̣̙̣̣̜̰̝͕̤̝̫̺̳͙̮̬̪̹̲͍̣̹̙̠̫̘̥̦̘̰̞̙̟̟̤͓̙͖̣͓͔͓̩̩͈̗̤͇̠̞̩̮̪̥̪̱͚͍̝͕͎̞͔̩̖̲͔͈̩̻̩͕̫͓̳̙͓̞̟͙͉͉̬̮̗͓̱̲̮̯͇͕̰̖͚̦͈̞̺̠̳͕̭̭̳͓̻̯̞̳͔͍̟̬̳̩͚͎̲̹͍͇͈̙̳̞̖̗̯͖̱͖̯̤̠̲͍̩͈̭̙͈̲̱̲̼̩̘̘̜͔̲̱̯͔̈́̈́̋̿̋̿͋͋͌̏̽̇͗͊͑̔͆͌̿̋͌̋͗̉̊̿̐̄̈́̈́̈̄̆̅̃́̄̅̍́̽͒̈́̽̄̌̇̓̈͂͆̊͆̿́͗͛̅̋́͆͑͛̆̔̍̀̍̃̎͒̀͋͛̽́̏̄̓̌͘͘͘̚̕̕͘͜͜͜͜͜͜͠͠͠͝͠͝͝ͅͅͅd̷̨̧̧̢̢̧̛̛̛̛̛̛̛͖̭̘̺͕̜̬̤̭̬̠̫̤͍͚̪̬̣͉̳̮̱͖̻̟͓̫̹͚̝̗̳̰̺͍͎͉̟̱̜̫͇̫̯̼̠̞̝̤͖̖̻͍͖̰̻͕̙͙͚͈̱̝͉͙̘̰͚̩̗̟͕̞̞̼̣͖̜̳̥̼͉̘͈̘̩͕̦̺̝̟̼͍̥̲̤̪̗̀͌̊̃̆̑̓̓̌͌̏̎͋̀͌͐̈́̀̂̍̒̅̓̏̓̈́̀̀͊̒̎̓́̒̔̉̀̍̿̒͛̍̍̅̇͑̆͒̓̌̑̏̏̈͊̈́́͌̀̃̆́̔̃̀͛̾̅́̿̀́̿̒͆́̍̂̀̿̆͑̊̉͆́̒̑̅̽̂̄͂̏̿̍̽̃͂̈́̀͌̒͗̅̉̎̓̐̀̌̿̓̈̓͛̽̄̉̑̄̊͂̀̽̔̇̍̀͂̇̈͊͐͗̽͐͊͐̑͘͘͘͘̕̚̕̕̚̚̕͘͘͜͜͜͜͜͝͝͝͝͠͠͝͠͝͠͠͝͝͠ͅͅͅę̴̨̡̨̡̢̛͈̳̞͈͇͕͙̪̩̼̩̗̲̳̹̯̖̙̱͔̺̪͇̜̼̍͌̆̅̽͛̏̑͊͒͊͌́̇̄͊́̏́̄̈͆̿͌̌̀̈̃͊̈̀̽͒͑̊́̍̑̃̒̐́̓̈̃̀͛̽̔̎̀̄̑͌̾͒̊̀̓̆̀̕̕͘͜͜͠͝͠͝ͅͅ ̴̨̡̢̢̢̢̛̛̛̛̛̛̛̛̼̻̬̪͎̖̭̯̤̥̭͚̖̖͚̳͍͎̻̰̯̗̭͔͎͇̖̮̻̯̰̯̦̗͔̺͔̩͈̫̣̪͕̜͇͓͓̅͐́̃̿̀̍͂̽̂͒̇̉̿̑̀̈̒̇͋͗̓͑̒̿͒̃̏̏̔͐̓͐̽͛̆̈͗̿͆́͌́̀̇̈́̓̄̾̇̈́̀͑̽̔͒̌͑̓́̀̈́̀͊̓̏̾̿̓͒̅͋̓̂͆͊̎̾̆̀̾̏̆̈̿̆͗̀̿͊̒̌̓́͆̈́͂̍͆͗͌̇̇͋̅̍̈́̊̽̈́̑́̅͐́̌̉͆͊͑̓̿͆̊͒̑̑̉̑̔̀̀́̐̓̽͂͌̾͑̌͑̓͒̀͗̈́̑̀̋͂͆̓̍̆́͛̈́̈́̀́̀͋͂͛̎̑̌͊̅͑̔̓͛͂̓̇̾́͌̓́̆͋̓̓͑̔̈́̎̍͊̃̋̃͌͛̓́̔͆̈͐͒̂̅̂̓͂̋̅̽̏̉̎̊̈̿̾̊̃͆̆͊͂̎͋̌͊͌̍̄̔͒̄͗̈́͒̇̕̕̕̕̕̚͘̚̕͘̕̚͘͘͘̕͘̚͘̕̚͝͝͝͠͝͠͝͝͝͝͝͠͠͝͝͝͠͠͝͝ͅͅį̴̛͕͍̠̩͎͇̳̪̱̖̝͙͉̩̩̯̜͕͓͕̀͂͛̃͑̉͐̏͑́̒̃̑̐̾̈͐͝ͅs̶̨̢̨̡̧̡̡̧̨̪̱̪̙̤̥̺̰͚̦̞̫̟̭̟̠̗̺̲̺̹͙͇͈̭̱̪͔̦̦̻̭͙̱̱̬̙̺̤̤̙͈̭͖̯͇̞͙͈̟͓̖̠͚̳̤̺̙̤͔̯͍͔͖̱͈͍̞͚̗̭̮̣͕̻̝̮̯͐̑̃̌̐̈́̌̈̔́͋̂͊̿̈́̉̄̆̎̃̏͑̈̑̔̋͐̂̽̈́̔͗̒̌́̓̉̕̕͜͜͠ͅͅ ̴̢̡̧̧̡̢̡̨̢̢̧̡̧̨̡̡̨̧̧̡̨̛̛̛̱͚̭̯̯̘͍͕͓̱̯̩̪̠͓̫͕̖̠̤̱͕̬̞̘̭̗͍͙͚͎̗̫̘̹̫͔̹̱̟̻̬̞͙͇͉͔͙͍̟͙͈̪̞̤̪͉̫̠̤̫̭̦͍̰̪͎̠̲̣̰̠͍̪̦̞̬̘̟̳̣̼̜̻̬̗͎͓͓̳̙̳̩͙̼̬͍̝͓̲̰̤͇͚͖̠̹͖͓̜̳̳̼͈͈̝̘̹̪̱̳̱͎̙̳̩͕̞̻͍͓̗̪̖̣͚̤͇͈̳͓̝̗͔͇̖̲͙̤͉̺̮͔̞̫̱̮̻͇̼̯̹͓̥̪̩̹̳̰͍͓̖̟̮͉͔̰͙̲͓͇͉̞͓̥̖̗̘̜͖̱̯͎̺͓̬͎͕̘̻̻̥̲̖̬̯̰̞̜̫̬̪̲͎̠̳̥̫̜̠͍̼̟͓͈̻͍͈̙̮̠̱̻̫̼̯̜̯͓́͂͊̽͑̾̃̽̈́̒̓̒́̑̽͗̃̏̏̿̅̃͑̒́͌̈́́̒͊͊̆́͒̒̓͌̊͆̿̉̈́̇̑̃̇̋̾̒̽̎̍́̕̚̕̕̕̕͘̚̚͜͜͝͠͝͠͠͝ͅͅͅͅͅͅs̸̨̨̨̢̡̢̨̡̢̢̨̧̡̧̡̧̡̧̧̛̯͕̦̪̹̦͓͓̮̹͈̩͎̗̻͍̪̩̮͖̺͕͉̲̖̹̹̻͈̗͎̮̬͔̦̹͔̞̳̙̤͙͈̗̪̥̦͉̯̮͓̰̙̝͇̦̤̳̣̦͎̬̬͈͖̙̺͉̥̮̖͕̗̗͓̥͔̥̬̘͉̠̝͕̥̦̙͉͎͚͔̖͍͓̖̩̳͚͔̟̰̝̳͖̲̬̗̹͈͙̳̘̠̱͇͎̗̞̳̯̣͖͎͇̮̞̗̻̞̱̪̳͓̣̱͙̩̼͍͖̭͓͇̗̫͔̗̘̤͖͈̦̭̻͓̤͚͍̜̝̯͍͓͖̥̳̮͓̦͕̦͕̱͉̗͙̫̞͔̪͍̭͕̄̊͒͌͛̅̑̅̂͒̂̈́̃̂̀́̈͋̑̋̃̊̇̈̄̽̃̆̑̔͆̂̍͑͛͊̇̒̍̂̏̋̓̂́͐͆̎̿́̑̚̕͘̕͘͘͜͜͜͜͜͜͜͝͝͝͝͝͝ͅͅu̴̢̧̨̡̨̡̨̢̢̧̨̧̡̧̨̢̢̡̢̡̨̨̢̡̡̧̢̨͈͔̟̯͇̻͙̬̟͖̘͎͈̘͙̬̰͉̟̠͉̻̯͖̼̪͎͓͚̟̞̺͖̞͕͚̗͇͔̩̼̪͔̺̯̹͍̮̗͍͚̻̙̹͙͉͈̙͔̜̬̙̺̥̬̜̩̜̟̘̪͍̤̤̪͈͈͖̲̥͇̣͈̥͖̩̞̬̟̺̻̩̝͉̮̜̖͖̺͉̺̱̖̗̰͕͓̼̱̥̠̖̫̱̖̝̤̭̲̭̖̙͎̫̰͈̲͈̣̪̣̳͓̝͚̘̪̞͖̩̮̗̱͈͉̰̻̻̠̞͙̭̰̪͙̝̰̞͖̩͖͇̩̺̗̬̦͙͉̬̜̱̰̱͓̪͙̮̝̼̙̻͔͎̱͖͙͓̣̼̩̰̗͖̱̞̼͇̙̦̹̯̖͇̫͕͍̒̀̂̿͆̊̔̐̿̔̀͆͂̅̽̽̋̊̈́̈́̌͂̿̀̌́̔̉̑́̓̒̃̿͛̓̋̆͆́̈́̆̍̔͊͗̏̆̈́̑͑̓̀̆͘͘̕͘͘̚͜͜͜͜͝͝͠͝ͅͅͅͅͅc̶̡̢̢̢̢̨̡̨̢̧̢̨̢̨̧̢̢̡͍̖͎̪͉̼̮̲̣̪̘̮̯͖͖̼̯͙̻̮͍̲̖̙͕͖̯̠̪̯̲̞̞̠̳͈͚̜̟̙̫͎̫̱̩͈͚͎̮̱̝̼͚̺͚͇̪̱̫͇̱͈̟̲͇͔̝̯͎̗̣̘̘̺͈̼̦̖̺̖͉̬̫̥̲̣̞͔̣̣͚̤͇̻̫͉̥̖̦̫̪̠͈̙̰͈̤̤͎͕͎̙͔̪̭̼̞̙͇͕͎͔̼̘̖̦͚͔͉̫͕͔̜̮̱͉̠͓̪͕̼̳̖͙͍̭̬̞̻̬͔͕̑̐̄̆́͊͂͗̒̐̅̾͗̉̕͜͜͜͝ͅḫ̸̢̧̧̧̧̡̢̢̢̫̝̬̣̺̠̯̮͚̦̩͍̻̯̪̪̝̩̹̠̘̤͓͇̪͍̲̠͍̝͉̭̲̘̼͙͍̜̙̣̫̪̬͓̻̤͚͖͛̈̀̌͜͜͝ͅ ̴̨̢̡̡̨̨̡̢̧̡̨̡̡̛̛̛̛̹̭̗̖̹̰̼̗̳̹̯͔͚̻͚̙̹̰̪̺̩͈̳͉̼̗̝̳͖̞̯̠̭̯͎͓͎̘͉̺͇̬͇̯̜̯͓̳̞͚͍̭̯̦̺̳̘̰̲̲̜͓͔̼̺͍̟̠̙̱̞̲͉̣̮̭̗͈͕͚͚̣͓̻͍̩̣̻̲̳̹̲̫̮͚̲͍͎̰̮̮̯͖̰̥̝̮̞͍͇̹̹̫̞͔̫̭̥͉͉̱̯̻̥͈̑̔͊̆̌̇̇̌͆̍̓͛̅̂̊̂̃̌̋́͑̐̄̃̾̔͗̿͛̊̀̉͐̋͑̇̿̃̏̈́̏̔́̌̿̈́̃̈́́̈́̄̃͌̆̅̓̎̽́̑͊̑̈͛̌́̈́̿̿̐͐͗̾͛̉̐͊̏̉̏̉̏̌͋͊̍͒͐̑́̽̈́͊́̃̂͂̓̂͌̓̉̏͛̍̍̄̐̃͐̐͒̉̏̈̐̒̔̈́͒͆̈́̾̄͛̋̔̿̅́̃͌̎͐̀̿̊̍̿̊͌̚̚̚͘͘͘̚̕̕͜͜͜͜͠͠͠͠͝͝͝͝͝ͅͅf̶̨̢̡̢̢̢̢̡̨̡̢̧̢̨̨̧̢̨̨̨̨̢̧̢̢̦͇̼̹̫͔̬͔͎͇̱͉̜̤̟̩̖̯̞̱̗̺͎͖̙͖̱̻̩̮̯̲̝̥̟̠̰̘̮̖̹̲͖̖̪͖̲̖̫͈̞̫̣̗̖̝̹̟̙͓͙͖̺͉͚̪̣͓̮͉̦̪͕̗͈̩̗̤͈̮̱͈̙͉͙̭̼̺̻͙̟̥̬̤̤̺̼͚̣̗͙͇̬̭͇̖͇̖̣͎̜̭͙̠̤̫̫͙͕̺̱͙̟̤̦͓̦͍̜̖͉̥̤͓̹͉̮͇̙͍̙̠̳̲͉̦̮̣͇̠͕͙̫̗̲̘̞͎͕̗̹̞̟̺̥̤̥̪̝̹͎͚̦͍͓͓̘̟̼͙̯̠̮̖̲̲̪̜̖̝̙͉͚̼̳̘̘̻͕̘͓̜̯͙͕͉̬̲̲̼̥̭̰͕̣̻̬̫̬̼̖͈̺̞̹̘̭͈̼̣̮̘̜̗̦̬͓͇͉͍̮͕̲͙̗͍̝̝͉͔̻͔̭͇̟̞̜̘̗̥̲̉̎̀͛̈͊̋̾͋͑̾̃̽̽̓͆̉̃́̈́́͐͂͜͜͜͜͜͝͝͝ͅͅͅͅͅͅͅͅư̸̡̧̢̨̨̢̨̡̧̛̛̛͕̺̘̗͕̪̟̞̳͖̲̻̻̦̤̤͔̬͍̦͈̬͇̯̭͉̬͚̙͙̼͎̩̠̺͙̫̜͙̜̮̬͎̩̼̣͔̦̘̫̞͖͕̻̩̻̱̫̻͉̬͚̘̫̟̣̱̮̞͍̖̰̫͙̭̳͓̦̯͙̣̫̼͓̱͚̩̺͉̭̮̠̮̲̭̙̳͇͙͉̺̖͙̼͔͇̤͙͈̭̟̹̰͎̝͓̗̘̼̤̞̪̱̜̭̖̣͔̹̹̠̝̖̪͉͕̌̍̋́̈̾̓͆͗̑͆̄̓̏̃͒̄̎̐͌̍̐̓̎͊͂̉̍͆́͆̋̒̆̌͗̓͗͋̃̈́̈́̌̏͒̌̏͗̓̿͌̄̃̎̿͋͌̒̏̀͐͆̋̿̕̕̕͜͝͝͠͝͠͝͠͠ͅͅͅǹ̵̨̨̧̨̧̢̡̧̨̡̨̨̨̢̢̨̡̧̨̡̢̡̢̳̙̻̘͔͈̹͓̺̩̦̦̻̥͓͚̟͚͕͔͉̺͈̝͓̯͔͕͍͕̖̬̟̝̰̩̩̰͍̮̥̦̝̲̜̬̝̩͔̺͍͍̻̺̱͎̫͍̥͉̯̳͉͓̟͈̳̤͚̘̮̱̭̞̻̦̗̹̠͖̫̫̤̹̗̺͔̖̦̰̮̬̱̖̹͉̩̬̭̖̦͚̻̹̖̮͙͎̣͓̳̪̳͍͍̗̺̯͈̙͓̣̗̦͙̺͚̰̪͍̤̻̥̣̬̻̜̘̘͇̟̜̝̼̩͇̣̤̳̹̩̜͖̜̤̩̺̼̻̩̟̝̩̼̩̲͖̟̣̝͇̜͙̗̞̦̘͙̳͚̺̫̰̜̖͉̟̗͖͕̬̦̥̮̜̙̬̺͓̠̯̤̮̼̜͙͉̰̙̗͕͍͚̦͕̮͉͈̙̪͓̳̯̟̱̦̹̭̺̼͉̯̯͖̖̘̮̞̼͎̪͖͙̭͍̣̯͚̾̽͒͒̊̈̃̐͐͒̉̋̎͑͆̈̎͌̃̒͊̔͑̄̿͑̃̓͐͆̿̿̾̃̏̀̚̕͜͜͜͜͝͝ͅͅͅͅͅͅ!̶̡̢̨̨̨̡̡̨̡̨̨̨̢̢̧̢̢̢̢̡̨̛̛̛̛̭̲̺͔̰͓͓͈͍̖̮̭̤̩͚̭̩̼̫͈̹̙̭͚͇̗͖̙̙̼̰͔̭͓͎̯͓̯̜͚̗̝͔͉̼̠̹͚͇̩̬̬͓͚̭͎̠̖͖̬̞͉͎͎͉̘̩̬̺̳̖̻̘͎̹̹͕̟̗͉̰͖̮͔͇̘̞̭̮͈̲̪͉͈̻̹̻̣͖̠̙͎͍͉̤̭̳̞̳̝̠̳̺͈̺͍̮̭̺͚̹̫͓͎̱̹̰͓̺̘͓͇̙͙̱͉̟̙͖̭̙̳̰̮̻̬̖̲̹͖̝̬̳͉̗̫̮̮̹͚̹͕̤͓̺̮̜̜̻̩̦̪͓͎̬͍̗̺̝̗̣̘̖͇̬̻͍̮̜͚̱͍̗͔͎͙̗̳̞̩̩͇͕͈͙̬̻̮͕̤̲͚̘̥̙̻̲̠̦͍̩̺̩̭͓̘͙͎̳̝̞͚̄̍̇̎̊̉̃̄͐͆̒͗̈́͛̊͗̉̑̅̒̈́̀̈̈́̌̊̂̃̍̈́̊͒̂̆̎̈́͌́̆͑͆̈́̐͗͋̾̇̂̍̃͑̏͐̍̐̌̑̃̄̓̓̃̽̑̂̂͌͊͆͋̉̇̓̽͛̂̅̀̀̌̎̌̈́̐̽͊͒̀͛̏̌͐̈́̽͒̉̇͒͑͋͛́̽͋̋̊̋̒̈́͛̉̒͊́̓̋͂̋̓̅̃͗́́̾͋͛̃́́̋̎̌̓̄̽̔̌́̅̎̓̎͆́̋͊͆͒͒̈́̂̆͐͋̐̿͆̿̾̿̅͑́̿̏̌̅̌͊͐̔͌̽͆͒͋̈̇̀̈́́͑͐̍̏̀̓̀̓̐͑̓͒̉̂̇͐͐͌̀̈́̅̓͊̓͌̔͂̀͗̓͑́̈́̀̉̀̓̇͐̒͛̈́̀̉̏̐̃̈͂̋̋̀͛̈̌̎̏̐͛̑͊͗̐͘̚͘͘̚͘̚̕͘͘͘͘͘̚̕͘̕̕͘̚͜͜͜͜͜͜͜͜͜͝͠͠͠͝͠͝͝͠͝͝͝͠͝͝͠͝͠͝͝͝͠͝ͅͅͅͅͅͅ + + T̸h̴e̶ ̵p̷o̷w̶e̵r̷f̸u̷l̷ ̵p̴r̷o̷g̶r̷a̸m̸m̶i̸n̴g̴ ̷l̶a̴n̸g̵u̵a̶g̸e̶ ̸t̶h̴a̵t̵ ̶i̷s̶ ̵a̷l̴s̸o̷ ̵e̵a̷s̷y̴ ̵t̵o̷ ̷l̷e̶a̵r̴n̸.̵ + """# + + +func randomStride( + from start: Int, + to end: Int, + by maxStep: Int, + seed: Int +) -> UnfoldSequence { + var rng = RepeatableRandomNumberGenerator(seed: seed) + return sequence(state: start, next: { + $0 += Int.random(in: 1 ... maxStep, using: &rng) + guard $0 < end else { return nil } + return $0 + }) +} + + +let sampleString2 = + #""" + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + The powerful programming language that is also easy to learn. + Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# + tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# + concise yet expressive, and Swift includes modern features developers love. \# + Swift code is safe by design and produces software that runs lightning-fast. + + """# diff --git a/Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift b/Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift new file mode 100644 index 00000000..37834fad --- /dev/null +++ b/Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift @@ -0,0 +1,45 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-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 +// +//===----------------------------------------------------------------------===// + +var globalSeed: Int { + 42.hashValue +} + +public struct RepeatableRandomNumberGenerator: RandomNumberGenerator { + // This uses the same linear congruential generator as rand48. + // FIXME: Replace with something better. + internal static let _m: UInt64 = 1 << 48 + internal static let _a: UInt64 = 25214903917 + internal static let _c: UInt64 = 11 + + internal var _state: UInt64 + + public init(seed: Int) { + self.init(seed: UInt64(truncatingIfNeeded: seed)) + } + + public init(seed: UInt64) { + // Perturb the seed a little so that the sequence doesn't start with a + // zero value in the common case of seed == 0. (Using a zero seed is a + // rather silly thing to do, but it's the easy thing.) + let global = UInt64(truncatingIfNeeded: globalSeed) + _state = seed ^ global ^ 0x536f52616e646f6d // "SoRandom" + } + + private mutating func _next() -> UInt64 { + _state = (Self._a &* _state &+ Self._c) & (Self._m - 1) + return _state &>> 16 + } + + public mutating func next() -> UInt64 { + return (_next() &<< 32) | _next() + } +} diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift new file mode 100644 index 00000000..94e47457 --- /dev/null +++ b/Tests/RopeModuleTests/TestBString.swift @@ -0,0 +1,368 @@ +//===----------------------------------------------------------------------===// +// +// 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 DEBUG +@testable import RopeModule +import XCTest + +class TestBString: XCTestCase { + override class func setUp() { + // Turn off output buffering. + setbuf(stdout, nil) + setbuf(stderr, nil) + super.setUp() + } + + override func setUp() { + print("Global seed: \(globalSeed)") + } + + func test_empty() { + let s = _BString() + s.invariantCheck() + XCTAssertEqual(s.characterCount, 0) + XCTAssertEqual(s.unicodeScalarCount, 0) + XCTAssertEqual(s.utf16Count, 0) + XCTAssertEqual(s.utf8Count, 0) + XCTAssertTrue(s.isEmpty) + XCTAssertEqual(s.startIndex, s.endIndex) + XCTAssertEqual(s.startIndex._utf8Offset, 0) + } + + func test_string_conversion() { + let big = _BString(sampleString) + + big.invariantCheck() + XCTAssertEqual(big.characterCount, sampleString.count) + XCTAssertEqual(big.unicodeScalarCount, sampleString.unicodeScalars.count) + XCTAssertEqual(big.utf16Count, sampleString.utf16.count) + XCTAssertEqual(big.utf8Count, sampleString.utf8.count) + + let flat = String(_from: big) + XCTAssertEqual(flat, sampleString) + } + + @discardableResult + func checkCharacterIndices( + _ flat: String, + _ big: _BString, + file: StaticString = #file, line: UInt = #line + ) -> (flat: [String.Index], big: [_BString.Index]) { + let indices1 = Array(flat.indices) + [flat.endIndex] + let indices2 = Array( + sequence(first: big.startIndex) { + $0 == big.endIndex ? nil : big.characterIndex(after: $0) + } + ) + + XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + for i in 0 ..< min(indices1.count, indices2.count) { + let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) + let d2 = big.utf8Distance(from: big.startIndex, to: indices2[i]) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + return (indices1, indices2) + } + + @discardableResult + func checkScalarIndices( + _ flat: String, + _ big: _BString, + file: StaticString = #file, line: UInt = #line + ) -> (flat: [String.Index], big: [_BString.Index]) { + let indices1 = Array(flat.unicodeScalars.indices) + [flat.unicodeScalars.endIndex] + let indices2 = Array( + sequence(first: big.startIndex) { + $0 == big.endIndex ? nil : big.unicodeScalarIndex(after: $0) + } + ) + + XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + for i in 0 ..< min(indices1.count, indices2.count) { + let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) + let d2 = big.utf8Distance(from: big.startIndex, to: indices2[i]) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + return (indices1, indices2) + } + + @discardableResult + func checkUTF8Indices( + _ flat: String, + _ big: _BString, + file: StaticString = #file, line: UInt = #line + ) -> (flat: [String.Index], big: [_BString.Index]) { + let indices1 = Array(flat.utf8.indices) + [flat.utf8.endIndex] + let indices2 = Array( + sequence(first: big.startIndex) { + $0 == big.endIndex ? nil : big.utf8Index(after: $0) + } + ) + + XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + for i in 0 ..< min(indices1.count, indices2.count) { + let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) + let d2 = big.utf8Distance(from: big.startIndex, to: indices2[i]) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + return (indices1, indices2) + } + + @discardableResult + func checkUTF16Indices( + _ flat: String, + _ big: _BString, + file: StaticString = #file, line: UInt = #line + ) -> (flat: [String.Index], big: [_BString.Index]) { + let indices1 = Array(flat.utf16.indices) + [flat.utf16.endIndex] + let indices2 = Array( + sequence(first: big.startIndex) { + $0 == big.endIndex ? nil : big.utf16Index(after: $0) + } + ) + + XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + for i in 0 ..< min(indices1.count, indices2.count) { + let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) + let d2 = big.utf8Distance(from: big.startIndex, to: indices2[i]) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]._description), i2: \(indices2[i])", file: file, line: line) + } + return (indices1, indices2) + } + + func test_indices_character() { + let flat = sampleString + let big = _BString(flat) + + let (indices1, indices2) = checkCharacterIndices(flat, big) + + let c = min(indices1.count, indices2.count) + for i in randomStride(from: 0, to: c, by: 5, seed: 0) { + for j in randomStride(from: i, to: c, by: 5, seed: i) { + let i1 = indices1[i] + let j1 = indices1[j] + let a = String(sampleString[i1 ..< j1]) + + let i2 = indices2[i] + let j2 = big.characterIndex(i2, offsetBy: j - i) + let b = String(_from: big, in: i2 ..< j2) + XCTAssertEqual(b, a) + } + } + } + + func test_indices_scalar() { + let flat = sampleString + let big = _BString(flat) + + let (indices1, indices2) = checkScalarIndices(flat, big) + + let c = min(indices1.count, indices2.count) + for i in randomStride(from: 0, to: c, by: 20, seed: 0) { + for j in randomStride(from: i, to: c, by: 20, seed: i) { + let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) + + let i2 = indices2[i] + let j2 = big.unicodeScalarIndex(i2, offsetBy: j - i) + let b = String(_from: big, in: i2 ..< j2) + XCTAssertEqual(b, a) + } + } + } + + func test_indices_utf16() { + let flat = sampleString + let big = _BString(flat) + + let (indices1, indices2) = checkUTF16Indices(flat, big) + + let c = min(indices1.count, indices2.count) + for i in randomStride(from: 0, to: c, by: 20, seed: 0) { + for j in randomStride(from: i, to: c, by: 20, seed: i) { + let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) + + let i2 = indices2[i] + let j2 = big.utf16Index(i2, offsetBy: j - i) + let b = String(_from: big, in: i2 ..< j2) + XCTAssertEqual(b, a) + } + } + } + + func test_indices_utf8() { + let flat = sampleString + let big = _BString(flat) + + let (indices1, indices2) = checkUTF8Indices(flat, big) + + let c = min(indices1.count, indices2.count) + for i in randomStride(from: 0, to: c, by: 40, seed: 0) { + for j in randomStride(from: i, to: c, by: 40, seed: i) { + let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) + + let i2 = indices2[i] + let j2 = big.utf8Index(i2, offsetBy: j - i) + let b = String(_from: big, in: i2 ..< j2) + XCTAssertEqual(b, a) + } + } + } + + func test_append_string() { + let flat = sampleString + let ref = _BString(flat) + for stride in [1, 2, 4, 8, 16, 32, 64, 128, 250, 1000, 10000, 20000] { + var big: _BString = "" + var i = flat.startIndex + while i < flat.endIndex { + let j = flat.unicodeScalars.index(i, offsetBy: stride, limitedBy: flat.endIndex) ?? flat.endIndex + let next = String(flat[i ..< j]) + big.append(contentsOf: next) + //big.invariantCheck() + //XCTAssertEqual(String(big)[...], s[.. [(i: Int, str: String)] { + var pieces: [(i: Int, str: String)] = [] + var c = 0 + var i = str.startIndex + while i < str.endIndex { + let j = str.unicodeScalars.index(i, offsetBy: stride, limitedBy: str.endIndex) ?? str.endIndex + let next = String(str[i ..< j]) + pieces.append((c, next)) + c += 1 + i = j + } + return pieces + } + + func test_insert_string() { + let flat = sampleString + let ref = _BString(flat) + for stride in [1, 2, 4, 8, 16, 32, 64, 128, 250, 1000, 10000, 20000] { + print("Stride: \(stride)") + var pieces = pieces(of: flat, by: stride) + var rng = RepeatableRandomNumberGenerator(seed: 0) + pieces.shuffle(using: &rng) + + var big: _BString = "" + var smol = "" + for i in pieces.indices { + let piece = pieces[i] + let utf8Offset = pieces[..") + XCTAssertEqual(s.utf16.description, "<0043 0061 0066 00E9>") + } + + func test_string_conversion() { + let big = BigString(sampleString) + + big._invariantCheck() + XCTAssertEqual(big.count, sampleString.count) + XCTAssertEqual(big.unicodeScalars.count, sampleString.unicodeScalars.count) + XCTAssertEqual(big.utf16.count, sampleString.utf16.count) + XCTAssertEqual(big.utf8.count, sampleString.utf8.count) + + let flat = String(big) + XCTAssertEqual(flat, sampleString) + } + + @discardableResult + func checkCharacterIndices( + _ flat: String, + _ big: BigString, + file: StaticString = #file, line: UInt = #line + ) -> (flat: [String.Index], big: [BigString.Index]) { + let indices1 = Array(flat.indices) + [flat.endIndex] + let indices2 = Array( + sequence(first: big.startIndex) { + $0 == big.endIndex ? nil : big.index(after: $0) + } + ) + + XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + + let c = min(indices1.count, indices2.count) + + for i in 0 ..< min(c, indices1.count - 1) { + let c1 = flat[indices1[i]] + let c2 = big[indices2[i]] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + + for i in 0 ..< c { + let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) + let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + return (indices1, indices2) + } + + @discardableResult + func checkScalarIndices( + _ flat: String, + _ big: BigString, + file: StaticString = #file, line: UInt = #line + ) -> (flat: [String.Index], big: [BigString.Index]) { + let indices1 = Array(flat.unicodeScalars.indices) + [flat.unicodeScalars.endIndex] + let indices2 = Array( + sequence(first: big.startIndex) { + $0 == big.endIndex ? nil : big.unicodeScalars.index(after: $0) + } + ) + + XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + + let c = min(indices1.count, indices2.count) + + for i in 0 ..< min(c, indices1.count - 1) { + let s1 = flat.unicodeScalars[indices1[i]] + let s2 = big.unicodeScalars[indices2[i]] + XCTAssertEqual(s1, s2, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + + for i in 0 ..< min(indices1.count, indices2.count) { + let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) + let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + return (indices1, indices2) + } + + @discardableResult + func checkUTF8Indices( + _ flat: String, + _ big: BigString, + file: StaticString = #file, line: UInt = #line + ) -> (flat: [String.Index], big: [BigString.Index]) { + let indices1 = Array(flat.utf8.indices) + [flat.utf8.endIndex] + let indices2 = Array( + sequence(first: big.startIndex) { + $0 == big.endIndex ? nil : big.utf8.index(after: $0) + } + ) + + XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + + let c = min(indices1.count, indices2.count) + + for i in 0 ..< min(c, indices1.count - 1) { + let c1 = flat.utf8[indices1[i]] + let c2 = big.utf8[indices2[i]] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + + for i in 0 ..< min(indices1.count, indices2.count) { + let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) + let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + return (indices1, indices2) + } + + @discardableResult + func checkUTF16Indices( + _ flat: String, + _ big: BigString, + file: StaticString = #file, line: UInt = #line + ) -> (flat: [String.Index], big: [BigString.Index]) { + let indices1 = Array(flat.utf16.indices) + [flat.utf16.endIndex] + let indices2 = Array( + sequence(first: big.startIndex) { + $0 == big.endIndex ? nil : big.utf16.index(after: $0) + } + ) + + XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + + let c = min(indices1.count, indices2.count) + + for i in 0 ..< min(c, indices1.count - 1) { + let c1 = flat.utf16[indices1[i]] + let c2 = big.utf16[indices2[i]] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + } + + for i in 0 ..< min(indices1.count, indices2.count) { + let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) + let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]._description), i2: \(indices2[i])", file: file, line: line) + } + return (indices1, indices2) + } + + func test_iterator_character() { + let small: BigString = "Cafe\u{301} 👩‍👩‍👧" + var it = small.makeIterator() + XCTAssertEqual(it.next(), "C") + XCTAssertEqual(it.next(), "a") + XCTAssertEqual(it.next(), "f") + XCTAssertEqual(it.next(), "e\u{301}") + XCTAssertEqual(it.next(), " ") + XCTAssertEqual(it.next(), "👩‍👩‍👧") + XCTAssertNil(it.next()) + + let flat = sampleString + let big = BigString(flat) + + let c1 = Array(flat) + let c2 = Array(big) + XCTAssertEqual(c1, c2) + } + + func test_iterator_scalar() { + let flat = sampleString + let big = BigString(flat) + + let c1 = Array(flat.unicodeScalars) + let c2 = Array(big.unicodeScalars) + XCTAssertEqual(c1, c2) + } + + func test_iterator_utf8() { + let flat = sampleString + let big = BigString(flat) + + let c1 = Array(flat.utf8) + let c2 = Array(big.utf8) + XCTAssertEqual(c1, c2) + } + + func test_iterator_utf16() { + let flat = sampleString + let big = BigString(flat) + + let c1 = Array(flat.utf16) + let c2 = Array(big.utf16) + XCTAssertEqual(c1, c2) + } + + func test_indices_character() { + let flat = sampleString + let big = BigString(flat) + + let (indices1, indices2) = checkCharacterIndices(flat, big) + + let c = min(indices1.count, indices2.count) + for i in randomStride(from: 0, to: c, by: 5, seed: 0) { + for j in randomStride(from: i, to: c, by: 5, seed: i) { + let i1 = indices1[i] + let j1 = indices1[j] + let a = String(sampleString[i1 ..< j1]) + + let i2 = indices2[i] + let j2 = big.index(i2, offsetBy: j - i) + let b = String(big[i2 ..< j2]) + XCTAssertEqual(b, a) + } + } + } + + func test_indices_scalar() { + let flat = sampleString + let big = BigString(flat) + + let (indices1, indices2) = checkScalarIndices(flat, big) + + let c = min(indices1.count, indices2.count) + for i in randomStride(from: 0, to: c, by: 20, seed: 0) { + for j in randomStride(from: i, to: c, by: 20, seed: i) { + let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) + + let i2 = indices2[i] + let j2 = big.unicodeScalars.index(i2, offsetBy: j - i) + let b = String(big[i2 ..< j2]) + XCTAssertEqual(b, a) + } + } + } + + func test_indices_utf16() { + let flat = sampleString + let big = BigString(flat) + + let (indices1, indices2) = checkUTF16Indices(flat, big) + + let c = min(indices1.count, indices2.count) + for i in randomStride(from: 0, to: c, by: 20, seed: 0) { + for j in randomStride(from: i, to: c, by: 20, seed: i) { + let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) + + let i2 = indices2[i] + let j2 = big.utf16.index(i2, offsetBy: j - i) + let b = String(big[i2 ..< j2]) + XCTAssertEqual(b, a) + } + } + } + + func test_indices_utf8() { + let flat = sampleString + let big = BigString(flat) + + let (indices1, indices2) = checkUTF8Indices(flat, big) + + let c = min(indices1.count, indices2.count) + for i in randomStride(from: 0, to: c, by: 40, seed: 0) { + for j in randomStride(from: i, to: c, by: 40, seed: i) { + let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) + + let i2 = indices2[i] + let j2 = big.utf8.index(i2, offsetBy: j - i) + let b = String(big[i2 ..< j2]) + XCTAssertEqual(b, a) + } + } + } + + func test_append_string() { + let flat = sampleString + let ref = BigString(flat) + for stride in [1, 2, 4, 8, 16, 32, 64, 128, 250, 1000, 10000, 20000] { + var big: BigString = "" + var i = flat.startIndex + while i < flat.endIndex { + let j = flat.unicodeScalars.index(i, offsetBy: stride, limitedBy: flat.endIndex) ?? flat.endIndex + let next = String(flat[i ..< j]) + big.append(contentsOf: next) + //big._invariantCheck() + //XCTAssertEqual(String(big)[...], s[.. [(i: Int, str: String)] { + var pieces: [(i: Int, str: String)] = [] + var c = 0 + var i = str.startIndex + while i < str.endIndex { + let j = str.unicodeScalars.index(i, offsetBy: stride, limitedBy: str.endIndex) ?? str.endIndex + let next = String(str[i ..< j]) + pieces.append((c, next)) + c += 1 + i = j + } + return pieces + } + + func test_insert_string() { + let flat = sampleString + let ref = BigString(flat) + for stride in [1, 2, 4, 8, 16, 32, 64, 128, 250, 1000, 10000, 20000] { + print("Stride: \(stride)") + var pieces = pieces(of: flat, by: stride) + var rng = RepeatableRandomNumberGenerator(seed: 0) + pieces.shuffle(using: &rng) + + var big: BigString = "" + var smol = "" + for i in pieces.indices { + let piece = pieces[i] + let utf8Offset = pieces[.. Bool { left.length == right.length } + static func <(left: Self, right: Self) -> Bool { left.length < right.length } + + static var maxNodeSize: Int { 6 } + static var nodeSizeBitWidth: Int { 3 } + } + + struct Metric: _RopeMetric { + typealias Element = Chunk + + func size(of summary: Chunk.Summary) -> Int { + summary.length + } + + func index(at offset: Int, in element: Chunk) -> Int { + precondition(offset >= 0 && offset <= element.length) + return offset + } + } + + init(length: Int, value: Int) { + self.length = length + self.value = value + } + + var description: String { + "\(value)*\(length)" + } + + var summary: Summary { + Summary(length) + } + + var isEmpty: Bool { length == 0 } + var isUndersized: Bool { isEmpty } + + func invariantCheck() {} + + mutating func rebalance(prevNeighbor left: inout Chunk) -> Bool { + // Fully merge neighbors that have the same value + if left.value == self.value { + self.length += left.length + left.length = 0 + return true + } + if left.isEmpty { return true } + guard self.isEmpty else { return false } + swap(&self, &left) + return true + } + + mutating func rebalance(nextNeighbor right: inout Chunk) -> Bool { + // Fully merge neighbors that have the same value + if self.value == right.value { + self.length += right.length + right.length = 0 + return true + } + if right.isEmpty { return true } + guard self.isEmpty else { return false } + swap(&self, &right) + return true + } + + typealias Index = Int + + mutating func split(at index: Int) -> Chunk { + precondition(index >= 0 && index <= length) + let tail = Chunk(length: length - index, value: value) + self.length = index + return tail + } +} + +class TestRope: XCTestCase { + override func setUp() { + print("Global seed: \(globalSeed)") + } + + func test_empty() { + let empty = _Rope() + empty.invariantCheck() + XCTAssertTrue(empty.isEmpty) + XCTAssertEqual(empty.count, 0) + XCTAssertTrue(empty.summary.isZero) + XCTAssertEqual(empty.startIndex, empty.endIndex) + } + + func test_build() { + let c = 1000 + + let ref = (0 ..< c).map { + Chunk(length: ($0 % 4) + 1, value: $0) + } + var builder = _Rope.Builder() + for chunk in ref { + builder.append(chunk) + builder.invariantCheck() + } + let rope = builder.finalize() + + let actualSum = rope.summary + let expectedSum: Chunk.Summary = ref.reduce(into: .zero) { $0.add($1.summary) } + XCTAssertEqual(actualSum, expectedSum) + + XCTAssertTrue(rope.elementsEqual(ref)) + } + + func test_iteration() { + for c in [0, 1, 2, 10, 100, 500, 1000, 10000] { + let ref = (0 ..< c).map { + Chunk(length: ($0 % 4) + 1, value: $0) + } + let rope = _Rope(ref) + XCTAssertTrue(rope.elementsEqual(ref)) + + let expectedLength = ref.reduce(into: 0) { $0 += $1.length } + let actualLength = rope.reduce(into: 0) { $0 += $1.length } + XCTAssertEqual(actualLength, expectedLength) + } + } + + func test_subscript() { + for c in [0, 1, 2, 10, 100, 500, 1000, 10000] { + let ref = (0 ..< c).map { + Chunk(length: ($0 % 4) + 1, value: $0) + } + let rope = _Rope(ref) + XCTAssertTrue(rope.elementsEqual(ref)) + + var i = rope.startIndex + var j = 0 + while i != rope.endIndex, j != ref.count { + XCTAssertEqual(rope[i], ref[j]) + i = rope.index(after: i) + j += 1 + } + XCTAssertEqual(i, rope.endIndex) + XCTAssertEqual(j, ref.count) + } + } + + func test_index_before() { + for c in [0, 1, 2, 10, 100, 500, 1000, 10000] { + let ref = (0 ..< c).map { + Chunk(length: ($0 % 4) + 1, value: $0) + } + let rope = _Rope(ref) + XCTAssertTrue(rope.elementsEqual(ref)) + + var indices: [_Rope.Index] = [] + var i = rope.startIndex + while i != rope.endIndex { + indices.append(i) + i = rope.index(after: i) + } + + while let j = indices.popLast() { + i = rope.index(before: i) + XCTAssertEqual(i, j) + } + } + } + + func test_distance() { + let c = 500 + + let ref = (0 ..< c).map { + Chunk(length: ($0 % 4) + 1, value: $0) + } + let rope = _Rope(ref) + + let indices = Array(rope.indices) + [rope.endIndex] + XCTAssertEqual(indices.count, c + 1) + for i in indices.indices { + for j in indices.indices { + let d = rope.distance(from: indices[i], to: indices[j], in: Chunk.Metric()) + let r = ( + i <= j + ? ref[i..(ref) + + let indices = Array(rope.indices) + [rope.endIndex] + XCTAssertEqual(indices.count, c + 1) + for i in indices.indices { + for j in indices.indices { + let d = ( + i <= j + ? ref[i..() + var ref: [Chunk] = [] + + for i in 0 ..< c { + let chunk = Chunk(length: (i % 4) + 1, value: i) + ref.append(chunk) + rope.append(chunk) + rope.invariantCheck() + } + + let actualSum = rope.summary + let expectedSum: Chunk.Summary = ref.reduce(into: .zero) { $0.add($1.summary) } + XCTAssertEqual(actualSum, expectedSum) + + XCTAssertTrue(rope.elementsEqual(ref)) + } + + func test_prepend_item() { + let c = 1000 + + let ref = (0 ..< c).map { + Chunk(length: ($0 % 4) + 1, value: $0) + } + + var rope = _Rope() + for chunk in ref.reversed() { + rope.insert(chunk, at: 0, in: Chunk.Metric()) + rope.invariantCheck() + } + + let actualSum = rope.summary + let expectedSum: Chunk.Summary = ref.reduce(into: .zero) { $0.add($1.summary) } + XCTAssertEqual(actualSum, expectedSum) + + XCTAssertTrue(rope.elementsEqual(ref)) + } + + func test_insert_item() { + let c = 1000 + let ref = (0 ..< c).map { + Chunk(length: ($0 % 4) + 1, value: $0) + } + + var rng = RepeatableRandomNumberGenerator(seed: 0) + let input = ref.shuffled(using: &rng) + + var rope = _Rope() + for i in input.indices { + let chunk = input[i] + let position = input[..(ref) + + var rng = RepeatableRandomNumberGenerator(seed: 0) + let input = ref.shuffled(using: &rng) + + for i in input.indices { + let chunk = input[i] + let offset = input[i...].reduce(into: 0) { + $0 += $1.value < chunk.value ? 1 : 0 + } + let index = rope.index(rope.startIndex, offsetBy: offset) + let removed = rope.remove(at: index) + XCTAssertEqual(removed, chunk) + rope.invariantCheck() + } + XCTAssertTrue(rope.isEmpty) + XCTAssertEqual(rope.summary, .zero) + } + + func test_remove_at_position() { + let c = 1000 + let ref = (0 ..< c).map { + Chunk(length: ($0 % 4) + 1, value: $0) + } + + var rope = _Rope(ref) + + var rng = RepeatableRandomNumberGenerator(seed: 0) + let input = ref.shuffled(using: &rng) + + for i in input.indices { + let chunk = input[i] + let position = input[i...].reduce(into: 0) { + $0 += $1.value < chunk.value ? $1.length : 0 + } + let removed = rope.remove(at: position, in: Chunk.Metric()) + XCTAssertEqual(removed, chunk) + rope.invariantCheck() + } + XCTAssertTrue(rope.isEmpty) + XCTAssertEqual(rope.summary, .zero) + } + + func test_join() { + let c = 100_000 + var trees = (0 ..< c).map { + let chunk = Chunk(length: ($0 % 4) + 1, value: $0) + return _Rope(CollectionOfOne(chunk)) + } + var ranges = (0 ..< c).map { $0 ..< $0 + 1 } + + var rng = RepeatableRandomNumberGenerator(seed: 0) + while trees.count >= 2 { + let i = (0 ..< trees.count - 1).randomElement(using: &rng)! + let expectedRange = ranges[i].lowerBound ..< ranges[i + 1].upperBound + + let a = trees[i] + let b = trees.remove(at: i + 1) + trees[i] = _Rope() + + let joined = _Rope.join(a, b) + joined.invariantCheck() + let actualValues = joined.map { $0.value } + XCTAssertEqual(actualValues, Array(expectedRange)) + trees[i] = joined + ranges.replaceSubrange(i ... i + 1, with: CollectionOfOne(expectedRange)) + } + XCTAssertEqual(ranges, [0 ..< c]) + } + + func chunkify(_ values: [Int]) -> [Chunk] { + var result: [Chunk] = [] + var last = Int.min + var length = 0 + for i in values { + if length == 0 || i == last { + length += 1 + } else { + result.append(Chunk(length: length, value: last)) + length = 1 + } + last = i + } + if length > 0 { + result.append(Chunk(length: length, value: last)) + } + return result + } + + func checkEqual( + _ x: _Rope, + _ y: [Int], + file: StaticString = #file, + line: UInt = #line + ) { + let u = Array(x) + let v = chunkify(y) + XCTAssertEqual(u, v, file: file, line: line) + } + + func checkRemoveSubrange( + _ a: _Rope, + _ b: [Int], + range: Range, + file: StaticString = #file, + line: UInt = #line + ) { + var x = a + x.removeSubrange(range, in: Chunk.Metric()) + var y = b + y.removeSubrange(range) + + checkEqual(x, y, file: file, line: line) + } + + func test_removeSubrange_simple() { + var rope = _Rope() + for i in 0 ..< 10 { + rope.append(Chunk(length: 10, value: i)) + } + let ref = (0 ..< 10).flatMap { Array(repeating: $0, count: 10) } + + // Basics + checkRemoveSubrange(rope, ref, range: 0 ..< 0) + checkRemoveSubrange(rope, ref, range: 30 ..< 30) + checkRemoveSubrange(rope, ref, range: 0 ..< 100) + + // Whole individual chunks + checkRemoveSubrange(rope, ref, range: 90 ..< 100) + checkRemoveSubrange(rope, ref, range: 0 ..< 10) + checkRemoveSubrange(rope, ref, range: 30 ..< 40) + checkRemoveSubrange(rope, ref, range: 70 ..< 80) + + // Prefixes of single chunks + checkRemoveSubrange(rope, ref, range: 0 ..< 1) + checkRemoveSubrange(rope, ref, range: 30 ..< 35) + checkRemoveSubrange(rope, ref, range: 60 ..< 66) + checkRemoveSubrange(rope, ref, range: 90 ..< 98) + + // Suffixes of single chunks + checkRemoveSubrange(rope, ref, range: 9 ..< 10) + checkRemoveSubrange(rope, ref, range: 35 ..< 40) + checkRemoveSubrange(rope, ref, range: 64 ..< 70) + checkRemoveSubrange(rope, ref, range: 98 ..< 100) + + // Neighboring couple of whole chunks + checkRemoveSubrange(rope, ref, range: 0 ..< 20) + checkRemoveSubrange(rope, ref, range: 80 ..< 100) + checkRemoveSubrange(rope, ref, range: 10 ..< 30) + checkRemoveSubrange(rope, ref, range: 50 ..< 70) // Crosses nodes! + + // Longer whole chunk sequences + checkRemoveSubrange(rope, ref, range: 0 ..< 30) + checkRemoveSubrange(rope, ref, range: 70 ..< 90) + checkRemoveSubrange(rope, ref, range: 0 ..< 60) // entire first node + checkRemoveSubrange(rope, ref, range: 60 ..< 100) // entire second node + checkRemoveSubrange(rope, ref, range: 40 ..< 70) // crosses into second node + checkRemoveSubrange(rope, ref, range: 10 ..< 90) // crosses into second node + + // Arbitrary cuts + checkRemoveSubrange(rope, ref, range: 0 ..< 69) + checkRemoveSubrange(rope, ref, range: 42 ..< 73) + checkRemoveSubrange(rope, ref, range: 21 ..< 89) + checkRemoveSubrange(rope, ref, range: 1 ..< 99) + checkRemoveSubrange(rope, ref, range: 1 ..< 59) + checkRemoveSubrange(rope, ref, range: 61 ..< 99) + + } + + func test_removeSubrange_larger() { + var rope = _Rope() + for i in 0 ..< 100 { + rope.append(Chunk(length: 10, value: i)) + } + let ref = (0 ..< 100).flatMap { Array(repeating: $0, count: 10) } + + checkRemoveSubrange(rope, ref, range: 0 ..< 0) + checkRemoveSubrange(rope, ref, range: 0 ..< 1000) + checkRemoveSubrange(rope, ref, range: 0 ..< 100) + checkRemoveSubrange(rope, ref, range: 900 ..< 1000) + checkRemoveSubrange(rope, ref, range: 120 ..< 330) + checkRemoveSubrange(rope, ref, range: 734 ..< 894) + checkRemoveSubrange(rope, ref, range: 183 ..< 892) + + checkRemoveSubrange(rope, ref, range: 181 ..< 479) + checkRemoveSubrange(rope, ref, range: 191 ..< 469) + checkRemoveSubrange(rope, ref, range: 2 ..< 722) + checkRemoveSubrange(rope, ref, range: 358 ..< 718) + checkRemoveSubrange(rope, ref, range: 12 ..< 732) + checkRemoveSubrange(rope, ref, range: 348 ..< 728) + checkRemoveSubrange(rope, ref, range: 63 ..< 783) + checkRemoveSubrange(rope, ref, range: 297 ..< 655) + } + + func test_removeSubrange_random() { + for iteration in 0 ..< 20 { + var rng = RepeatableRandomNumberGenerator(seed: iteration) + let c = 1000 + var rope = _Rope() + for i in 0 ..< c { + rope.append(Chunk(length: 2, value: i)) + } + var ref = (0 ..< c).flatMap { Array(repeating: $0, count: 2) } + + while !ref.isEmpty { + print(ref.count) + let i = (0 ..< ref.count).randomElement(using: &rng)! + let j = (i + 1 ... ref.count).randomElement(using: &rng)! + rope.removeSubrange(i ..< j, in: Chunk.Metric()) + ref.removeSubrange(i ..< j) + checkEqual(rope, ref) + } + } + } + +} +#endif diff --git a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme new file mode 100644 index 00000000..19a77614 --- /dev/null +++ b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From eabd9417991fee880a566951c223a0adcaf0832b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 1 Feb 2023 00:09:44 -0800 Subject: [PATCH 021/113] Add some operations taking subsequences --- .../BString/Basics/_BString+Builder.swift | 7 +- .../BString/Operations/_BString+Append.swift | 34 ++++- .../Operations/_BString+Initializers.swift | 31 +++- .../BString/Operations/_BString+Insert.swift | 19 +++ .../Operations/_BString+ReplaceSubrange.swift | 22 +++ .../BigString/BigString+CharacterView.swift | 24 +++- .../BigString+UnicodeScalarView.swift | 18 +++ .../Rope/Basics/_Rope+Builder.swift | 134 +++++++++--------- .../Rope/Operations/_Rope+Extract.swift | 84 +++++++++++ .../Operations/_Rope+RemoveSubrange.swift | 4 +- .../Utilities/Range Utilities.swift | 22 +++ Tests/RopeModuleTests/TestBigString.swift | 25 ++++ 12 files changed, 344 insertions(+), 80 deletions(-) create mode 100644 Sources/RopeModule/Rope/Operations/_Rope+Extract.swift create mode 100644 Sources/RopeModule/Utilities/Range Utilities.swift diff --git a/Sources/RopeModule/BString/Basics/_BString+Builder.swift b/Sources/RopeModule/BString/Basics/_BString+Builder.swift index 5a4fb631..a2a77e90 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Builder.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Builder.swift @@ -94,7 +94,12 @@ extension _BString.Builder { var state = _CharacterRecognizer() append(other.rope, state: &state) } - + + mutating func append(_ other: __owned _BString, in range: Range<_BString.Index>) { + let extract = _BString(other, in: range, state: &self.prefixEndState) + self.base.append(extract.rope) + } + mutating func append(_ other: __owned Rope, state: inout _CharacterRecognizer) { guard !other.isEmpty else { return } var other = _BString(rope: other) diff --git a/Sources/RopeModule/BString/Operations/_BString+Append.swift b/Sources/RopeModule/BString/Operations/_BString+Append.swift index 0806bb60..e22fcd56 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Append.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Append.swift @@ -66,21 +66,49 @@ extension _BString { _ = other.resyncBreaks(old: &old, new: &new) _append(other) } - + + mutating func append(contentsOf other: __owned _BString, in range: Range) { + guard !range._isEmptyUTF8 else { return } + guard !self.isEmpty else { + self = Self(other, in: range) + return + } + + var other = _BString(other, in: range) + let hint = other._firstUnicodeScalar + var old = _CharacterRecognizer() + var new = self._breakState(upTo: endIndex, nextScalarHint: hint).state + _ = other.rope.resyncBreaks(old: &old, new: &new) + _append(other.rope) + } + mutating func prepend(contentsOf other: __owned _BString) { guard !other.isEmpty else { return } guard !self.isEmpty else { self = other return } - let hint = self._firstUnicodeScalar var old = _CharacterRecognizer() var new = other._breakState(upTo: other.endIndex, nextScalarHint: hint).state _ = self.rope.resyncBreaks(old: &old, new: &new) - + _prepend(other.rope) } + + mutating func prepend(contentsOf other: __owned _BString, in range: Range) { + guard !range._isEmptyUTF8 else { return } + let extract = Self(other, in: range) + guard !self.isEmpty else { + self = extract + return + } + let hint = self._firstUnicodeScalar + var old = _CharacterRecognizer() + var new = extract._breakState(upTo: extract.endIndex, nextScalarHint: hint).state + _ = self.rope.resyncBreaks(old: &old, new: &new) + _prepend(extract.rope) + } } extension _BString { diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index 4c0060af..11453502 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -46,6 +46,33 @@ extension _BString { builder.append(piece) self = builder.finalize() } + + internal init( + _ other: Self, + in range: Range + ) { + self.rope = other.rope.extract( + from: range.lowerBound._utf8Offset, + to: range.upperBound._utf8Offset, + in: UTF8Metric()) + var old = other._breakState(upTo: range.lowerBound).state + var new = _CharacterRecognizer() + _ = self.rope.resyncBreaks(old: &old, new: &new) + } + + internal init( + _ other: Self, + in range: Range, + state: inout _CharacterRecognizer + ) { + self.rope = other.rope.extract( + from: range.lowerBound._utf8Offset, + to: range.upperBound._utf8Offset, + in: UTF8Metric()) + var old = other._breakState(upTo: range.lowerBound).state + var new = state + self.rope.resyncBreaksToEnd(old: &old, new: &new) + } } extension String { @@ -59,7 +86,7 @@ extension String { internal init(_from big: _BString, in range: Range<_BString.Index>) { self.init() - guard range.lowerBound._utf8Offset < range.upperBound._utf8Offset else { + guard range._isEmptyUTF8 else { // We can safely ignore UTF-16 offsets, as we're rounding down to scalar boundaries // anyway. return @@ -71,7 +98,7 @@ extension String { self += start.chunk.string[start.path.chunk ..< end.path.chunk] return } - + self += start.chunk.string[start.path.chunk...] var it = big.rope.makeIterator(from: start.path.rope) diff --git a/Sources/RopeModule/BString/Operations/_BString+Insert.swift b/Sources/RopeModule/BString/Operations/_BString+Insert.swift index e73045bb..d0fdffce 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Insert.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Insert.swift @@ -76,3 +76,22 @@ extension _BString { self = builder.finalize() } } + +extension _BString { + 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) + return + } + guard index > startIndex else { + self.prepend(contentsOf: other, in: range) + return + } + guard !range._isEmptyUTF8 else { return } + // FIXME: Fast path when `other` is tiny. + var builder = self.split(at: index) + builder.append(other, in: range) + self = builder.finalize() + } +} diff --git a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift index bafec9ee..f3af7655 100644 --- a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift +++ b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift @@ -33,6 +33,28 @@ extension _BString { self = builder.finalize() } + mutating func replaceSubrange( + _ targetRange: Range, + with newElements: _BString, + in sourceRange: Range + ) { + if sourceRange._isEmptyUTF8 { + removeSubrange(targetRange) + return + } + if targetRange._isEmptyUTF8 { + insert( + contentsOf: newElements, + in: sourceRange, + at: targetRange.lowerBound) + return + } + precondition(targetRange.upperBound <= endIndex, "Index out of bounds") + var builder = _split(removing: targetRange) + builder.append(newElements, in: sourceRange) + self = builder.finalize() + } + mutating func _split(removing range: Range) -> Builder { let lower = range.lowerBound._utf8Offset let upper = range.upperBound._utf8Offset diff --git a/Sources/RopeModule/BigString/BigString+CharacterView.swift b/Sources/RopeModule/BigString/BigString+CharacterView.swift index 48ab9e4f..50b5f61b 100644 --- a/Sources/RopeModule/BigString/BigString+CharacterView.swift +++ b/Sources/RopeModule/BigString/BigString+CharacterView.swift @@ -117,12 +117,6 @@ extension BigString: BidirectionalCollection { } } -extension Range where Bound == BigString.Index { - var _base: Range<_BString.Index> { - Range<_BString.Index>(uncheckedBounds: (lowerBound._value, upperBound._value)) - } -} - extension BigString: RangeReplaceableCollection { public mutating func replaceSubrange( _ subrange: Range, @@ -186,6 +180,12 @@ extension BigString: RangeReplaceableCollection { self._guts = elements._guts } + public init(_ elements: Self.SubSequence) { + let lower = elements.startIndex._value + let upper = elements.endIndex._value + self._guts = _BString(elements.base._guts, in: lower ..< upper) + } + public init(repeating repeatedValue: Character, count: Int) { self._guts = _BString(repeating: _BString(String(repeatedValue)), count: count) } @@ -226,6 +226,12 @@ extension BigString: RangeReplaceableCollection { _guts.append(contentsOf: newElements._guts) } + 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) + } + public mutating func insert(_ newElement: __owned Character, at i: Index) { _guts.insert(contentsOf: String(newElement), at: i._value) } @@ -254,6 +260,12 @@ extension BigString: RangeReplaceableCollection { _guts.insert(contentsOf: newElements._guts, at: i._value) } + 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) + } + @discardableResult public mutating func remove(at i: Index) -> Character { _guts.removeCharacter(at: i._value) diff --git a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift index 65a3bdcb..dbce1e65 100644 --- a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift @@ -196,6 +196,12 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { self._guts = elements._guts } + public init(_ elements: Self.SubSequence) { + let lower = elements.startIndex._value + let upper = elements.endIndex._value + self._guts = _BString(elements.base._guts, in: lower ..< upper) + } + public init(repeating scalar: Unicode.Scalar, count: Int) { self._guts = _BString(repeating: _BString(String(scalar)), count: count) } @@ -228,6 +234,12 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { _guts.append(contentsOf: newElements._guts) } + 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) + } + public mutating func insert(_ newElement: __owned Unicode.Scalar, at i: Index) { _guts.insert(contentsOf: String(newElement), at: i._value) } @@ -256,6 +268,12 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { _guts.insert(contentsOf: newElements._guts, at: i._value) } + 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) + } + @discardableResult public mutating func remove(at i: Index) -> Unicode.Scalar { _guts.removeUnicodeScalar(at: i._value) diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift index c376a503..bf5f2047 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift @@ -44,7 +44,7 @@ extension _Rope { var isPrefixEmpty: Bool { if prefix != nil { return false } - if let seedling = self.prefixLeaf, !seedling.isEmpty { return false } + if let leaf = self.prefixLeaf, !leaf.isEmpty { return false } return prefixTrees.isEmpty } @@ -58,8 +58,8 @@ extension _Rope { for sapling in prefixTrees { sum.add(sapling.summary) } - if let seedling = prefixLeaf { sum.add(seedling.summary) } - if let seed = prefix { sum.add(seed.summary) } + if let leaf = prefixLeaf { sum.add(leaf.summary) } + if let item = prefix { sum.add(item.summary) } return sum } @@ -75,8 +75,8 @@ extension _Rope { var lastPrefixItem: _Rope.Item { get { assert(!isPrefixEmpty) - if let prefix { return prefix } - if let prefixLeaf { return prefixLeaf.lastItem } + if let item = self.prefix { return item } + if let leaf = self.prefixLeaf { return leaf.lastItem } return prefixTrees.last!.root.lastItem } _modify { @@ -127,29 +127,29 @@ extension _Rope { guard prefixTrees[i].forEachWhile({ body($0, nil) }) else { return false } i += 1 } - if let seedling = self.prefixLeaf { - guard seedling.forEachWhile({ body($0, nil) }) else { return false } + if let leaf = self.prefixLeaf { + guard leaf.forEachWhile({ body($0, nil) }) else { return false } } - if let seed = self.prefix { - guard body(seed.value, nil) else { return false } + if let item = self.prefix { + guard body(item.value, nil) else { return false } } return true } - if let seedling = self.prefixLeaf { - let size = metric.size(of: seedling.summary) + if let leaf = self.prefixLeaf { + let size = metric.size(of: leaf.summary) if position < size { - guard seedling.forEachWhile(from: position, in: metric, body) else { return false } - if let seed = self.prefix { - guard body(seed.value, nil) else { return false } + guard leaf.forEachWhile(from: position, in: metric, body) else { return false } + if let item = self.prefix { + guard body(item.value, nil) else { return false } } return true } position -= size } - if let seed = self.prefix { - let i = metric.index(at: position, in: seed.value) - guard body(seed.value, i) else { return false} + if let item = self.prefix { + let i = metric.index(at: position, in: item.value) + guard body(item.value, i) else { return false} } return true } @@ -175,28 +175,28 @@ extension _Rope { mutating func append(_ item: __owned _Rope.Item) { guard !item.isEmpty else { return } - guard var seed = self.prefix._take() else { + guard var prefix = self.prefix._take() else { self.prefix = item return } var item = item - if seed.rebalance(nextNeighbor: &item) { - self.prefix = seed + if prefix.rebalance(nextNeighbor: &item) { + self.prefix = prefix return } - _append(seed) + _append(prefix) self.prefix = item } mutating func _append(_ item: __owned _Rope.Item) { assert(self.prefix == nil) assert(!item.isUndersized) - var seedling = self.prefixLeaf._take() ?? .createLeaf() - seedling._appendItem(item) - if seedling.isFull { - self._append(seedling) + var leaf = self.prefixLeaf._take() ?? .createLeaf() + leaf._appendItem(item) + if leaf.isFull { + self._append(leaf) } else { - self.prefixLeaf = seedling + self.prefixLeaf = leaf } invariantCheck() } @@ -214,19 +214,19 @@ extension _Rope { append(node.firstItem) return } - if let seed = self.prefix._take() { - if let spawn = node.prepend(seed) { + if let item = self.prefix._take() { + if let spawn = node.prepend(item) { append(node) append(spawn) return } } - if var seedling = self.prefixLeaf._take() { - if seedling.rebalance(nextNeighbor: &node), !seedling.isFull { - self.prefixLeaf = seedling + if var leaf = self.prefixLeaf._take() { + if leaf.rebalance(nextNeighbor: &node), !leaf.isFull { + self.prefixLeaf = leaf return } - self._append(seedling) + self._append(leaf) } if node.isFull { @@ -237,13 +237,13 @@ extension _Rope { return } - if var seed = self.prefix._take() { - if !seed.isUndersized || !node.firstItem.rebalance(prevNeighbor: &seed) { - self._append(seed) + if var prefix = self.prefix._take() { + if !prefix.isUndersized || !node.firstItem.rebalance(prevNeighbor: &prefix) { + self._append(prefix) } } - if let seedling = self.prefixLeaf._take() { - _append(seedling) + if let leaf = self.prefixLeaf._take() { + _append(leaf) } _append(node) } @@ -353,33 +353,33 @@ extension _Rope { if let suffixItem = self.suffix._take() { append(suffixItem) } - if var seed = self.prefix._take() { - if !seed.isUndersized { - _append(seed) + if var prefix = self.prefix._take() { + if !prefix.isUndersized { + _append(prefix) } else if !self.isPrefixEmpty { - if !self.lastPrefixItem.rebalance(nextNeighbor: &seed) { - _append(seed) + if !self.lastPrefixItem.rebalance(nextNeighbor: &prefix) { + _append(prefix) } } else if !self.isSuffixEmpty { - if !self.firstSuffixItem.rebalance(prevNeighbor: &seed) { - _append(seed) + if !self.firstSuffixItem.rebalance(prevNeighbor: &prefix) { + _append(prefix) } } else { // We only have the seed; allow undersized chunk - return Rope(root: .createLeaf(seed)) + return Rope(root: .createLeaf(prefix)) } } assert(self.prefix == nil && self.suffix == nil) - while let sapling = suffixTrees.popLast() { - append(sapling) + while let tree = suffixTrees.popLast() { + append(tree) } // Merge all saplings, the seedling and the seed into a single rope. - if let seed = self.prefix._take() { - _append(seed) + if let item = self.prefix._take() { + _append(item) } var rope = Rope(root: prefixLeaf._take()) - while let sapling = prefixTrees.popLast() { - rope.prepend(sapling) + while let tree = prefixTrees.popLast() { + rope.prepend(tree) } assert(prefixLeaf == nil && prefixTrees.isEmpty && suffixTrees.isEmpty) rope.invariantCheck() @@ -394,16 +394,16 @@ extension _Rope { sapling.invariantCheck() h = sapling.height } - if let seedling = self.prefixLeaf { - precondition(seedling.height == 0) - precondition(!seedling.isFull) - seedling.invariantCheck(depth: 0, height: 0) + if let leaf = self.prefixLeaf { + precondition(leaf.height == 0) + precondition(!leaf.isFull) + leaf.invariantCheck(depth: 0, height: 0) } h = 0 - for sapling in suffixTrees.reversed() { - precondition(sapling.height >= h) - sapling.invariantCheck() - h = sapling.height + for tree in suffixTrees.reversed() { + precondition(tree.height >= h) + tree.invariantCheck() + h = tree.height } #endif @@ -414,25 +414,25 @@ extension _Rope { print("Sapling \(i):") self.prefixTrees[i].dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") } - if let seedling = self.prefixLeaf { + if let leaf = self.prefixLeaf { print("Seedling:") - seedling.dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") + leaf.dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") } - if let seed = self.prefix { + if let item = self.prefix { print("Seed:") - print(" \(seed)") + print(" \(item)") } print("---") var i = 0 - if let suffix = self.suffix { + if let item = self.suffix { print("Suffix \(i):") i += 1 - print(" \(suffix)") + print(" \(item)") } - for suffix in self.suffixTrees.reversed() { + for tree in self.suffixTrees.reversed() { print("Suffix \(i)") i += 1 - suffix.dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") + tree.dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") } } } diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Extract.swift b/Sources/RopeModule/Rope/Operations/_Rope+Extract.swift new file mode 100644 index 00000000..495d8748 --- /dev/null +++ b/Sources/RopeModule/Rope/Operations/_Rope+Extract.swift @@ -0,0 +1,84 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + func extract(from start: Int, to end: Int, in metric: some _RopeMetric) -> Self { + if _root == nil { + precondition(start == 0 && end == 0, "Invalid range") + return Self() + } + var builder = Builder() + root.extract(from: start, to: end, in: metric, into: &builder) + return builder.finalize() + } +} + +extension _Rope.Node { + func extract( + from start: Int, + to end: Int, + in metric: some _RopeMetric, + into builder: inout _Rope.Builder + ) { + let size = metric.size(of: summary) + precondition(start >= 0 && start <= end && end <= size, "Range out of bounds") + + guard start != end else { return } + + if self.isLeaf { + self.readLeaf { + let l = $0.findSlot(at: start, in: metric, preferEnd: false) + let u = $0.findSlot(from: l, offsetBy: end - start, in: metric, preferEnd: true) + let c = $0.children + if l.slot == u.slot { + var item = c[l.slot] + let i = metric.index(at: l.remaining, in: item.value) + var item2 = item.split(at: i) + let j = metric.index( + at: u.remaining - metric.nonnegativeSize(of: item.summary), + in: item2.value) + _ = item2.split(at: j) + builder.append(item2) + return + } + assert(l.slot < u.slot) + var left = c[l.slot] + left = left.split(at: metric.index(at: l.remaining, in: left.value)) + builder.append(left) + for i in l.slot + 1 ..< u.slot { + builder.append(c[i]) + } + var right = c[u.slot] + _ = right.split(at: metric.index(at: u.remaining, in: right.value)) + builder.append(right) + } + return + } + + self.readInner { + let l = $0.findSlot(at: start, in: metric, preferEnd: false) + let u = $0.findSlot(from: l, offsetBy: end - start, in: metric, preferEnd: true) + let c = $0.children + if l.slot == u.slot { + c[l.slot].extract( + from: l.remaining, to: u.remaining, in: metric, into: &builder) + return + } + assert(l.slot < u.slot) + let lsize = metric.nonnegativeSize(of: c[l.slot].summary) + c[l.slot].extract(from: l.remaining, to: lsize, in: metric, into: &builder) + for i in l.slot + 1 ..< u.slot { + builder.append(c[i]) + } + c[u.slot].extract(from: 0, to: u.remaining, in: metric, into: &builder) + } + } +} diff --git a/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift b/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift index 47aabed5..32eccf76 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift @@ -43,7 +43,9 @@ extension _Rope { in metric: some _RopeMetric ) -> Builder { let size = metric.size(of: summary) - precondition(bounds.lowerBound >= 0 && bounds.upperBound <= size, "Position out of bounds") + precondition( + bounds.lowerBound >= 0 && bounds.upperBound <= size, + "Range out of bounds") guard !bounds.isEmpty else { return builder(splittingAt: bounds.lowerBound, in: metric) diff --git a/Sources/RopeModule/Utilities/Range Utilities.swift b/Sources/RopeModule/Utilities/Range Utilities.swift new file mode 100644 index 00000000..0088e25d --- /dev/null +++ b/Sources/RopeModule/Utilities/Range Utilities.swift @@ -0,0 +1,22 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension Range { + internal var _base: Range<_BString.Index> { + Range<_BString.Index>(uncheckedBounds: (lowerBound._value, upperBound._value)) + } +} + +extension Range<_BString.Index> { + internal var _isEmptyUTF8: Bool { + lowerBound._utf8Offset == upperBound._utf8Offset + } +} diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index 443f2d5d..d5502406 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -512,4 +512,29 @@ class TestBigString: XCTestCase { checkCharacterIndices(input, big) } } + + func test_init_from_substring() { + let flat = sampleString + let big = BigString(flat) + + let (indices1, indices2) = checkScalarIndices(flat, big) + + for i in randomStride(from: 0, to: indices1.count, by: 1000, seed: 0) { + let a1 = indices1[i] + let a2 = indices2[i] + for j in randomStride(from: i, to: indices1.count, by: 1000, seed: i) { + let b1 = indices1[j] + let b2 = indices2[j] + + let expected = String(flat[a1 ..< b1]) + let actual = BigString(big[a2 ..< b2]) + actual._invariantCheck() + XCTAssertEqual(String(big), flat) + checkUTF8Indices(expected, actual) + checkUTF16Indices(expected, actual) + checkScalarIndices(expected, actual) + checkCharacterIndices(expected, actual) + } + } + } } From 18aa309f758a889ab78a88debd9f6b9eab169267 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 3 Feb 2023 18:35:24 -0800 Subject: [PATCH 022/113] Generalize some _BString iterators --- .../BString/Basics/_BString+Contents.swift | 40 +++++ .../BString/Basics/_BString+Iterators.swift | 160 ++++++++++++++---- .../Rope/Conformances/_Rope+Collection.swift | 4 + .../Rope/Conformances/_Rope+Sequence.swift | 13 +- .../Utilities/String.Index+ABI.swift | 8 + Tests/RopeModuleTests/TestBString.swift | 56 ++++++ 6 files changed, 247 insertions(+), 34 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 3fd8c807..4c8523f2 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -69,6 +69,46 @@ extension _BString { } } +extension _BString { + // FIXME: See if we need direct implementations for these. + + func characterOffset(of index: Index) -> Int { + characterDistance(from: startIndex, to: index) + } + + func unicodeScalarOffset(of index: Index) -> Int { + unicodeScalarDistance(from: startIndex, to: index) + } + + func utf16Offset(of index: Index) -> Int { + utf16Distance(from: startIndex, to: index) + } + + func utf8Offset(of index: Index) -> Int { + utf8Distance(from: startIndex, to: index) + } +} + +extension _BString { + // FIXME: See if we need direct implementations for these. + + func characterIndex(at offset: Int) -> Index { + characterIndex(startIndex, offsetBy: offset) + } + + func unicodeScalarIndex(at offset: Int) -> Index { + unicodeScalarIndex(startIndex, offsetBy: offset) + } + + func utf16Index(at offset: Int) -> Index { + utf16Index(startIndex, offsetBy: offset) + } + + func utf8Index(at offset: Int) -> Index { + utf8Index(startIndex, offsetBy: offset) + } +} + extension _BString { func _path( _ i: Index, diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index fbbd6ef4..793e99f7 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -94,17 +94,26 @@ extension _BString.UTF16Iterator: IteratorProtocol { extension _BString { internal struct UnicodeScalarIterator { internal var _rope: Rope.Iterator - internal var _chunk: String.UnicodeScalarView.Iterator + // FIXME: Change to using String.UnicodeScalarView.Iterator once makeIterator(from:) is a thing + internal var _chunk: String.UnicodeScalarView + internal var _index: String.Index - internal init(_base: Rope.Iterator) { + internal init(_base: Rope.Iterator, _ chunk: Chunk, _ index: String.Index) { self._rope = _base - let str = self._rope.next()?.string ?? "" - self._chunk = str.unicodeScalars.makeIterator() + self._chunk = chunk.string.unicodeScalars + self._index = index } } internal func makeUnicodeScalarIterator() -> UnicodeScalarIterator { - UnicodeScalarIterator(_base: self.rope.makeIterator()) + makeUnicodeScalarIterator(from: startIndex) + } + + internal func makeUnicodeScalarIterator(from index: Index) -> UnicodeScalarIterator { + let (path, chunk) = self.path(to: index, preferEnd: false) + var base = self.rope.makeIterator(from: path.rope) + _ = base.next() + return UnicodeScalarIterator(_base: base, chunk, path.chunk) } } @@ -112,57 +121,146 @@ extension _BString.UnicodeScalarIterator: IteratorProtocol { internal typealias Element = Unicode.Scalar internal mutating func next() -> Unicode.Scalar? { - if let scalar = _chunk.next() { - return scalar + if _index == _chunk.endIndex { + guard let chunk = _rope.next() else { return nil } + _chunk = chunk.string.unicodeScalars + _index = _chunk.startIndex + assert(_index < _chunk.endIndex) } - guard let chunk = _rope.next() else { return nil } - _chunk = chunk.string.unicodeScalars.makeIterator() - return _chunk.next()! + let scalar = _chunk[_index] + _index = _chunk.index(after: _index) + return scalar } } extension _BString { internal struct CharacterIterator { internal var _base: _Rope.Iterator - internal var _str: Substring + internal var _index: String.Index + internal var _next: String.Index internal init(_base: _Rope.Iterator) { self._base = _base - if let chunk = self._base.next() { - assert(chunk.firstBreak == chunk.string.startIndex) - self._str = chunk.wholeCharacters - } else { - self._str = "" + guard !_base.isAtEnd else { + _index = "".startIndex + _next = "".endIndex + return } + let chunk = _base.current + assert(chunk.firstBreak == chunk.string.startIndex) + self._index = chunk.firstBreak + self._next = chunk.string[_index...].index(after: _index) + } + + internal init(_base: _Rope.Iterator, _ i: String.Index) { + self._base = _base + self._index = i + assert(i >= _base.current.firstBreak) + guard !_base.isAtEnd, i < _base.current.string.endIndex else { + self._next = i + return + } + self._next = _base.current.wholeCharacters.index(after: i) } } internal func makeCharacterIterator() -> CharacterIterator { CharacterIterator(_base: rope.makeIterator()) } + + internal func makeCharacterIterator(from index: Index) -> CharacterIterator { + if index == endIndex { + return CharacterIterator(_base: rope.makeIterator(from: rope.endIndex)) + } + let (path, _) = self.path(to: index, preferEnd: false) + let base = rope.makeIterator(from: path.rope) + return CharacterIterator(_base: base, path.chunk) + } } extension _BString.CharacterIterator: IteratorProtocol { internal typealias Element = Character - internal mutating func next() -> Character? { - guard !_str.isEmpty else { return nil } + internal var isAtEnd: Bool { + _index == _next + } - let j = _str.index(after: _str.startIndex) - var result = String(_str[.. (str: String, done: Bool) in + assert(_index >= chunk.firstBreak) + return (String(chunk.string[_index ..< _next]), _next < chunk.string.endIndex) } - while let next = _base.next() { - let firstBreak = next.firstBreak - result.append(contentsOf: next.string[.. Bool { + guard !isAtEnd else { return false } + let chunk = _base.current + if _next < chunk.string.endIndex { + _index = _next + _next = chunk.wholeCharacters.index(after: _next) + return true + } + while _base.stepForward() { + let chunk = _base.current + let i = chunk.firstBreak + if i < chunk.string.endIndex { + _index = i + _next = chunk.string[i...].index(after: i) + return true + } + } + return false + } + + mutating func stepBackward() -> Bool { + if !isAtEnd { + let chunk = _base.current + let i = chunk.firstBreak + if _index > i { + _next = _index + _index = chunk.string[i...].index(before: _index) + return true + } + } + while _base.stepBackward() { + let chunk = _base.current + if chunk.hasBreaks { + _next = chunk.string.endIndex + _index = chunk.lastBreak + return true + } + } + return false + } + + internal mutating func next() -> Character? { + guard !isAtEnd else { return nil } + let item = self.current + if !stepForward() { + _index = _next + } + return item + } +} + +extension _BString.CharacterIterator { + var index: _BString.Index { + let utf8Base = _base.rope.offset(of: _base.index, in: _BString.UTF8Metric()) + return _BString.Index(_utf8Offset: utf8Base + _index._utf8Offset) } } diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift index a6368fcb..33c48b28 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift @@ -157,6 +157,10 @@ extension _Rope { } return -root.distance(from: end, to: start, in: metric) } + + func offset(of index: Index, in metric: some _RopeMetric) -> Int { + distance(from: startIndex, to: index, in: metric) + } } extension _Rope.Node { diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift index 107a2e59..92056ce5 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift @@ -19,7 +19,7 @@ extension _Rope: Sequence { } struct Iterator: IteratorProtocol { - private let rope: _Rope + let rope: _Rope private(set) var index: Index private var leaf: Node? @@ -58,7 +58,7 @@ extension _Rope: Sequence { } return true } - + mutating func stepBackward() -> Bool { guard let leaf = self.leaf else { guard !rope.isEmpty else { return false } @@ -78,10 +78,17 @@ extension _Rope: Sequence { return true } + mutating func stepToEnd() { + leaf = nil + index = rope.endIndex + } + mutating func next() -> Element? { guard !isAtEnd else { return nil } let item = self.current - if !stepForward() { leaf = nil; index = rope.endIndex } + if !stepForward() { + stepToEnd() + } return item } } diff --git a/Sources/RopeModule/Utilities/String.Index+ABI.swift b/Sources/RopeModule/Utilities/String.Index+ABI.swift index 839e21a0..d007f542 100644 --- a/Sources/RopeModule/Utilities/String.Index+ABI.swift +++ b/Sources/RopeModule/Utilities/String.Index+ABI.swift @@ -88,7 +88,15 @@ extension String.Index { init(_utf8Offset: Int) { self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | Self.__utf8Bit) } + + init(_utf8Offset: Int, utf16Delta: Int) { + assert(utf16Delta >= 0 && utf16Delta <= 1) + let transcodedOffset: UInt64 = (utf16Delta != 0 ? 1 &<< 14 : 0) + self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | transcodedOffset | Self.__utf8Bit) + } +} +extension String.Index { @inline(__always) var _chunkData: UInt16 { UInt16(_rawBits &>> 14) diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 94e47457..cbe6606c 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -56,6 +56,20 @@ class TestBString: XCTestCase { _ big: _BString, file: StaticString = #file, line: UInt = #line ) -> (flat: [String.Index], big: [_BString.Index]) { + // Check iterators + var it1 = flat.makeIterator() + var it2 = big.makeCharacterIterator() + while true { + let a = it1.next() + let b = it2.next() + guard a == b else { + XCTAssertEqual(a, b) + break + } + if a == nil { break } + } + + // Check indices let indices1 = Array(flat.indices) + [flat.endIndex] let indices2 = Array( sequence(first: big.startIndex) { @@ -78,6 +92,20 @@ class TestBString: XCTestCase { _ big: _BString, file: StaticString = #file, line: UInt = #line ) -> (flat: [String.Index], big: [_BString.Index]) { + // Check iterators + var it1 = flat.unicodeScalars.makeIterator() + var it2 = big.makeUnicodeScalarIterator() + while true { + let a = it1.next() + let b = it2.next() + guard a == b else { + XCTAssertEqual(a, b) + break + } + if a == nil { break } + } + + // Check indices let indices1 = Array(flat.unicodeScalars.indices) + [flat.unicodeScalars.endIndex] let indices2 = Array( sequence(first: big.startIndex) { @@ -100,6 +128,20 @@ class TestBString: XCTestCase { _ big: _BString, file: StaticString = #file, line: UInt = #line ) -> (flat: [String.Index], big: [_BString.Index]) { + // Check iterators + var it1 = flat.utf8.makeIterator() + var it2 = big.makeUTF8Iterator() + while true { + let a = it1.next() + let b = it2.next() + guard a == b else { + XCTAssertEqual(a, b) + break + } + if a == nil { break } + } + + // Check indices let indices1 = Array(flat.utf8.indices) + [flat.utf8.endIndex] let indices2 = Array( sequence(first: big.startIndex) { @@ -122,6 +164,20 @@ class TestBString: XCTestCase { _ big: _BString, file: StaticString = #file, line: UInt = #line ) -> (flat: [String.Index], big: [_BString.Index]) { + // Check iterators + var it1 = flat.utf16.makeIterator() + var it2 = big.makeUTF16Iterator() + while true { + let a = it1.next() + let b = it2.next() + guard a == b else { + XCTAssertEqual(a, b) + break + } + if a == nil { break } + } + + // Check indices let indices1 = Array(flat.utf16.indices) + [flat.utf16.endIndex] let indices2 = Array( sequence(first: big.startIndex) { From 96aebb90b74791ea5d6b9377653d84c1e9ef226b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 3 Feb 2023 18:35:48 -0800 Subject: [PATCH 023/113] Fix initializing a String from a _BString slice --- .../RopeModule/BString/Operations/_BString+Initializers.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index 11453502..0f3d14a0 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -86,7 +86,7 @@ extension String { internal init(_from big: _BString, in range: Range<_BString.Index>) { self.init() - guard range._isEmptyUTF8 else { + guard !range._isEmptyUTF8 else { // We can safely ignore UTF-16 offsets, as we're rounding down to scalar boundaries // anyway. return From 283d4071bcf1705850b43ab001265673682abe8f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 9 Feb 2023 14:33:36 -0800 Subject: [PATCH 024/113] Assorted bug fixes and refinements --- .../BString/Basics/_BString+Contents.swift | 17 ++++-- .../BString/Basics/_BString+Iterators.swift | 58 +++++++++++++++++-- .../Conformances/_BString+Comparisons.swift | 32 ++++++++++ .../Operations/Range+_BString.swift} | 6 -- .../Operations/_BString+Initializers.swift | 16 ++++- Sources/RopeModule/BigString/BigString.swift | 6 ++ .../Utilities/String.Index+ABI.swift | 46 +++++++-------- 7 files changed, 141 insertions(+), 40 deletions(-) rename Sources/RopeModule/{Utilities/Range Utilities.swift => BString/Operations/Range+_BString.swift} (76%) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 4c8523f2..206e68f6 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -36,10 +36,9 @@ extension _BString { to end: Index, in metric: some _StringMetric ) -> Int { - guard !isEmpty else { - precondition(start == end && start == endIndex, "Invalid index") - return 0 - } + precondition(start <= endIndex && end <= endIndex, "Invalid index") + guard start != end else { return 0 } + assert(!isEmpty) let a = path(to: Swift.min(start, end), preferEnd: false) let b = path(to: Swift.max(start, end), preferEnd: true) if a.path.rope == b.path.rope { @@ -320,12 +319,22 @@ extension _BString { return chunk.string.utf8[path.chunk] } + subscript(utf8 offset: Int) -> UInt8 { + let (path, chunk) = _path(startIndex, offsetBy: offset, in: UTF8Metric()) + return chunk.string.utf8[path.chunk] + } + subscript(utf16 index: Index) -> UInt16 { precondition(index < endIndex, "Index out of bounds") let (path, chunk) = path(to: index, preferEnd: false) return chunk.string.utf16[path.chunk] } + subscript(utf16 offset: Int) -> UInt16 { + let (path, chunk) = _path(startIndex, offsetBy: offset, in: UTF16Metric()) + return chunk.string.utf16[path.chunk] + } + subscript(character index: Index) -> Character { precondition(index < endIndex, "Index out of bounds") let (path, chunk) = path(to: index, preferEnd: false) diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index 793e99f7..ba3fa117 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -135,11 +135,13 @@ extension _BString.UnicodeScalarIterator: IteratorProtocol { extension _BString { internal struct CharacterIterator { + internal var _utf8BaseOffset: Int internal var _base: _Rope.Iterator internal var _index: String.Index internal var _next: String.Index - internal init(_base: _Rope.Iterator) { + internal init(_base: _Rope.Iterator, utf8BaseOffset: Int) { + self._utf8BaseOffset = utf8BaseOffset self._base = _base guard !_base.isAtEnd else { _index = "".startIndex @@ -152,7 +154,8 @@ extension _BString { self._next = chunk.string[_index...].index(after: _index) } - internal init(_base: _Rope.Iterator, _ i: String.Index) { + internal init(_base: _Rope.Iterator, utf8BaseOffset: Int, _ i: String.Index) { + self._utf8BaseOffset = utf8BaseOffset self._base = _base self._index = i assert(i >= _base.current.firstBreak) @@ -165,16 +168,21 @@ extension _BString { } internal func makeCharacterIterator() -> CharacterIterator { - CharacterIterator(_base: rope.makeIterator()) + CharacterIterator(_base: rope.makeIterator(), utf8BaseOffset: 0) } internal func makeCharacterIterator(from index: Index) -> CharacterIterator { if index == endIndex { - return CharacterIterator(_base: rope.makeIterator(from: rope.endIndex)) + return CharacterIterator( + _base: rope.makeIterator(from: rope.endIndex), + utf8BaseOffset: index._utf8Offset) } let (path, _) = self.path(to: index, preferEnd: false) let base = rope.makeIterator(from: path.rope) - return CharacterIterator(_base: base, path.chunk) + return CharacterIterator( + _base: base, + utf8BaseOffset: index._utf8Offset - path.chunk._utf8Offset, + path.chunk) } } @@ -215,7 +223,10 @@ extension _BString.CharacterIterator: IteratorProtocol { _next = chunk.wholeCharacters.index(after: _next) return true } - while _base.stepForward() { + while true { + let c = _base.current.utf8Count + guard _base.stepForward() else { break } + _utf8BaseOffset += c let chunk = _base.current let i = chunk.firstBreak if i < chunk.string.endIndex { @@ -239,6 +250,7 @@ extension _BString.CharacterIterator: IteratorProtocol { } while _base.stepBackward() { let chunk = _base.current + _utf8BaseOffset -= chunk.utf8Count if chunk.hasBreaks { _next = chunk.string.endIndex _index = chunk.lastBreak @@ -259,8 +271,42 @@ extension _BString.CharacterIterator: IteratorProtocol { } extension _BString.CharacterIterator { + // The UTF-8 offset of the current position, from the start of the string. + var utf8Offset: Int { + _utf8BaseOffset + _index._utf8Offset + } + + /// The UTF-8 offset range of the current character, measured from the start of the string. + var utf8Range: Range { + assert(!isAtEnd) + let start = utf8Offset + var end = _utf8BaseOffset + if _next < _base.current.string.endIndex { + end += _next._utf8Offset + return Range(uncheckedBounds: (start, end)) + } + var it = _base + while true { + end += it.current.utf8Count + guard it.stepForward() else { break } + let chunk = it.current + let i = chunk.firstBreak + if i < chunk.string.endIndex { + end += i._utf8Offset + break + } + } + return Range(uncheckedBounds: (start, end)) + } + var index: _BString.Index { let utf8Base = _base.rope.offset(of: _base.index, in: _BString.UTF8Metric()) return _BString.Index(_utf8Offset: utf8Base + _index._utf8Offset) } + + func isBelow(_ path: _BString.Path) -> Bool { + if self._base.index < path.rope { return true } + guard self._base.index == path.rope else { return false } + return self._index < path.chunk + } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift index 8b423e7d..e65b2bf9 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift @@ -37,6 +37,38 @@ extension _BString { return true } + internal static func characterIsEqual( + _ left: Self, + in leftRange: Range, + to right: Self, + in rightRange: Range + ) -> Bool { + // FIXME: Implement properly normalized comparisons & hashing. + // This is somewhat tricky as we shouldn't just normalize individual pieces of the string + // split up on random Character boundaries -- Unicode does not promise that + // norm(a + c) == norm(a) + norm(b) in this case. + // To do this properly, we'll probably need to expose new stdlib entry points. :-/ + if left.isIdentical(to: right), leftRange == rightRange { return true } + + // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. + var it1 = left.makeCharacterIterator(from: leftRange.lowerBound) + var it2 = right.makeCharacterIterator(from: rightRange.upperBound) + + let leftEnd = left.path(to: leftRange.upperBound, preferEnd: true).path + let rightEnd = right.path(to: rightRange.upperBound, preferEnd: true).path + + var a: Character? = nil + var b: Character? = nil + while it1.isBelow(leftEnd), it2.isBelow(rightEnd) { + a = it1.next() + b = it2.next() + assert(a != nil && b != nil) + guard a == b else { return false } + } + return !it1.isBelow(leftEnd) && !it2.isBelow(rightEnd) + } + + internal func characterIsLess(than other: Self) -> Bool { // FIXME: Implement properly normalized comparisons & hashing. // This is somewhat tricky as we shouldn't just normalize individual pieces of the string diff --git a/Sources/RopeModule/Utilities/Range Utilities.swift b/Sources/RopeModule/BString/Operations/Range+_BString.swift similarity index 76% rename from Sources/RopeModule/Utilities/Range Utilities.swift rename to Sources/RopeModule/BString/Operations/Range+_BString.swift index 0088e25d..6c9d1f0b 100644 --- a/Sources/RopeModule/Utilities/Range Utilities.swift +++ b/Sources/RopeModule/BString/Operations/Range+_BString.swift @@ -9,12 +9,6 @@ // //===----------------------------------------------------------------------===// -extension Range { - internal var _base: Range<_BString.Index> { - Range<_BString.Index>(uncheckedBounds: (lowerBound._value, upperBound._value)) - } -} - extension Range<_BString.Index> { internal var _isEmptyUTF8: Bool { lowerBound._utf8Offset == upperBound._utf8Offset diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index 0f3d14a0..5b2c86af 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -77,6 +77,14 @@ extension _BString { extension String { internal init(_from big: _BString) { + guard !big.isEmpty else { + self.init() + return + } + if big.rope.isSingleton { + self = big.rope[big.rope.startIndex].string + return + } self.init() self.reserveCapacity(big.utf8Count) for chunk in big.rope { @@ -86,11 +94,17 @@ extension String { internal init(_from big: _BString, in range: Range<_BString.Index>) { self.init() - guard !range._isEmptyUTF8 else { + let estimatedUTF8Size = range.upperBound._utf8Offset - range.lowerBound._utf8Offset + guard estimatedUTF8Size > 0 else { // We can safely ignore UTF-16 offsets, as we're rounding down to scalar boundaries // anyway. return } + // Note: if the range isn't scalar aligned, then this may be slightly under- or overestimating + // the actual size of the result. (Underestimations can be problematic due to String's + // exponential resizing. If those become an issue, consider adding +3 here.) + self.reserveCapacity(estimatedUTF8Size) + let start = big.path(to: range.lowerBound, preferEnd: false) let end = big.path(to: range.upperBound, preferEnd: true) diff --git a/Sources/RopeModule/BigString/BigString.swift b/Sources/RopeModule/BigString/BigString.swift index dcc37cd8..0d44c07b 100644 --- a/Sources/RopeModule/BigString/BigString.swift +++ b/Sources/RopeModule/BigString/BigString.swift @@ -64,3 +64,9 @@ extension String.UnicodeScalarView { self = String().unicodeScalars } } + +extension Range { + internal var _base: Range<_BString.Index> { + Range<_BString.Index>(uncheckedBounds: (lowerBound._value, upperBound._value)) + } +} diff --git a/Sources/RopeModule/Utilities/String.Index+ABI.swift b/Sources/RopeModule/Utilities/String.Index+ABI.swift index d007f542..e8505f4c 100644 --- a/Sources/RopeModule/Utilities/String.Index+ABI.swift +++ b/Sources/RopeModule/Utilities/String.Index+ABI.swift @@ -12,54 +12,54 @@ // Bits of String.Index that are ABI but aren't exposed by public API. extension String.Index { @inline(__always) - var _rawBits: UInt64 { + var _abi_rawBits: UInt64 { unsafeBitCast(self, to: UInt64.self) } @inline(__always) - var _encodedOffset: Int { - Int(truncatingIfNeeded: _rawBits &>> 16) + var _abi_encodedOffset: Int { + Int(truncatingIfNeeded: _abi_rawBits &>> 16) } @inline(__always) - var _transcodedOffset: Int { - Int(truncatingIfNeeded: (_rawBits &>> 14) & 0x3) + var _abi_transcodedOffset: Int { + Int(truncatingIfNeeded: (_abi_rawBits &>> 14) & 0x3) } @inline(__always) - static var __scalarAlignmentBit: UInt64 { 0x1 } - + static var _abi_scalarAlignmentBit: UInt64 { 0x1 } + @inline(__always) - static var __characterAlignmentBit: UInt64 { 0x2 } - + static var _abi_characterAlignmentBit: UInt64 { 0x2 } + @inline(__always) - static var __utf8Bit: UInt64 { 0x4 } - + static var _abi_utf8Bit: UInt64 { 0x4 } + @inline(__always) - static var __utf16Bit: UInt64 { 0x8 } - + static var _abi_utf16Bit: UInt64 { 0x8 } + @inline(__always) var _encodingBits: UInt64 { - _rawBits & (Self.__utf8Bit | Self.__utf16Bit) + _abi_rawBits & (Self._abi_utf8Bit | Self._abi_utf16Bit) } @inline(__always) var _canBeUTF8: Bool { // The only way an index cannot be UTF-8 is it has only the UTF-16 flag set. - _encodingBits != Self.__utf16Bit + _encodingBits != Self._abi_utf16Bit } var _isScalarAligned: Bool { - 0 != _rawBits & Self.__scalarAlignmentBit + 0 != _abi_rawBits & Self._abi_scalarAlignmentBit } var _isCharacterAligned: Bool { - 0 != _rawBits & Self.__characterAlignmentBit + 0 != _abi_rawBits & Self._abi_characterAlignmentBit } var _characterAligned: String.Index { - let r = _rawBits | Self.__characterAlignmentBit | Self.__scalarAlignmentBit + let r = _abi_rawBits | Self._abi_characterAlignmentBit | Self._abi_scalarAlignmentBit return unsafeBitCast(r, to: String.Index.self) } } @@ -68,13 +68,13 @@ extension String.Index { @inline(__always) var _utf8Offset: Int { assert(_canBeUTF8) - return _encodedOffset + return _abi_encodedOffset } @inline(__always) var _utf16Delta: Int { assert(_canBeUTF8) - let r = _transcodedOffset + let r = _abi_transcodedOffset assert(r <= 1) return r } @@ -86,20 +86,20 @@ extension String.Index { @inline(__always) init(_utf8Offset: Int) { - self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | Self.__utf8Bit) + self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | Self._abi_utf8Bit) } init(_utf8Offset: Int, utf16Delta: Int) { assert(utf16Delta >= 0 && utf16Delta <= 1) let transcodedOffset: UInt64 = (utf16Delta != 0 ? 1 &<< 14 : 0) - self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | transcodedOffset | Self.__utf8Bit) + self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | transcodedOffset | Self._abi_utf8Bit) } } extension String.Index { @inline(__always) var _chunkData: UInt16 { - UInt16(_rawBits &>> 14) + UInt16(_abi_rawBits &>> 14) } @inline(__always) From 8c8cb5622bf62576a4fb435bddb98c363cfa1f1d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 9 Feb 2023 14:35:27 -0800 Subject: [PATCH 025/113] Restrict BIgString and _BString to Swift 5.8 and macOS 13.3 /iOS 16.4/etc These types heavily rely on stdlib functionality that ships in Swift 5.8; they do not run correctly on earlier releases. --- .../BString/Basics/_BString+Builder.swift | 8 + .../BString/Basics/_BString+Contents.swift | 14 ++ .../BString/Basics/_BString+Debugging.swift | 5 + .../BString/Basics/_BString+Index.swift | 11 ++ .../BString/Basics/_BString+Ingester.swift | 8 + .../BString/Basics/_BString+Invariants.swift | 5 + .../BString/Basics/_BString+Iterators.swift | 15 ++ .../BString/Basics/_BString+Metrics.swift | 6 + .../BString/Basics/_BString+Path.swift | 8 + .../BString/Basics/_BString+Summary.swift | 7 + .../RopeModule/BString/Basics/_BString.swift | 10 ++ .../_BString+Chunk+Append and Insert.swift | 6 + .../BString/Chunk/_BString+Chunk+Breaks.swift | 5 + .../Chunk/_BString+Chunk+CordElement.swift | 6 + .../BString/Chunk/_BString+Chunk+Counts.swift | 6 + .../Chunk/_BString+Chunk+Description.swift | 5 + ...BString+Chunk+Indexing by Characters.swift | 6 + .../_BString+Chunk+Indexing by UTF16.swift | 5 + .../Chunk/_BString+Chunk+Splitting.swift | 5 + .../BString/Chunk/_BString+Chunk.swift | 11 +- .../Conformances/_BString+Comparisons.swift | 7 + .../Conformances/_BString+Conformances.swift | 6 + .../Conformances/_BString+Hashing.swift | 5 + .../BString/Operations/Range+_BString.swift | 5 + .../BString/Operations/_BString+Append.swift | 8 + .../Operations/_BString+Initializers.swift | 7 + .../BString/Operations/_BString+Insert.swift | 7 + .../Operations/_BString+Managing Breaks.swift | 8 + .../Operations/_BString+RemoveSubrange.swift | 6 + .../Operations/_BString+ReplaceSubrange.swift | 4 + .../BString/Operations/_BString+Split.swift | 5 + .../BigString/BigString+CharacterView.swift | 15 ++ .../BigString/BigString+UTF16View.swift | 12 ++ .../BigString/BigString+UTF8View.swift | 12 ++ .../BigString+UnicodeScalarView.swift | 14 ++ Sources/RopeModule/BigString/BigString.swift | 17 ++ .../Utilities/String Utilities.swift | 3 + .../Utilities/_CharacterRecognizer.swift | 159 ++---------------- Tests/RopeModuleTests/TestBigString.swift | 3 + 39 files changed, 313 insertions(+), 142 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Builder.swift b/Sources/RopeModule/BString/Basics/_BString+Builder.swift index a2a77e90..fd33db18 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Builder.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Builder.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { struct Builder { typealias Chunk = _BString.Chunk @@ -37,6 +40,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _Rope<_BString.Chunk>.Builder { func breakState() -> _CharacterRecognizer { let chars = self.prefixSummary.characters @@ -55,6 +59,7 @@ extension _Rope<_BString.Chunk>.Builder { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Builder { mutating func append(_ str: __owned some StringProtocol) { append(Substring(str)) @@ -126,6 +131,7 @@ extension _BString.Builder { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Builder { mutating func finalize() -> _BString { // Resync breaks in suffix. @@ -139,3 +145,5 @@ extension _BString.Builder { return string } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 206e68f6..3601488b 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { var isEmpty: Bool { rope.summary.isZero @@ -23,6 +26,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { var characterCount: Int { rope.summary.characters } var unicodeScalarCount: Int { rope.summary.unicodeScalars } @@ -30,6 +34,7 @@ extension _BString { var utf8Count: Int { rope.summary.utf8 } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func distance( from start: Index, @@ -68,6 +73,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { // FIXME: See if we need direct implementations for these. @@ -88,6 +94,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { // FIXME: See if we need direct implementations for these. @@ -108,6 +115,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func _path( _ i: Index, @@ -193,6 +201,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func characterIndex(after i: Index) -> Index { index(i, offsetBy: 1, in: CharacterMetric()) @@ -213,6 +222,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func characterIndex(before i: Index) -> Index { index(i, offsetBy: -1, in: CharacterMetric()) @@ -233,6 +243,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func characterIndex(roundingDown i: Index) -> Index { let offset = i._utf8Offset - 1 @@ -287,6 +298,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func _character( at start: Path, base: Index?, in chunk: Chunk @@ -359,3 +371,5 @@ extension _BString { return chunk.string.unicodeScalars[path.chunk] } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Debugging.swift b/Sources/RopeModule/BString/Basics/_BString+Debugging.swift index bd31783d..b53bd0af 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Debugging.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Debugging.swift @@ -9,8 +9,13 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func dump(heightLimit: Int = .max) { rope.dump(heightLimit: heightLimit) } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift index 21e00106..ef649833 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct Index { // The layout is similar to (and somewhat compatible with) String.Index. @@ -26,6 +29,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index { @inline(__always) internal var _orderingValue: UInt64 { @@ -33,24 +37,28 @@ extension _BString.Index { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index: Equatable { internal static func ==(left: Self, right: Self) -> Bool { left._orderingValue == right._orderingValue } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index: Comparable { internal static func <(left: Self, right: Self) -> Bool { left._orderingValue < right._orderingValue } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index: Hashable { internal func hash(into hasher: inout Hasher) { hasher.combine(_orderingValue) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index: CustomStringConvertible { internal var description: String { let offset = _utf16Delta == 0 ? "" : "+\(_utf16Delta)" @@ -58,6 +66,7 @@ extension _BString.Index: CustomStringConvertible { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index { @inline(__always) internal static func _bitsForUTF8Offset(_ utf8Offset: Int) -> UInt64 { @@ -94,3 +103,5 @@ extension _BString.Index { Self(_utf8Offset: _utf8Offset + delta) } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Ingester.swift b/Sources/RopeModule/BString/Basics/_BString+Ingester.swift index 38f2faf4..2bb9c36b 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Ingester.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Ingester.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func ingester( forInserting input: __owned Substring, @@ -21,6 +24,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { struct Ingester { typealias Chunk = _BString.Chunk @@ -133,6 +137,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String { func _nextSlice( after i: Index, @@ -148,6 +153,7 @@ extension String { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { init(_ string: String) { guard !string.isEmpty else { self.init(); return } @@ -157,3 +163,5 @@ extension _BString.Chunk { assert(ingester.isAtEnd) } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Invariants.swift b/Sources/RopeModule/BString/Basics/_BString+Invariants.swift index 0360d819..ec88d4d3 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Invariants.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Invariants.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func invariantCheck() { #if DEBUG @@ -32,3 +35,5 @@ extension _BString { #endif } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index ba3fa117..ab0863e1 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { struct ChunkIterator { var base: Rope.Iterator @@ -23,6 +26,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.ChunkIterator: IteratorProtocol { typealias Element = String @@ -31,6 +35,7 @@ extension _BString.ChunkIterator: IteratorProtocol { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct UTF8Iterator { internal var _rope: Rope.Iterator @@ -48,6 +53,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF8Iterator: IteratorProtocol { internal typealias Element = UInt8 @@ -61,6 +67,7 @@ extension _BString.UTF8Iterator: IteratorProtocol { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct UTF16Iterator { internal var _rope: Rope.Iterator @@ -78,6 +85,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF16Iterator: IteratorProtocol { internal typealias Element = UInt16 @@ -91,6 +99,7 @@ extension _BString.UTF16Iterator: IteratorProtocol { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct UnicodeScalarIterator { internal var _rope: Rope.Iterator @@ -117,6 +126,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarIterator: IteratorProtocol { internal typealias Element = Unicode.Scalar @@ -133,6 +143,7 @@ extension _BString.UnicodeScalarIterator: IteratorProtocol { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct CharacterIterator { internal var _utf8BaseOffset: Int @@ -186,6 +197,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.CharacterIterator: IteratorProtocol { internal typealias Element = Character @@ -270,6 +282,7 @@ extension _BString.CharacterIterator: IteratorProtocol { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.CharacterIterator { // The UTF-8 offset of the current position, from the start of the string. var utf8Offset: Int { @@ -310,3 +323,5 @@ extension _BString.CharacterIterator { return self._index < path.chunk } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Metrics.swift b/Sources/RopeModule/BString/Basics/_BString+Metrics.swift index c7561584..4e0761df 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Metrics.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Metrics.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) internal protocol _StringMetric: _RopeMetric where Element == _BString.Chunk { func distance( from start: String.Index, @@ -23,6 +26,7 @@ internal protocol _StringMetric: _RopeMetric where Element == _BString.Chunk { ) -> (found: Bool, forward: Bool) } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct CharacterMetric: _StringMetric { typealias Element = _BString.Chunk @@ -201,3 +205,5 @@ extension _BString { } } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Path.swift b/Sources/RopeModule/BString/Basics/_BString+Path.swift index abcb3730..b32cd629 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Path.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Path.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { struct Path { var rope: Rope.Index @@ -42,12 +45,14 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Path: CustomStringConvertible { var description: String { "\(rope).\(chunk._description)" } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func path( to i: Index, @@ -62,6 +67,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func baseIndex( with index: Index, @@ -83,3 +89,5 @@ extension _BString { return index(base: base, offsetBy: path.chunk) } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Summary.swift b/Sources/RopeModule/BString/Basics/_BString+Summary.swift index 8720894d..ce138a82 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Summary.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Summary.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { struct Summary { // FIXME: We only need 48 * 3 = 192 bits to represent a nonnegative value; pack these better @@ -34,12 +37,14 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Summary: CustomStringConvertible { var description: String { "❨\(utf8)⋅\(utf16)⋅\(unicodeScalars)⋅\(characters)❩" } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Summary: _RopeSummary { @inline(__always) static var maxNodeSize: Int { 10 } @@ -67,3 +72,5 @@ extension _BString.Summary: _RopeSummary { utf8 -= other.utf8 } } + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString.swift b/Sources/RopeModule/BString/Basics/_BString.swift index 056d6de0..cda99f64 100644 --- a/Sources/RopeModule/BString/Basics/_BString.swift +++ b/Sources/RopeModule/BString/Basics/_BString.swift @@ -9,7 +9,10 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + /// The core of a B-tree based String implementation. +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) internal struct _BString: Sendable { typealias Rope = _Rope @@ -23,3 +26,10 @@ internal struct _BString: Sendable { self.rope = rope } } + +#else + +@available(*, unavailable, message: "_BString requires Swift 5.8") +internal struct _BString: Sendable {} + +#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift index 5aa80c8b..b0d7016b 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { mutating func append(_ other: __owned Self) { self._append(other.string[...], other.counts) @@ -63,6 +66,7 @@ extension _BString.Chunk { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { mutating func _insert( _ slice: Slice, @@ -166,3 +170,5 @@ extension _BString.Chunk { return .split(spawn: spawn, endStates: (sum - offset, old, new)) } } + +#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift index d184f3a6..fe85a115 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { @inline(__always) var hasBreaks: Bool { counts.hasBreaks } @@ -37,6 +40,7 @@ extension _BString.Chunk { var wholeCharacters: Substring { string[firstBreak...] } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { var immediateLastBreakState: _CharacterRecognizer? { guard hasBreaks else { return nil } @@ -64,3 +68,4 @@ extension _BString.Chunk { } } +#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift index 58fae24e..bd009ef5 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk: _RopeElement { typealias Summary = _BString.Summary typealias Index = String.Index @@ -112,6 +115,7 @@ extension _BString.Chunk: _RopeElement { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { static func _redistributeData( _ left: inout Self, @@ -149,3 +153,5 @@ extension _BString.Chunk { left = Self(left.string[..=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { struct Counts: Equatable { /// The number of UTF-8 code units within this chunk. @@ -96,6 +99,7 @@ extension _BString.Chunk { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk.Counts { var characters: Int { get { Int(_characters) } @@ -121,6 +125,7 @@ extension _BString.Chunk.Counts { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk.Counts { mutating func append(_ other: Self) { assert(hasSpaceToMerge(other)) @@ -144,3 +149,4 @@ extension _BString.Chunk.Counts { } } +#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift index 89ba9ec4..f97d1c3c 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk: CustomStringConvertible { var description: String { let counts = """ @@ -65,3 +68,5 @@ extension _BString.Chunk: CustomStringConvertible { return result } } + +#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift index a7a59264..f97e128c 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift @@ -9,12 +9,16 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension UInt8 { /// Returns true if this is a leading code unit in the UTF-8 encoding of a Unicode scalar that /// is outside the BMP. var _isUTF8NonBMPLeadingCodeUnit: Bool { self >= 0b11110000 } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { func characterDistance(from start: String.Index, to end: String.Index) -> Int { let firstBreak = self.firstBreak @@ -104,3 +108,5 @@ extension _BString.Chunk { return (false, false) } } + +#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift index a5a1f509..45473005 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { /// UTF-16 index lookup. func index(at utf8Offset: Int, utf16Delta: Int) -> String.Index { @@ -24,3 +27,5 @@ extension _BString.Chunk { return index } } + +#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift index d4af04a9..73898e4e 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { func splitCounts(at i: String.Index) -> (left: Counts, right: Counts) { precondition(i <= string.endIndex) @@ -142,3 +145,5 @@ extension _BString.Chunk { return result } } + +#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift index f318912d..09c25757 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { struct Chunk { typealias Slice = (string: Substring, characters: Int, prefix: Int, suffix: Int) @@ -43,6 +46,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { @inline(__always) static var maxUTF8Count: Int { 255 } @@ -54,6 +58,7 @@ extension _BString.Chunk { static var maxSlicingError: Int { 3 } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { @inline(__always) mutating func take() -> Self { @@ -70,7 +75,7 @@ extension _BString.Chunk { } } - +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { @inline(__always) var characterCount: Int { counts.characters } @@ -94,6 +99,7 @@ extension _BString.Chunk { var lastScalar: UnicodeScalar { string.unicodeScalars.last! } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { var availableSpace: Int { Swift.max(0, Self.maxUTF8Count - utf8Count) } @@ -103,6 +109,7 @@ extension _BString.Chunk { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { func hasSpaceToMerge(_ other: some StringProtocol) -> Bool { utf8Count + other.utf8.count <= Self.maxUTF8Count @@ -112,3 +119,5 @@ extension _BString.Chunk { utf8Count + other.utf8Count <= Self.maxUTF8Count } } + +#endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift index e65b2bf9..4fac1847 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift @@ -9,12 +9,16 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func isIdentical(to other: Self) -> Bool { self.rope.isIdentical(to: other.rope) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal func characterIsEqual(to other: Self) -> Bool { // FIXME: Implement properly normalized comparisons & hashing. @@ -93,6 +97,7 @@ extension _BString { } } +@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 equal to `right`. @@ -183,3 +188,5 @@ extension _BString { } } } + +#endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+Conformances.swift b/Sources/RopeModule/BString/Conformances/_BString+Conformances.swift index fd6c0093..aa069437 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Conformances.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Conformances.swift @@ -9,14 +9,20 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: ExpressibleByStringLiteral { internal init(stringLiteral value: String) { self.init(value) } } +@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 ceede27f..81192eae 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal func hashCharacters(into hasher: inout Hasher) { // FIXME: Implement properly normalized comparisons & hashing. @@ -35,3 +38,5 @@ extension _BString { } } } + +#endif diff --git a/Sources/RopeModule/BString/Operations/Range+_BString.swift b/Sources/RopeModule/BString/Operations/Range+_BString.swift index 6c9d1f0b..621458d9 100644 --- a/Sources/RopeModule/BString/Operations/Range+_BString.swift +++ b/Sources/RopeModule/BString/Operations/Range+_BString.swift @@ -9,8 +9,13 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension Range<_BString.Index> { internal var _isEmptyUTF8: Bool { lowerBound._utf8Offset == upperBound._utf8Offset } } + +#endif diff --git a/Sources/RopeModule/BString/Operations/_BString+Append.swift b/Sources/RopeModule/BString/Operations/_BString+Append.swift index e22fcd56..8ad1e8ad 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Append.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Append.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@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)) @@ -46,6 +49,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { var _firstUnicodeScalar: Unicode.Scalar { assert(!isEmpty) @@ -111,12 +115,14 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { var isUndersized: Bool { utf8Count < Chunk.minUTF8Count } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { /// Note: This assumes `other` already has the correct break positions. mutating func _append(_ other: __owned Chunk) { @@ -197,3 +203,5 @@ extension _BString { self.rope = Rope.join(other, self.rope) } } + +#endif diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index 5b2c86af..7e16118a 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal init(_ input: some StringProtocol) { var builder = Rope.Builder() @@ -75,6 +78,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String { internal init(_from big: _BString) { guard !big.isEmpty else { @@ -123,6 +127,7 @@ 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") @@ -146,3 +151,5 @@ extension _BString { } } } + +#endif diff --git a/Sources/RopeModule/BString/Operations/_BString+Insert.swift b/Sources/RopeModule/BString/Operations/_BString+Insert.swift index d0fdffce..707a4286 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Insert.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Insert.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@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) @@ -54,6 +57,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) { guard index < endIndex else { @@ -77,6 +81,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, in range: Range, at index: Index) { guard index < endIndex else { @@ -95,3 +100,5 @@ extension _BString { self = builder.finalize() } } + +#endif diff --git a/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift b/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift index da0b3a93..f108d77d 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func _breakState( upTo end: Path, @@ -61,6 +64,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { /// - Returns: the position at which the grapheme breaks finally sync up with the originals. /// (or nil if they never did). @@ -96,6 +100,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Rope { mutating func resyncBreaks( old: inout _CharacterRecognizer, @@ -152,6 +157,7 @@ extension _BString.Rope { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { /// Resyncronize chunk metadata with the (possibly) reshuffled grapheme /// breaks after an insertion that ended at `index`. @@ -261,3 +267,5 @@ extension _BString.Chunk { return } } + +#endif diff --git a/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift index 308b05f0..ef6ffbce 100644 --- a/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift +++ b/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { mutating func removeSubrange(_ bounds: Range) { precondition(bounds.upperBound <= endIndex, "Index out of bounds") @@ -19,6 +22,7 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { mutating func removeCharacter(at i: Index) -> Character { let (start, chunk) = self.path(to: i, preferEnd: false) @@ -40,3 +44,5 @@ extension _BString { return scalar } } + +#endif diff --git a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift index f3af7655..754e664c 100644 --- a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift +++ b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { mutating func replaceSubrange(_ range: Range, with newElements: some StringProtocol) { precondition(range.upperBound <= endIndex, "Index out of bounds") @@ -69,3 +72,4 @@ extension _BString { } } +#endif diff --git a/Sources/RopeModule/BString/Operations/_BString+Split.swift b/Sources/RopeModule/BString/Operations/_BString+Split.swift index 0865685e..e38675fa 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Split.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Split.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { mutating func split( at index: Index @@ -28,3 +31,5 @@ extension _BString { return builder } } + +#endif diff --git a/Sources/RopeModule/BigString/BigString+CharacterView.swift b/Sources/RopeModule/BigString/BigString+CharacterView.swift index 50b5f61b..e6a366c9 100644 --- a/Sources/RopeModule/BigString/BigString+CharacterView.swift +++ b/Sources/RopeModule/BigString/BigString+CharacterView.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public struct Index { internal var _value: _BString.Index @@ -19,48 +22,56 @@ extension BigString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.Index: CustomStringConvertible { public var description: String { "\(_value)" } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.Index: Equatable { public static func ==(left: Self, right: Self) -> Bool { left._value == right._value } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.Index: Comparable { public static func <(left: Self, right: Self) -> Bool { left._value < right._value } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.Index: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(_value) } } +@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) } } +@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) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: Hashable { public func hash(into hasher: inout Hasher) { _guts.hashCharacters(into: &hasher) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: Sequence { public struct Iterator: IteratorProtocol { public typealias Element = Character @@ -81,6 +92,7 @@ extension BigString: Sequence { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: BidirectionalCollection { public typealias Element = Character @@ -117,6 +129,7 @@ extension BigString: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: RangeReplaceableCollection { public mutating func replaceSubrange( _ subrange: Range, @@ -279,3 +292,5 @@ extension BigString: RangeReplaceableCollection { _guts = _BString() } } + +#endif diff --git a/Sources/RopeModule/BigString/BigString+UTF16View.swift b/Sources/RopeModule/BigString/BigString+UTF16View.swift index 5304cd51..b6da68f9 100644 --- a/Sources/RopeModule/BigString/BigString+UTF16View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF16View.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public struct UTF16View { internal var _guts: _BString @@ -36,12 +39,14 @@ extension BigString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public init(_ content: UTF16View) { self._guts = content._guts } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: CustomStringConvertible { public var description: String { var d = "<" @@ -53,24 +58,28 @@ extension BigString.UTF16View: CustomStringConvertible { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: Equatable { public static func ==(left: Self, right: Self) -> Bool { left._guts.utf8IsEqual(to: right._guts) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: Comparable { public static func <(left: Self, right: Self) -> Bool { left._guts.utf8IsLess(than: right._guts) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: Hashable { public func hash(into hasher: inout Hasher) { _guts.hashUTF8(into: &hasher) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: Sequence { public struct Iterator: IteratorProtocol { public typealias Element = UInt16 @@ -91,6 +100,7 @@ extension BigString.UTF16View: Sequence { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: BidirectionalCollection { public typealias Index = BigString.Index public typealias Element = UInt16 @@ -127,3 +137,5 @@ extension BigString.UTF16View: BidirectionalCollection { _guts[utf16: position._value] } } + +#endif diff --git a/Sources/RopeModule/BigString/BigString+UTF8View.swift b/Sources/RopeModule/BigString/BigString+UTF8View.swift index fbb46a1b..9f789113 100644 --- a/Sources/RopeModule/BigString/BigString+UTF8View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF8View.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public struct UTF8View { internal var _guts: _BString @@ -36,12 +39,14 @@ extension BigString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public init(_ content: UTF8View) { self._guts = content._guts } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: CustomStringConvertible { public var description: String { var d = "<" @@ -53,24 +58,28 @@ extension BigString.UTF8View: CustomStringConvertible { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: Equatable { public static func ==(left: Self, right: Self) -> Bool { left._guts.utf8IsEqual(to: right._guts) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: Comparable { public static func <(left: Self, right: Self) -> Bool { left._guts.utf8IsLess(than: right._guts) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: Hashable { public func hash(into hasher: inout Hasher) { _guts.hashUTF8(into: &hasher) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: Sequence { public struct Iterator: IteratorProtocol { public typealias Element = UInt8 @@ -91,6 +100,7 @@ extension BigString.UTF8View: Sequence { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: BidirectionalCollection { public typealias Index = BigString.Index public typealias Element = UInt8 @@ -127,3 +137,5 @@ extension BigString.UTF8View: BidirectionalCollection { _guts[utf8: position._value] } } + +#endif diff --git a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift index dbce1e65..a24d4ecc 100644 --- a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public struct UnicodeScalarView { var _guts: _BString @@ -36,42 +39,49 @@ extension BigString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public init(_ content: UnicodeScalarView) { self._guts = content._guts } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(_guts: _BString(value)) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: CustomStringConvertible { public var description: String { String(_from: _guts) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: Equatable { public static func ==(left: Self, right: Self) -> Bool { left._guts.utf8IsEqual(to: right._guts) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: Comparable { public static func <(left: Self, right: Self) -> Bool { left._guts.utf8IsLess(than: right._guts) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: Hashable { public func hash(into hasher: inout Hasher) { _guts.hashUTF8(into: &hasher) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: Sequence { public struct Iterator: IteratorProtocol { public typealias Element = Unicode.Scalar @@ -92,6 +102,7 @@ extension BigString.UnicodeScalarView: Sequence { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: BidirectionalCollection { public typealias Element = Unicode.Scalar public typealias Index = BigString.Index @@ -129,6 +140,7 @@ 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( _ subrange: Range, @@ -287,3 +299,5 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { _guts = _BString() } } + +#endif diff --git a/Sources/RopeModule/BigString/BigString.swift b/Sources/RopeModule/BigString/BigString.swift index 0d44c07b..c13fcc97 100644 --- a/Sources/RopeModule/BigString/BigString.swift +++ b/Sources/RopeModule/BigString/BigString.swift @@ -9,6 +9,9 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) public struct BigString: Sendable { internal var _guts: _BString @@ -21,30 +24,35 @@ public struct BigString: Sendable { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(value) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: CustomStringConvertible, LosslessStringConvertible { public var description: String { String(_from: _guts) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: TextOutputStream { public mutating func write(_ string: String) { self.append(contentsOf: string) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public func _invariantCheck() { _guts.invariantCheck() } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String { public init(_ big: BigString) { self.init(_from: big._guts) @@ -55,6 +63,7 @@ extension String { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String.UnicodeScalarView { public init(_ big: BigString.UnicodeScalarView) { self = String(_from: big._guts).unicodeScalars @@ -65,8 +74,16 @@ extension String.UnicodeScalarView { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension Range { internal var _base: Range<_BString.Index> { Range<_BString.Index>(uncheckedBounds: (lowerBound._value, upperBound._value)) } } + +#else + +@available(*, unavailable, message: "BigString requires Swift 5.8") +public struct BigString: Sendable {} + +#endif diff --git a/Sources/RopeModule/Utilities/String Utilities.swift b/Sources/RopeModule/Utilities/String Utilities.swift index 0b1fe136..a27ab140 100644 --- a/Sources/RopeModule/Utilities/String Utilities.swift +++ b/Sources/RopeModule/Utilities/String Utilities.swift @@ -9,6 +9,7 @@ // //===----------------------------------------------------------------------===// +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension StringProtocol { @inline(__always) var _indexOfLastCharacter: Index { @@ -44,6 +45,7 @@ extension StringProtocol { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String { internal func _lpad(to width: Int, with pad: Character = " ") -> String { let c = self.count @@ -58,6 +60,7 @@ extension String { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String { @discardableResult mutating func _appendQuotedProtectingLeft( diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift index da1b9d1e..faab4ef3 100644 --- a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -9,125 +9,26 @@ // //===----------------------------------------------------------------------===// -/// CR and LF are common special cases in grapheme breaking logic -private var _CR: UInt8 { return 0x0d } -private var _LF: UInt8 { return 0x0a } +#if swift(>=5.8) -internal func _hasGraphemeBreakBetween( - _ lhs: Unicode.Scalar, _ rhs: Unicode.Scalar -) -> Bool { - - // CR-LF is a special case: no break between these - if lhs == Unicode.Scalar(_CR) && rhs == Unicode.Scalar(_LF) { - return false - } - - // Whether the given scalar, when it appears paired with another scalar - // satisfying this property, has a grapheme break between it and the other - // scalar. - func hasBreakWhenPaired(_ x: Unicode.Scalar) -> Bool { - // TODO: This doesn't generate optimal code, tune/re-write at a lower - // level. - // - // NOTE: Order of case ranges affects codegen, and thus performance. All - // things being equal, keep existing order below. - switch x.value { - // Unified CJK Han ideographs, common and some supplemental, amongst - // others: - // U+3400 ~ U+A4CF - case 0x3400...0xa4cf: return true - - // Repeat sub-300 check, this is beneficial for common cases of Latin - // characters embedded within non-Latin script (e.g. newlines, spaces, - // proper nouns and/or jargon, punctuation). - // - // NOTE: CR-LF special case has already been checked. - case 0x0000...0x02ff: return true - - // Non-combining kana: - // U+3041 ~ U+3096 - // U+30A1 ~ U+30FC - case 0x3041...0x3096: return true - case 0x30a1...0x30fc: return true - - // Non-combining modern (and some archaic) Cyrillic: - // U+0400 ~ U+0482 (first half of Cyrillic block) - case 0x0400...0x0482: return true - - // Modern Arabic, excluding extenders and prependers: - // U+061D ~ U+064A - case 0x061d...0x064a: return true - - // Precomposed Hangul syllables: - // U+AC00 ~ U+D7AF - case 0xac00...0xd7af: return true - - // Common general use punctuation, excluding extenders: - // U+2010 ~ U+2029 - case 0x2010...0x2029: return true - - // CJK punctuation characters, excluding extenders: - // U+3000 ~ U+3029 - case 0x3000...0x3029: return true - - // Full-width forms: - // U+FF01 ~ U+FF9D - case 0xFF01...0xFF9D: return true - - default: return false - } - } - return hasBreakWhenPaired(lhs) && hasBreakWhenPaired(rhs) -} - -// FIXME: This has terrible performance. -// FIXME: Replace with Unicode._CharacterRecognizer once it gets into a build. -struct _CharacterRecognizer { - private var string: String - - init() { - string = "" - } - - init(first: Unicode.Scalar) { - string = String(first) - } - - static func quickBreak( - between scalar1: Unicode.Scalar, - and scalar2: Unicode.Scalar - ) -> Bool? { - if scalar1 == Unicode.Scalar(_CR) && scalar2 == Unicode.Scalar(_LF) { return false } - if _hasGraphemeBreakBetween(scalar1, scalar2) { return true } - return nil - } - - mutating func hasBreak( - before next: Unicode.Scalar - ) -> Bool { - let next = String(next) - guard !string.isEmpty else { - string = next - return true - } - string.append(next) - let i = string.index(after: string.startIndex) - if i == string.endIndex { return false } - string = next - return true - } -} - -extension _CharacterRecognizer: Equatable { - static func ==(left: Self, right: Self) -> Bool { - left.string.utf8.elementsEqual(right.string.utf8) - } -} +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +internal typealias _CharacterRecognizer = Unicode._CharacterRecognizer +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _CharacterRecognizer { mutating func firstBreak( in str: Substring ) -> Range? { + #if true + var str = str + let scalarRange = str.withUTF8 { buffer in + self._firstBreak(inUncheckedUnsafeUTF8Buffer: buffer) + } + guard let scalarRange else { return nil } + let lower = str._utf8Index(at: scalarRange.lowerBound) + let upper = str._utf8Index(at: scalarRange.upperBound) + return lower ..< upper + #else guard !str.isEmpty else { return nil } let c = self.string.utf8.count if c == 0 { @@ -151,8 +52,11 @@ extension _CharacterRecognizer { let lower = str._utf8Index(at: offset - c) let upper = str._utf8Index(at: offset - c + scalarWidth) return lower ..< upper + #endif } } + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _CharacterRecognizer { init(partialCharacter: Substring.UnicodeScalarView) { self.init() @@ -257,31 +161,4 @@ extension _CharacterRecognizer { } } -extension String { - // FIXME: Remove once the stdlib entry point gets into a build. - func _index(roundingDown i: Index) -> Index { - guard i < endIndex else { return endIndex } - guard !i._isCharacterAligned else { return i } - return index(before: index(after: i)) - } -} - -extension Substring { - // FIXME: Remove once the stdlib entry point gets into a build. - func _index(roundingDown i: Index) -> Index { - index(i, offsetBy: 0) - } - - func _nextBreak(onOrAfter i: Index) -> Index { - let nearestDown = _index(roundingDown: i) - guard nearestDown != i else { return nearestDown } - return index(after: nearestDown) - } -} - -extension String.UnicodeScalarView { - // FIXME: Remove once the stdlib entry point gets into a build. - func _index(roundingDown i: Index) -> Index { - index(i, offsetBy: 0) - } -} +#endif diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index d5502406..34fde0df 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -9,9 +9,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=5.8) import RopeModule import XCTest +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) class TestBigString: XCTestCase { override class func setUp() { // Turn off output buffering. @@ -538,3 +540,4 @@ class TestBigString: XCTestCase { } } } +#endif From 67a149da6a3dcfd335d10bb026d85e5e91684db2 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 13 Feb 2023 10:55:51 -0800 Subject: [PATCH 026/113] _BString: Set better max node size in Release builds Also, adjust minimum node size calculation to match classic B-trees. --- Sources/RopeModule/BString/Basics/_BString+Summary.swift | 8 +++++++- Sources/RopeModule/Rope/Basics/_RopeSummary.swift | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Summary.swift b/Sources/RopeModule/BString/Basics/_BString+Summary.swift index ce138a82..5e0a9305 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Summary.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Summary.swift @@ -47,7 +47,13 @@ extension _BString.Summary: CustomStringConvertible { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Summary: _RopeSummary { @inline(__always) - static var maxNodeSize: Int { 10 } + static var maxNodeSize: Int { + #if DEBUG + return 10 + #else + return 15 + #endif + } @inline(__always) static var nodeSizeBitWidth: Int { 4 } diff --git a/Sources/RopeModule/Rope/Basics/_RopeSummary.swift b/Sources/RopeModule/Rope/Basics/_RopeSummary.swift index 4af962b2..d67f239f 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeSummary.swift +++ b/Sources/RopeModule/Rope/Basics/_RopeSummary.swift @@ -37,7 +37,7 @@ protocol _RopeSummary: Equatable, Sendable { extension _RopeSummary { @inline(__always) - static var minNodeSize: Int { maxNodeSize / 2 } + static var minNodeSize: Int { (maxNodeSize + 1) / 2 } } extension _RopeSummary { From 8c1740ad283caff01de9387e5592bd0aee8c6efd Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 13 Feb 2023 11:00:38 -0800 Subject: [PATCH 027/113] _Rope.Index: Merge height into UInt64 storage. This leaves 56 bits for path data, which should still be plenty. (We want to allow big strings to grow to 2^48 UTF-8 code units, to match the standard String; however, there is no practical need to support any more, and even that is a stretch.) Add tests to verify that the tree capacity matches expectations in Release builds. (In Debug builds, we limit the maximum node size, which drastically reduces capacity. This is okay.) --- .../BString/Basics/_BString+Contents.swift | 22 ++++++ Sources/RopeModule/BigString/BigString.swift | 3 + .../Rope/Conformances/_Rope+Collection.swift | 79 +++++++++++++++---- .../Rope/Conformances/_Rope+Sequence.swift | 2 +- Tests/RopeModuleTests/TestBString.swift | 17 +++- Tests/RopeModuleTests/TestBigString.swift | 11 +++ 6 files changed, 114 insertions(+), 20 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 3601488b..71837692 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -11,6 +11,28 @@ #if swift(>=5.8) +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + /// The estimated maximum number of UTF-8 code units that `_BString` is guaranteed to be able + /// to hold without encountering an overflow in its operations. This corresponds to the capacity + /// of the deepest tree where every node is the minimum possible size. + static var minimumCapacity: Int { + let c = Rope.minimumCapacity + let (r, overflow) = Chunk.minUTF8Count.multipliedReportingOverflow(by: c) + guard !overflow else { return Int.max } + return r + } + + /// The maximum number of UTF-8 code units that `_BString` may be able to store in the best + /// possible case, when every node in the underlying tree is fully filled with data. + static var maximumCapacity: Int { + let c = Rope.maximumCapacity + let (r, overflow) = Chunk.maxUTF8Count.multipliedReportingOverflow(by: c) + guard !overflow else { return Int.max } + return r + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { var isEmpty: Bool { diff --git a/Sources/RopeModule/BigString/BigString.swift b/Sources/RopeModule/BigString/BigString.swift index c13fcc97..e52722b1 100644 --- a/Sources/RopeModule/BigString/BigString.swift +++ b/Sources/RopeModule/BigString/BigString.swift @@ -47,6 +47,9 @@ extension BigString: TextOutputStream { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { + public static var _minimumCapacity: Int { _BString.minimumCapacity } + public static var _maximumCapacity: Int { _BString.maximumCapacity } + public func _invariantCheck() { _guts.invariantCheck() } diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift index 33c48b28..5965b5e7 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift @@ -61,39 +61,44 @@ extension _Rope { struct Index { typealias Summary = _Rope.Summary - var _height: UInt8 + // ┌──────────────────────────────────┬────────┐ + // │ b63:b8 │ b7:b0 │ + // ├──────────────────────────────────┼────────┤ + // │ path │ height │ + // └──────────────────────────────────┴────────┘ var _path: UInt64 - + + @inline(__always) + static var _pathBitWidth: Int { 56 } + init(height: UInt8) { - self._height = height - self._path = 0 - assert(Int(_height + 1) * Summary.nodeSizeBitWidth < UInt64.bitWidth) + self._path = UInt64(truncatingIfNeeded: height) + assert((Int(height) + 1) * Summary.nodeSizeBitWidth <= Self._pathBitWidth) } } } extension _Rope.Index: Equatable { static func ==(left: Self, right: Self) -> Bool { - left._height == right._height && left._path == right._path + left._path == right._path } } extension _Rope.Index: Hashable { func hash(into hasher: inout Hasher) { - hasher.combine(_height) hasher.combine(_path) } } extension _Rope.Index: Comparable { static func <(left: Self, right: Self) -> Bool { - (left._height, left._path) < (right._height, right._path) + left._path < right._path } } extension _Rope.Index: CustomStringConvertible { var description: String { var r = "<" - for h in stride(from: _height, through: 0, by: -1) { + for h in stride(from: height, through: 0, by: -1) { r += "\(self[height: h])" if h > 0 { r += ", " } } @@ -103,17 +108,21 @@ extension _Rope.Index: CustomStringConvertible { } extension _Rope.Index { + var height: UInt8 { + UInt8(truncatingIfNeeded: _path) + } + subscript(height height: UInt8) -> Int { get { - assert(height <= self._height) - let shift = Int(height) * Summary.nodeSizeBitWidth + assert(height <= self.height) + let shift = 8 + Int(height) * Summary.nodeSizeBitWidth let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1 return numericCast((_path &>> shift) & mask) } set { - assert(height <= self._height) + assert(height <= self.height) assert(newValue >= 0 && newValue <= Summary.maxNodeSize) - let shift = Int(height) * Summary.nodeSizeBitWidth + let shift = 8 + Int(height) * Summary.nodeSizeBitWidth let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1 _path &= ~(mask &<< shift) _path |= numericCast(newValue) &<< shift @@ -122,19 +131,55 @@ extension _Rope.Index { func isEmpty(below height: UInt8) -> Bool { let shift = Int(height) * Summary.nodeSizeBitWidth - assert(shift + Summary.nodeSizeBitWidth < UInt64.bitWidth) - let mask: UInt64 = (1 &<< shift) - 1 + assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth) + let mask: UInt64 = ((1 &<< shift) - 1) &<< 8 return (_path & mask) == 0 } mutating func clear(below height: UInt8) { let shift = Int(height) * Summary.nodeSizeBitWidth - assert(shift + Summary.nodeSizeBitWidth < UInt64.bitWidth) - let mask: UInt64 = (1 &<< shift) - 1 + assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth) + let mask: UInt64 = ((1 &<< shift) - 1) &<< 8 _path &= ~mask } } +extension _Rope { + static var maxHeight: Int { + Index._pathBitWidth / Summary.nodeSizeBitWidth + } + + /// The estimated maximum number of items that can fit in this rope in the worst possible case, + /// i.e., when the tree consists of minimum-sized nodes. (The data structure itself has no + /// inherent limit, but this implementation of it is limited by the fixed 56-bit path + /// representation used in the `Index` type.) + /// + /// This is one less than the minimum possible size for a rope whose size exceeds the maximum. + static var minimumCapacity: Int { + var c = 2 + for _ in 0 ..< maxHeight { + let (r, overflow) = c.multipliedReportingOverflow(by: Summary.minNodeSize) + if overflow { return .max } + c = r + } + return c - 1 + } + + /// The maximum number of items that can fit in this rope in the best possible case, i.e., when + /// the tree consists of maximum-sized nodes. (The data structure itself has no inherent limit, + /// but this implementation of it is limited by the fixed 56-bit path representation used in + /// the `Index` type.) + static var maximumCapacity: Int { + var c = 1 + for _ in 0 ... maxHeight { + let (r, overflow) = c.multipliedReportingOverflow(by: Summary.maxNodeSize) + if overflow { return .max } + c = r + } + return c + } +} + extension _Rope { func count(in metric: some _RopeMetric) -> Int { guard _root != nil else { return 0 } diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift index 92056ce5..3f80d56d 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift @@ -96,7 +96,7 @@ extension _Rope: Sequence { extension _Rope { func _leaf(at index: Index) -> Node? { - assert(index._height == root.height) + assert(index.height == root.height) var node = root while true { let h = node.height diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index cbe6606c..59d6d371 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -9,10 +9,11 @@ // //===----------------------------------------------------------------------===// -#if DEBUG +#if swift(>=5.8) && DEBUG @testable import RopeModule import XCTest +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) class TestBString: XCTestCase { override class func setUp() { // Turn off output buffering. @@ -24,7 +25,19 @@ class TestBString: XCTestCase { override func setUp() { print("Global seed: \(globalSeed)") } - + + func test_capacity() { + let min = _BString.minimumCapacity + let max = _BString.maximumCapacity + + XCTAssertLessThanOrEqual(min, max) +#if !DEBUG // Debug builds have smaller nodes + // We want big strings to hold at least as many UTF-8 code units as a regular String. + // We want big strings to hold at least as many UTF-8 code units as a regular String. + XCTAssertGreaterThanOrEqual(min, 1 << 48) +#endif + } + func test_empty() { let s = _BString() s.invariantCheck() diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index 34fde0df..f3f301ba 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -26,6 +26,17 @@ class TestBigString: XCTestCase { print("Global seed: \(globalSeed)") } + func test_capacity() { + let min = BigString._minimumCapacity + let max = BigString._maximumCapacity + + XCTAssertLessThanOrEqual(min, max) +#if !DEBUG // Debug builds have smaller nodes + // We want big strings to hold at least as many UTF-8 code units as a regular String. + XCTAssertGreaterThanOrEqual(min, 1 << 48) +#endif + } + func test_empty() { let s = BigString() s._invariantCheck() From 8f48c3ae37b4e9241bcb0c07a4376cbde9f5c22e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 16 Feb 2023 11:00:14 -0800 Subject: [PATCH 028/113] More assorted bug fixes and refinements --- .../BString/Basics/_BString+Contents.swift | 5 +- .../BString/Basics/_BString+Iterators.swift | 46 +++++++++---------- .../Conformances/_BString+Comparisons.swift | 2 + .../Conformances/_BString+Hashing.swift | 14 ++++++ 4 files changed, 41 insertions(+), 26 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 71837692..9bc335ec 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -175,7 +175,8 @@ extension _BString { offsetBy distance: Int, in metric: some _StringMetric ) -> Index { - var (path, chunk) = path(to: i, preferEnd: false) + precondition(i <= endIndex, "Index out of bounds") + var (path, chunk) = path(to: i, preferEnd: i == endIndex || distance < 0) let base = baseIndex(with: i, at: path.chunk) var d = distance let r = metric.formIndex(&path.chunk, offsetBy: &d, in: chunk) @@ -268,7 +269,7 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func characterIndex(roundingDown i: Index) -> Index { - let offset = i._utf8Offset - 1 + let offset = i._utf8Offset precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") guard offset > 0, offset < utf8Count else { return Index(_utf8Offset: offset) } diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index ab0863e1..e914fbef 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -146,14 +146,15 @@ extension _BString.UnicodeScalarIterator: IteratorProtocol { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct CharacterIterator { - internal var _utf8BaseOffset: Int internal var _base: _Rope.Iterator + + internal var _utf8BaseOffset: Int internal var _index: String.Index internal var _next: String.Index - internal init(_base: _Rope.Iterator, utf8BaseOffset: Int) { - self._utf8BaseOffset = utf8BaseOffset - self._base = _base + internal init(_ string: _BString) { + self._utf8BaseOffset = 0 + self._base = string.rope.makeIterator() guard !_base.isAtEnd else { _index = "".startIndex _next = "".endIndex @@ -165,35 +166,32 @@ extension _BString { self._next = chunk.string[_index...].index(after: _index) } - internal init(_base: _Rope.Iterator, utf8BaseOffset: Int, _ i: String.Index) { - self._utf8BaseOffset = utf8BaseOffset - self._base = _base - self._index = i - assert(i >= _base.current.firstBreak) - guard !_base.isAtEnd, i < _base.current.string.endIndex else { - self._next = i + internal init( + _ string: _BString, + from start: Index + ) { + self._utf8BaseOffset = start._utf8Offset + + if start == string.endIndex { + self._base = string.rope.makeIterator(from: string.rope.endIndex) + self._index = "".startIndex + self._next = "".endIndex return } - self._next = _base.current.wholeCharacters.index(after: i) + let path = string.path(to: start, preferEnd: false).path + self._base = string.rope.makeIterator(from: path.rope) + self._utf8BaseOffset -= path.chunk._utf8Offset + self._index = path.chunk + self._next = _base.current.wholeCharacters.index(after: path.chunk) } } internal func makeCharacterIterator() -> CharacterIterator { - CharacterIterator(_base: rope.makeIterator(), utf8BaseOffset: 0) + CharacterIterator(self) } internal func makeCharacterIterator(from index: Index) -> CharacterIterator { - if index == endIndex { - return CharacterIterator( - _base: rope.makeIterator(from: rope.endIndex), - utf8BaseOffset: index._utf8Offset) - } - let (path, _) = self.path(to: index, preferEnd: false) - let base = rope.makeIterator(from: path.rope) - return CharacterIterator( - _base: base, - utf8BaseOffset: index._utf8Offset - path.chunk._utf8Offset, - path.chunk) + CharacterIterator(self, from: index) } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift index 4fac1847..3ab28258 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift @@ -58,6 +58,8 @@ extension _BString { var it1 = left.makeCharacterIterator(from: leftRange.lowerBound) var it2 = right.makeCharacterIterator(from: rightRange.upperBound) + if leftRange._isEmptyUTF8 { return rightRange._isEmptyUTF8 } + let leftEnd = left.path(to: leftRange.upperBound, preferEnd: true).path let rightEnd = right.path(to: rightRange.upperBound, preferEnd: true).path diff --git a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift index 81192eae..6871c8fb 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift @@ -27,6 +27,20 @@ extension _BString { hasher.combine(0xFF as UInt8) } + internal func hashCharacters(into hasher: inout Hasher, from range: Range) { + var it = self.makeCharacterIterator(from: range.lowerBound) + let endOffset = range.upperBound._utf8Offset + while let character = it.next() { + var s = String(character) + if it.utf8Offset > endOffset { + let i = s.unicodeScalars._index(roundingDown: s._utf8Index(at: it.utf8Offset - endOffset)) + s.removeSubrange(i...) + } + s._withNFCCodeUnits { hasher.combine($0) } + } + hasher.combine(0xFF as UInt8) + } + /// Feed the UTF-8 encoding of `self` into hasher, with a terminating byte. internal func hashUTF8(into hasher: inout Hasher) { for chunk in self.rope { From 3cc5a3888abc39bdf5bc4add2ec4ea8d8fb3e2fd Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Feb 2023 14:47:29 -0800 Subject: [PATCH 029/113] _Rope: Add a leaf node reference to indices. Implement explicit index invalidation --- .../BString/Basics/_BString+Path.swift | 11 +- .../BString/Operations/_BString+Insert.swift | 3 +- .../Rope/Basics/_Rope+Debugging.swift | 6 + .../RopeModule/Rope/Basics/_Rope+Node.swift | 171 +++++---- .../Rope/Basics/_Rope+UnmanagedLeaf.swift | 43 +++ .../Rope/Basics/_Rope+UnsafeHandle.swift | 11 + Sources/RopeModule/Rope/Basics/_Rope.swift | 8 +- .../RopeModule/Rope/Basics/_RopePath.swift | 98 ++++++ .../RopeModule/Rope/Basics/_RopeVersion.swift | 41 +++ .../Rope/Conformances/_Rope+Collection.swift | 326 ++++++++++-------- .../Rope/Conformances/_Rope+Index.swift | 67 ++++ .../Rope/Conformances/_Rope+Sequence.swift | 64 ++-- .../Rope/Operations/_Rope+Append.swift | 1 + .../Rope/Operations/_Rope+Find.swift | 13 +- .../Rope/Operations/_Rope+Insert.swift | 23 +- .../Operations/_Rope+MutatingForEach.swift | 18 +- .../Rope/Operations/_Rope+Remove.swift | 11 +- .../Operations/_Rope+RemoveSubrange.swift | 3 + .../Rope/Operations/_Rope+Split.swift | 7 +- Tests/RopeModuleTests/TestRope.swift | 13 +- .../xcschemes/RopeModule.xcscheme | 14 + 21 files changed, 671 insertions(+), 281 deletions(-) create mode 100644 Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift create mode 100644 Sources/RopeModule/Rope/Basics/_RopePath.swift create mode 100644 Sources/RopeModule/Rope/Basics/_RopeVersion.swift create mode 100644 Sources/RopeModule/Rope/Conformances/_Rope+Index.swift diff --git a/Sources/RopeModule/BString/Basics/_BString+Path.swift b/Sources/RopeModule/BString/Basics/_BString+Path.swift index b32cd629..d6946c62 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Path.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Path.swift @@ -58,12 +58,11 @@ extension _BString { to i: Index, preferEnd: Bool ) -> (path: Path, chunk: Chunk) { - let r = rope.find(at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) - return r.node!.readLeaf { - let slot = r.index[height: 0] - let index = $0.children[slot].value.index(at: r.remaining, utf16Delta: i._utf16Delta) - return (Path(r.index, index), $0.children[slot].value) - } + let (ropeIndex, remaining) = rope.find( + at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) + let chunk = rope[ropeIndex] + let chunkIndex = chunk.index(at: remaining, utf16Delta: i._utf16Delta) + return (Path(ropeIndex, chunkIndex), chunk) } } diff --git a/Sources/RopeModule/BString/Operations/_BString+Insert.swift b/Sources/RopeModule/BString/Operations/_BString+Insert.swift index 707a4286..d2782857 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Insert.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Insert.swift @@ -36,7 +36,8 @@ extension _BString { // full grapheme breaking state of the ingester at the start of the insertion. // (We'll use it to resync grapheme breaks in the parts that follow the insertion.) var (ingester, _, path) = ingester(forInserting: other, at: index, allowForwardPeek: false) - let r = rope[path.rope].insert(from: &ingester, at: path.chunk) + let i = path.chunk + let r = rope.update(at: &path.rope) { $0.insert(from: &ingester, at: i) } switch r { case let .inline(r): assert(ingester.isAtEnd) diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift b/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift index 27543b48..4cab8d42 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift @@ -22,6 +22,12 @@ private func _addressString(for object: Unmanaged) -> String { _addressString(for: object.toOpaque()) } +extension _Rope.UnmanagedLeaf: CustomStringConvertible { + var description: String { + _addressString(for: _ref.toOpaque()) + } +} + extension _Rope { var nodeCount: Int { _root?.nodeCount ?? 0 } } diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Node.swift b/Sources/RopeModule/Rope/Basics/_Rope+Node.swift index c4df69e0..e5352e6c 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Node.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+Node.swift @@ -17,7 +17,9 @@ extension _Rope { typealias Item = _Rope.Item typealias Storage = _Rope.Storage typealias UnsafeHandle = _Rope.UnsafeHandle - + typealias Path = _Rope.Path + typealias UnmanagedLeaf = _Rope.UnmanagedLeaf + var object: AnyObject var summary: Summary @@ -335,59 +337,86 @@ extension _Rope.Node { } extension _Rope.Node { - var startIndex: Index { - var i = Index(height: self.height) - descendToFirstItem(under: &i) - return i + var startPath: Path { + Path(height: self.height) } - var lastIndex: Index { - var i = Index(height: self.height) - descendToLastItem(under: &i) - return i + var lastPath: Path { + var path = Path(height: self.height) + _ = descendToLastItem(under: &path) + return path } - func isAtEnd(_ i: Index) -> Bool { - i[height: self.height] == childCount + func isAtEnd(_ path: Path) -> Bool { + path[self.height] == childCount } - func descendToFirstItem(under i: inout Index) { - i.clear(below: self.height + 1) + func descendToFirstItem(under path: inout Path) -> UnmanagedLeaf { + path.clear(below: self.height + 1) + return unmanagedLeaf(at: path) } - func descendToLastItem(under i: inout Index) { + func descendToLastItem(under path: inout Path) -> UnmanagedLeaf { let h = self.height let slot = self.childCount - 1 - i[height: h] = slot + path[h] = slot if h > 0 { - readInner { $0.children[slot].descendToLastItem(under: &i) } + return readInner { $0.children[slot].descendToLastItem(under: &path) } } + return asUnmanagedLeaf } + var asUnmanagedLeaf: UnmanagedLeaf { + assert(height == 0) + return UnmanagedLeaf(unsafeDowncast(self.object, to: Storage.self)) + } + + func unmanagedLeaf(at path: Path) -> UnmanagedLeaf { + if height == 0 { + return asUnmanagedLeaf + } + let slot = path[height] + return readInner { $0.children[slot].unmanagedLeaf(at: path) } + } +} + +extension _Rope.Node { func formSuccessor(of i: inout Index) -> Bool { let h = self.height - var slot = i[height: h] + var slot = i._path[h] if h == 0 { - slot += 1 - guard slot < childCount else { return false } - i[height: h] = slot + slot &+= 1 + guard slot < childCount else { + return false + } + i._path[h] = slot + i._leaf = asUnmanagedLeaf + return true + } + return readInner { + let c = $0.children + if c[slot].formSuccessor(of: &i) { + return true + } + slot += 1 + guard slot < childCount else { + return false + } + i._path[h] = slot + i._leaf = c[slot].descendToFirstItem(under: &i._path) return true } - let success = readInner { $0.children[slot].formSuccessor(of: &i) } - if success { return true } - slot += 1 - guard slot < childCount else { return false } - i[height: h] = slot - i.clear(below: h) - return true } func formPredecessor(of i: inout Index) -> Bool { let h = self.height - var slot = i[height: h] + var slot = i._path[h] if h == 0 { - guard slot > 0 else { return false } - i[height: h] = slot - 1 + guard slot > 0 else { + return false + } + i._path[h] = slot &- 1 + i._leaf = asUnmanagedLeaf return true } return readInner { @@ -395,17 +424,21 @@ extension _Rope.Node { if slot < c.count, c[slot].formPredecessor(of: &i) { return true } - guard slot > 0 else { return false } + guard slot > 0 else { + return false + } slot -= 1 - i[height: h] = slot - c[slot].descendToLastItem(under: &i) + i._path[h] = slot + i._leaf = c[slot].descendToLastItem(under: &i._path) return true } } - +} + +extension _Rope.Node { var lastItem: Item { get { - self[lastIndex] + self[lastPath] } _modify { assert(childCount > 0) @@ -413,87 +446,89 @@ extension _Rope.Node { defer { _ = _finalizeModify(&state) } - yield &state.value + yield &state.item } } var firstItem: Item { get { - self[startIndex] + self[startPath] } _modify { - yield &self[startIndex] + yield &self[startPath] } } - subscript(i: Index) -> Item { + subscript(path: Path) -> Item { get { let h = height - let slot = i[height: h] - precondition(slot < childCount, "Index out of bounds") + let slot = path[h] + precondition(slot < childCount, "Path out of bounds") guard h == 0 else { - return readInner { $0.children[slot][i] } + return readInner { $0.children[slot][path] } } return readLeaf { $0.children[slot] } } @inline(__always) _modify { - var state = _prepareModify(at: i) + var state = _prepareModify(at: path) defer { _ = _finalizeModify(&state) } - yield &state.value + yield &state.item } } struct ModifyState { - var index: Index - var value: Item + var path: Path + var item: Item var summary: Summary } - mutating func _prepareModify(at i: Index) -> ModifyState { + mutating func _prepareModify(at path: Path) -> ModifyState { ensureUnique() let h = height - let slot = i[height: h] - precondition(slot < childCount, "Index out of bounds") + let slot = path[h] + precondition(slot < childCount, "Path out of bounds") guard h == 0 else { - return updateInner { $0.mutableChildren[slot]._prepareModify(at: i) } + return updateInner { $0.mutableChildren[slot]._prepareModify(at: path) } } - let value = updateLeaf { $0.mutableChildren.moveElement(from: slot) } - return ModifyState(index: i, value: value, summary: value.summary) + let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) } + return ModifyState(path: path, item: item, summary: item.summary) } mutating func _prepareModifyLast() -> ModifyState { - var i = Index(height: height) - return _prepareModifyLast(&i) + var path = Path(height: height) + return _prepareModifyLast(&path) } - mutating func _prepareModifyLast(_ i: inout Index) -> ModifyState { + mutating func _prepareModifyLast(_ path: inout Path) -> ModifyState { ensureUnique() let h = height let slot = self.childCount - 1 - i[height: h] = slot + path[h] = slot guard h == 0 else { - return updateInner { $0.mutableChildren[slot]._prepareModifyLast(&i) } + return updateInner { $0.mutableChildren[slot]._prepareModifyLast(&path) } } - let value = updateLeaf { $0.mutableChildren.moveElement(from: slot) } - return ModifyState(index: i, value: value, summary: value.summary) + let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) } + return ModifyState(path: path, item: item, summary: item.summary) } - mutating func _finalizeModify(_ state: inout ModifyState) -> Summary { + mutating func _finalizeModify( + _ state: inout ModifyState + ) -> (delta: Summary, leaf: UnmanagedLeaf) { assert(isUnique()) let h = height - let slot = state.index[height: h] - assert(slot < childCount, "Index out of bounds") + let slot = state.path[h] + assert(slot < childCount, "Path out of bounds") guard h == 0 else { - let delta = updateInner { $0.mutableChildren[slot]._finalizeModify(&state) } - summary.add(delta) - return delta + let r = updateInner { $0.mutableChildren[slot]._finalizeModify(&state) } + summary.add(r.delta) + return r } - let delta = state.value.summary.subtracting(state.summary) - updateLeaf { $0.mutableChildren.initializeElement(at: slot, to: state.value) } + let delta = state.item.summary.subtracting(state.summary) + updateLeaf { $0.mutableChildren.initializeElement(at: slot, to: state.item) } summary.add(delta) - return delta + return (delta, asUnmanagedLeaf) } } diff --git a/Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift b/Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift new file mode 100644 index 00000000..66924e80 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift @@ -0,0 +1,43 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + struct UnmanagedLeaf { + typealias Item = _Rope.Item + typealias Leaf = Storage + typealias UnsafeHandle = _Rope.UnsafeHandle + + var _ref: Unmanaged + + init(_ leaf: __shared Leaf) { + _ref = .passUnretained(leaf) + } + } +} + +extension _Rope.UnmanagedLeaf: Equatable { + static func ==(left: Self, right: Self) -> Bool { + left._ref.toOpaque() == right._ref.toOpaque() + } +} + +extension _Rope.UnmanagedLeaf { + func read( + body: (UnsafeHandle) -> R + ) -> R { + _ref._withUnsafeGuaranteedRef { leaf in + leaf.withUnsafeMutablePointers { h, p in + let handle = UnsafeHandle(isMutable: false, header: h, start: p) + return body(handle) + } + } + } +} diff --git a/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift b/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift index 4932182b..33ec4191 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift @@ -185,4 +185,15 @@ extension _Rope.UnsafeHandle { src.childCount -= count return children.prefix(count)._sum() } + + func distance(from start: Int, to end: Int, in metric: some _RopeMetric) -> Int { + if start <= end { + return children[start ..< end].reduce(into: 0) { + $0 += metric.nonnegativeSize(of: $1.summary) + } + } + return -children[end ..< start].reduce(into: 0) { + $0 += metric.nonnegativeSize(of: $1.summary) + } + } } diff --git a/Sources/RopeModule/Rope/Basics/_Rope.swift b/Sources/RopeModule/Rope/Basics/_Rope.swift index a83a4b60..8b6d7513 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope.swift @@ -14,15 +14,18 @@ /// quick lookup operations. struct _Rope { var _root: Node? - + var _version: _RopeVersion + init() { self._root = nil + self._version = _RopeVersion() } init(root: Node?) { self._root = root + self._version = _RopeVersion() } - + var root: Node { get { _root.unsafelyUnwrapped } @inline(__always) _modify { yield &_root! } @@ -30,6 +33,7 @@ struct _Rope { init(_ value: Element) { self._root = .createLeaf(Item(value)) + self._version = _RopeVersion() } } diff --git a/Sources/RopeModule/Rope/Basics/_RopePath.swift b/Sources/RopeModule/Rope/Basics/_RopePath.swift new file mode 100644 index 00000000..a6cc8d01 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_RopePath.swift @@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +struct _RopePath { + // ┌──────────────────────────────────┬────────┐ + // │ b63:b8 │ b7:b0 │ + // ├──────────────────────────────────┼────────┤ + // │ path │ height │ + // └──────────────────────────────────┴────────┘ + var _value: UInt64 + + @inline(__always) + static var _pathBitWidth: Int { 56 } + + init(height: UInt8) { + self._value = UInt64(truncatingIfNeeded: height) + assert((Int(height) + 1) * Summary.nodeSizeBitWidth <= Self._pathBitWidth) + } +} + +extension _Rope { + typealias Path = _RopePath +} + +extension _RopePath: Equatable { + static func ==(left: Self, right: Self) -> Bool { + left._value == right._value + } +} +extension _RopePath: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(_value) + } +} + +extension _RopePath: Comparable { + static func <(left: Self, right: Self) -> Bool { + left._value < right._value + } +} + +extension _RopePath: CustomStringConvertible { + var description: String { + var r = "<" + for h in stride(from: height, through: 0, by: -1) { + r += "\(self[h])" + if h > 0 { r += ", " } + } + r += ">" + return r + } +} + +extension _RopePath { + var height: UInt8 { + UInt8(truncatingIfNeeded: _value) + } + + subscript(height: UInt8) -> Int { + get { + assert(height <= self.height) + let shift = 8 + Int(height) * Summary.nodeSizeBitWidth + let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1 + return numericCast((_value &>> shift) & mask) + } + set { + assert(height <= self.height) + assert(newValue >= 0 && newValue <= Summary.maxNodeSize) + let shift = 8 + Int(height) * Summary.nodeSizeBitWidth + let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1 + _value &= ~(mask &<< shift) + _value |= numericCast(newValue) &<< shift + } + } + + func isEmpty(below height: UInt8) -> Bool { + let shift = Int(height) * Summary.nodeSizeBitWidth + assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth) + let mask: UInt64 = ((1 &<< shift) - 1) &<< 8 + return (_value & mask) == 0 + } + + mutating func clear(below height: UInt8) { + let shift = Int(height) * Summary.nodeSizeBitWidth + assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth) + let mask: UInt64 = ((1 &<< shift) - 1) &<< 8 + _value &= ~mask + } +} + diff --git a/Sources/RopeModule/Rope/Basics/_RopeVersion.swift b/Sources/RopeModule/Rope/Basics/_RopeVersion.swift new file mode 100644 index 00000000..e30d8ff8 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/_RopeVersion.swift @@ -0,0 +1,41 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +struct _RopeVersion { + // FIXME: Replace this probabilistic mess with atomics when Swift gets its act together. + var _value: UInt + + init() { + var rng = SystemRandomNumberGenerator() + _value = rng.next() + } + + init(_ value: UInt) { + self._value = value + } +} + +extension _RopeVersion: Equatable { + static func ==(left: Self, right: Self) -> Bool { + left._value == right._value + } +} + +extension _RopeVersion { + mutating func bump() { + _value &+= 1 + } + + mutating func reset() { + var rng = SystemRandomNumberGenerator() + _value = rng.next() + } +} diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift index 5965b5e7..b97a4800 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift @@ -9,21 +9,54 @@ // //===----------------------------------------------------------------------===// +extension _Rope { + func isValid(_ index: Index) -> Bool { + index._version == _version + } + + func validate(_ index: Index) { + precondition(isValid(index), "Invalid index") + } + + mutating func invalidateIndices() { + _version.bump() + } + + func ensureLeaf(in index: inout Index) { + validate(index) + guard index._leaf == nil else { return } + index._leaf = _unmanagedLeaf(at: index._path) + } +} + extension _Rope: BidirectionalCollection { - var height: UInt8 { _root?.height ?? 0 } - + var height: UInt8 { + _root?.height ?? 0 + } + var isEmpty: Bool { guard _root != nil else { return true } return root.childCount == 0 } - - var startIndex: Index { Index(height: height) } - + + var startPath: Path { + Path(height: height) + } + + var endPath: Path { + guard let root = _root else { return startPath } + var path = Path(height: height) + path[height] = root.childCount + return path + } + + var startIndex: Index { + // Note: `leaf` is intentionally not set here, to speed up accessing this property. + return Index(version: _version, path: startPath, leaf: nil) + } + var endIndex: Index { - guard let root = _root else { return startIndex } - var i = Index(height: height) - i[height: height] = root.childCount - return i + Index(version: _version, path: endPath, leaf: nil) } func index(after i: Index) -> Index { @@ -39,114 +72,75 @@ extension _Rope: BidirectionalCollection { } func formIndex(after i: inout Index) { + validate(i) precondition(i < endIndex, "Can't move after endIndex") + if let leaf = i._leaf { + let done = leaf.read { + let slot = i._path[$0.height] &+ 1 + guard slot < $0.childCount else { return false } + i._path[$0.height] = slot + return true + } + if done { return } + } if !root.formSuccessor(of: &i) { i = endIndex } } func formIndex(before i: inout Index) { + validate(i) precondition(i > startIndex, "Can't move before startIndex") + if let leaf = i._leaf { + let done = leaf.read { + let slot = i._path[$0.height] + guard slot > 0 else { return false } + i._path[$0.height] = slot &- 1 + return true + } + if done { return } + } let success = root.formPredecessor(of: &i) precondition(success, "Invalid index") } subscript(i: Index) -> Element { - get { root[i].value } - @inline(__always) _modify { yield &root[i].value } + get { + validate(i) + if let ref = i._leaf { + return ref.read { + $0.children[i._path[$0.height]].value + } + } + return root[i._path].value + } + @inline(__always) _modify { + validate(i) + // Note: we must not use _leaf -- it may not be on a unique path. + defer { invalidateIndices() } + yield &root[i._path].value + } } } extension _Rope { - struct Index { - typealias Summary = _Rope.Summary - - // ┌──────────────────────────────────┬────────┐ - // │ b63:b8 │ b7:b0 │ - // ├──────────────────────────────────┼────────┤ - // │ path │ height │ - // └──────────────────────────────────┴────────┘ - var _path: UInt64 - - @inline(__always) - static var _pathBitWidth: Int { 56 } - - init(height: UInt8) { - self._path = UInt64(truncatingIfNeeded: height) - assert((Int(height) + 1) * Summary.nodeSizeBitWidth <= Self._pathBitWidth) + /// Update the element at the given index, while keeping the index valid. + mutating func update( + at index: inout Index, + by body: (inout Element) -> R + ) -> R { + validate(index) + var state = root._prepareModify(at: index._path) + defer { + index._leaf = root._finalizeModify(&state).leaf } - } -} - -extension _Rope.Index: Equatable { - static func ==(left: Self, right: Self) -> Bool { - left._path == right._path - } -} -extension _Rope.Index: Hashable { - func hash(into hasher: inout Hasher) { - hasher.combine(_path) - } -} - -extension _Rope.Index: Comparable { - static func <(left: Self, right: Self) -> Bool { - left._path < right._path - } -} - -extension _Rope.Index: CustomStringConvertible { - var description: String { - var r = "<" - for h in stride(from: height, through: 0, by: -1) { - r += "\(self[height: h])" - if h > 0 { r += ", " } - } - r += ">" - return r - } -} - -extension _Rope.Index { - var height: UInt8 { - UInt8(truncatingIfNeeded: _path) - } - - subscript(height height: UInt8) -> Int { - get { - assert(height <= self.height) - let shift = 8 + Int(height) * Summary.nodeSizeBitWidth - let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1 - return numericCast((_path &>> shift) & mask) - } - set { - assert(height <= self.height) - assert(newValue >= 0 && newValue <= Summary.maxNodeSize) - let shift = 8 + Int(height) * Summary.nodeSizeBitWidth - let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1 - _path &= ~(mask &<< shift) - _path |= numericCast(newValue) &<< shift - } - } - - func isEmpty(below height: UInt8) -> Bool { - let shift = Int(height) * Summary.nodeSizeBitWidth - assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth) - let mask: UInt64 = ((1 &<< shift) - 1) &<< 8 - return (_path & mask) == 0 - } - - mutating func clear(below height: UInt8) { - let shift = Int(height) * Summary.nodeSizeBitWidth - assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth) - let mask: UInt64 = ((1 &<< shift) - 1) &<< 8 - _path &= ~mask + return body(&state.item.value) } } extension _Rope { static var maxHeight: Int { - Index._pathBitWidth / Summary.nodeSizeBitWidth + Path._pathBitWidth / Summary.nodeSizeBitWidth } /// The estimated maximum number of items that can fit in this rope in the worst possible case, @@ -195,8 +189,19 @@ extension _Rope.Node { extension _Rope { func distance(from start: Index, to end: Index, in metric: some _RopeMetric) -> Int { + validate(start) + validate(end) if start == end { return 0 } precondition(_root != nil, "Invalid index") + if start._leaf == end._leaf, let leaf = start._leaf { + // Fast path: both indices are pointing within the same leaf. + return leaf.read { + let h = $0.height + let a = start._path[h] + let b = end._path[h] + return $0.distance(from: a, to: b, in: metric) + } + } if start < end { return root.distance(from: start, to: end, in: metric) } @@ -204,29 +209,25 @@ extension _Rope { } func offset(of index: Index, in metric: some _RopeMetric) -> Int { - distance(from: startIndex, to: index, in: metric) + validate(index) + if _root == nil { return 0 } + return root.distanceFromStart(to: index, in: metric) } } extension _Rope.Node { func distanceFromStart(to index: Index, in metric: some _RopeMetric) -> Int { - let slot = index[height: height] + let slot = index._path[height] precondition(slot <= childCount, "Invalid index") if slot == childCount { precondition(index.isEmpty(below: height), "Invalid index") return metric.nonnegativeSize(of: self.summary) } if height == 0 { - return readLeaf { - $0.children[..) -> Int { assert(start < end) - let a = start[height: height] - let b = end[height: height] + let a = start._path[height] + let b = end._path[height] precondition(a < childCount, "Invalid index") precondition(b <= childCount, "Invalid index") assert(a <= b) @@ -251,9 +252,7 @@ extension _Rope.Node { } if height == 0 { assert(a < b) - return readLeaf { - $0.children[a.., preferEnd: Bool ) { + validate(i) if _root == nil { precondition(distance == 0, "Position out of bounds") return @@ -286,6 +286,13 @@ extension _Rope { precondition(success, "Position out of bounds") return } + if let leaf = i._leaf { + // Fast path: move within a single leaf + let r = leaf.read { + $0._seekForwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd) + } + if r { return } + } if root.seekForward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) { return } @@ -294,7 +301,10 @@ extension _Rope { } func index( - _ i: Index, offsetBy distance: Int, in metric: some _RopeMetric, preferEnd: Bool + _ i: Index, + offsetBy distance: Int, + in metric: some _RopeMetric, + preferEnd: Bool ) -> (index: Index, remainder: Int) { var i = i var distance = distance @@ -303,6 +313,53 @@ extension _Rope { } } +extension _Rope.UnsafeHandle { + func _seekForwardInLeaf( + from path: inout _Rope.Path, + by distance: inout Int, + in metric: some _RopeMetric, + preferEnd: Bool + ) -> Bool { + assert(distance >= 0) + assert(height == 0) + let c = children + var slot = path[0] + defer { path[0] = slot } + while slot < c.count { + let d = metric.nonnegativeSize(of: c[slot].summary) + if preferEnd ? d >= distance : d > distance { + return true + } + distance &-= d + slot &+= 1 + } + return false + } + + func _seekBackwardInLeaf( + from path: inout _Rope.Path, + by distance: inout Int, + in metric: some _RopeMetric, + preferEnd: Bool + ) -> Bool { + assert(distance >= 0) + assert(height == 0) + let c = children + var slot = path[0] &- 1 + while slot >= 0 { + let d = metric.nonnegativeSize(of: c[slot].summary) + if preferEnd ? d > distance : d >= distance { + path[0] = slot + distance = d &- distance + return true + } + distance &-= d + slot &-= 1 + } + return false + } +} + extension _Rope.Node { func seekForward( from i: inout Index, @@ -311,26 +368,20 @@ extension _Rope.Node { preferEnd: Bool ) -> Bool { assert(distance >= 0) - var slot = i[height: height] - precondition(slot < childCount, "Invalid index") - + if height == 0 { - return readLeaf { - let c = $0.children - while slot < c.count { - let d = metric.nonnegativeSize(of: c[slot].summary) - if preferEnd ? d >= distance : d > distance { - i[height: 0] = slot - return true - } - distance &-= d - slot &+= 1 - } - return false + let r = readLeaf { + $0._seekForwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd) } + if r { + i._leaf = asUnmanagedLeaf + } + return r } return readInner { + var slot = i._path[height] + precondition(slot < childCount, "Invalid index") let c = $0.children if c[slot].seekForward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) { return true @@ -339,7 +390,7 @@ extension _Rope.Node { while slot < c.count { let d = metric.size(of: c[slot].summary) if preferEnd ? d >= distance : d > distance { - i[height: $0.height] = slot + i._path[$0.height] = slot i.clear(below: $0.height) let success = c[slot].seekForward( from: &i, by: &distance, in: metric, preferEnd: preferEnd) @@ -361,28 +412,15 @@ extension _Rope.Node { ) -> Bool { assert(distance >= 0) guard distance > 0 || preferEnd else { return true } - var slot = i[height: height] - precondition(slot <= childCount, "Invalid index") - if height == 0 { return readLeaf { - let c = $0.children - slot &-= 1 - while slot >= 0 { - let d = metric.nonnegativeSize(of: c[slot].summary) - if preferEnd ? d > distance : d >= distance { - i[height: 0] = slot - distance = d &- distance - return true - } - distance &-= d - slot &-= 1 - } - return false + $0._seekBackwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd) } } return readInner { + var slot = i._path[height] + precondition(slot <= childCount, "Invalid index") let c = $0.children if slot < childCount, c[slot].seekBackward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) { @@ -392,7 +430,7 @@ extension _Rope.Node { while slot >= 0 { let d = metric.size(of: c[slot].summary) if preferEnd ? d > distance : d >= distance { - i[height: $0.height] = slot + i._path[$0.height] = slot i.clear(below: $0.height) distance = d - distance let success = c[slot].seekForward( diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift new file mode 100644 index 00000000..d003fc01 --- /dev/null +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift @@ -0,0 +1,67 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension _Rope { + struct Index { + typealias Path = _Rope.Path + typealias Summary = _Rope.Summary + + var _version: _RopeVersion + var _path: Path + /// A direct reference to the leaf node addressed by this index. + /// This must only be dereferenced while we own a tree with a matching + /// version. + var _leaf: UnmanagedLeaf? + + init(version: _RopeVersion, path: Path, leaf: __shared UnmanagedLeaf?) { + self._version = version + self._path = path + self._leaf = leaf + } + } +} + +extension _Rope.Index: Equatable { + static func ==(left: Self, right: Self) -> Bool { + left._path == right._path + } +} +extension _Rope.Index: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(_path) + } +} + +extension _Rope.Index: Comparable { + static func <(left: Self, right: Self) -> Bool { + left._path < right._path + } +} + +extension _Rope.Index: CustomStringConvertible { + var description: String { + "\(_path)" + } +} + +extension _Rope.Index { + var height: UInt8 { + _path.height + } + + func isEmpty(below height: UInt8) -> Bool { + _path.isEmpty(below: height) + } + + mutating func clear(below height: UInt8) { + _path.clear(below: height) + } +} diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift index 3f80d56d..6fa10817 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift @@ -21,16 +21,16 @@ extension _Rope: Sequence { struct Iterator: IteratorProtocol { let rope: _Rope private(set) var index: Index - private var leaf: Node? - + init(_ rope: _Rope, from start: Index) { + rope.validate(start) self.rope = rope self.index = start - self.leaf = start == rope.endIndex ? nil : rope._leaf(at: start) + self.rope.ensureLeaf(in: &index) } var isAtEnd: Bool { - leaf == nil + index._leaf == nil } var isAtStart: Bool { @@ -38,48 +38,35 @@ extension _Rope: Sequence { } var current: Element { - leaf!.readLeaf { $0.children[index[height: 0]].value } + guard let leaf = index._leaf else { + preconditionFailure("Cannot access current element in iterator at end") + } + return leaf.read { $0.children[index._path[0]].value } } func withCurrent(_ body: (Element) -> R) -> R { - leaf!.readLeaf { body($0.children[index[height: 0]].value) } + guard let leaf = index._leaf else { + preconditionFailure("Cannot access current element in iterator at end") + } + return leaf.read { body($0.children[index._path[0]].value) } } mutating func stepForward() -> Bool { - guard let leaf = self.leaf else { return false } - self.leaf = nil - if leaf.formSuccessor(of: &index) { - self.leaf = leaf - } else if rope.root.formSuccessor(of: &index) { - self.leaf = rope._leaf(at: index) - } else { - self.leaf = leaf - return false - } + let end = rope.endPath + guard index._path < end else { return false } + let next = rope.index(after: index) + guard next._path < end else { return false } + index = next return true } mutating func stepBackward() -> Bool { - guard let leaf = self.leaf else { - guard !rope.isEmpty else { return false } - self.index = rope.index(before: rope.endIndex) - self.leaf = rope._leaf(at: index) - return true - } - self.leaf = nil - if leaf.formPredecessor(of: &index) { - self.leaf = leaf - } else if rope.root.formPredecessor(of: &index) { - self.leaf = rope._leaf(at: index) - } else { - self.leaf = leaf - return false - } + guard index._path > rope.startPath else { return false } + rope.formIndex(before: &index) return true } mutating func stepToEnd() { - leaf = nil index = rope.endIndex } @@ -95,12 +82,19 @@ extension _Rope: Sequence { } extension _Rope { - func _leaf(at index: Index) -> Node? { - assert(index.height == root.height) + func _unmanagedLeaf(at path: Path) -> UnmanagedLeaf? { + assert(path.height == self.height) + guard path < endPath else { return nil } + return root.unmanagedLeaf(at: path) + } + + func _leaf(at path: Path) -> Node? { + assert(path.height == self.height) + guard _root != nil else { return nil } var node = root while true { let h = node.height - let slot = index[height: h] + let slot = path[h] guard slot < node.childCount else { return nil } if h == 0 { break } node = node.readInner { $0.child(at: slot)! } diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Append.swift b/Sources/RopeModule/Rope/Operations/_Rope+Append.swift index 96a0421e..f0fa488a 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Append.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Append.swift @@ -11,6 +11,7 @@ extension _Rope { mutating func append(_ item: __owned Element) { + invalidateIndices() if _root == nil { _root = .createLeaf(Item(item)) return diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift index 4627b6de..3da974d9 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift @@ -14,26 +14,27 @@ extension _Rope { at position: Int, in metric: some _RopeMetric, preferEnd: Bool - ) -> (index: Index, node: Node?, remaining: Int) { + ) -> (index: Index, remaining: Int) { let wholeSize = _root == nil ? 0 : metric.size(of: root.summary) precondition(position >= 0 && position <= wholeSize, "Position out of bounds") guard preferEnd || position < wholeSize else { - return (endIndex, nil, position) + return (endIndex, position) } var position = position var node = root - var index = Index(height: node.height) + var path = Path(height: node.height) while node.height > 0 { node = node.readInner { let r = $0.findSlot(at: position, in: metric, preferEnd: preferEnd) position = r.remaining - index[height: $0.height] = r.slot + path[$0.height] = r.slot return $0.children[r.slot] } } let r = node.readLeaf { $0.findSlot(at: position, in: metric, preferEnd: preferEnd) } - index[height: 0] = r.slot - return (index, node, r.remaining) + path[0] = r.slot + let index = Index(version: _version, path: path, leaf: node.asUnmanagedLeaf) + return (index, r.remaining) } } diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift b/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift index d18a2eda..29e89588 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift @@ -11,6 +11,7 @@ extension _Rope { mutating func prepend(_ item: __owned Element) { + invalidateIndices() insert(item, at: startIndex) } @@ -18,13 +19,22 @@ extension _Rope { _ item: __owned Element, at index: Index ) { - if index == endIndex { + validate(index) + insert(item, at: index._path) + } + + mutating func insert( + _ item: __owned Element, + at path: Path + ) { + if path == endPath { append(item) return } - if let spawn = root.insert(Item(item), at: index) { + if let spawn = root.insert(Item(item), at: path) { _root = .createInner(children: root, spawn) } + invalidateIndices() } mutating func insert( @@ -39,24 +49,25 @@ extension _Rope { if let spawn = root.insert(Item(item), at: position, in: metric) { _root = .createInner(children: root, spawn) } + invalidateIndices() } } extension _Rope.Node { mutating func prepend(_ item: __owned Item) -> Self? { - insert(item, at: startIndex) + insert(item, at: startPath) } mutating func insert( _ item: __owned Item, - at index: Index + at path: Path ) -> Self? { ensureUnique() let h = height - let slot = index[height: h] + let slot = path[h] if h > 0 { precondition(slot < childCount, "Index out of bounds") - return _innerInsert(at: slot) { $0.insert(item, at: index) } + return _innerInsert(at: slot) { $0.insert(item, at: path) } } precondition(slot <= childCount, "Index out of bounds") return _leafInsert(item, at: slot) diff --git a/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift b/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift index 1243c39a..7d2c2f41 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift @@ -38,8 +38,14 @@ extension _Rope { from index: inout Index, _ body: (inout Element) -> Bool ) -> Bool { + validate(index) guard _root != nil else { return true } - return root.mutatingForEach(from: &index, body: body).continue + defer { + invalidateIndices() + index._version = _version + } + let r = root.mutatingForEach(from: &index, body: body).continue + return r } } @@ -50,7 +56,7 @@ extension _Rope.Node { ) -> (continue: Bool, delta: Summary) { ensureUnique() let h = height - var slot = index[height: h] + var slot = index._path[h] precondition(slot <= childCount, "Index out of bounds") guard slot < childCount else { return (true, .zero) } var delta = Summary.zero @@ -63,13 +69,15 @@ extension _Rope.Node { delta.add(d) guard r else { return false } slot += 1 - index.clear(below: h) - index[height: h] = slot + index._path.clear(below: h) + index._path[h] = slot } + index._leaf = nil return true } return (r, delta) } + index._leaf = asUnmanagedLeaf let r = updateLeaf { let c = $0.mutableChildren while slot < c.count { @@ -78,7 +86,7 @@ extension _Rope.Node { delta.add(c[slot].summary.subtracting(sum)) guard r else { return false } slot += 1 - index[height: h] = slot + index._path[h] = slot } return true } diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift index 96ce7809..0d7febc7 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift @@ -11,28 +11,30 @@ extension _Rope { mutating func remove(at index: Index) -> Element { - let old = root.remove(at: index).removed + validate(index) + let old = root.remove(at: index._path).removed if root.isEmpty { _root = nil } else if root.childCount == 1, root.height > 0 { root = root.readInner { $0.children.first! } } + invalidateIndices() return old.value } } extension _Rope.Node { mutating func remove( - at index: Index + at path: Path ) -> (removed: Item, delta: Summary, needsFixing: Bool) { ensureUnique() - let slot = index[height: height] + let slot = path[height] precondition(slot < childCount, "Invalid index") guard height > 0 else { let r = _removeItem(at: slot) return (r.removed, r.delta, self.isUndersized) } - let r = updateInner { $0.mutableChildren[slot].remove(at: index) } + let r = updateInner { $0.mutableChildren[slot].remove(at: path) } self.summary.subtract(r.delta) if r.needsFixing { fixDeficiency(at: slot) @@ -46,6 +48,7 @@ extension _Rope { at position: Int, in metric: some _RopeMetric ) -> Element { + invalidateIndices() let old = root.remove(at: position, in: metric).removed if root.isEmpty { _root = nil diff --git a/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift b/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift index 32eccf76..3e90164b 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift @@ -14,6 +14,7 @@ extension _Rope { _ bounds: Range, in metric: some _RopeMetric ) { + invalidateIndices() precondition( bounds.lowerBound >= 0 && bounds.upperBound <= count(in: metric), "Position out of bounds") @@ -31,6 +32,7 @@ extension _Rope { // FIXME: Implement insert(contentsOf:at:in:) and dispatch to it when bounds.isEmpty. // FIXME: Add fast path for replacing tiny ranges with tiny data. // FIXME: Add special cases if newElements is itself a _Rope etc. + invalidateIndices() var builder = builder(removing: bounds, in: metric) for item in newElements { builder.append(item) @@ -42,6 +44,7 @@ extension _Rope { removing bounds: Range, in metric: some _RopeMetric ) -> Builder { + invalidateIndices() let size = metric.size(of: summary) precondition( bounds.lowerBound >= 0 && bounds.upperBound <= size, diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Split.swift b/Sources/RopeModule/Rope/Operations/_Rope+Split.swift index b7b21ee9..ae270c90 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Split.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Split.swift @@ -14,6 +14,7 @@ extension _Rope { splittingAt position: Int, in metric: some _RopeMetric ) -> Builder { + invalidateIndices() var builder = Builder() var position = position @@ -35,20 +36,22 @@ extension _Rope { } mutating func split(at index: Index) -> (builder: Builder, item: Element) { + validate(index) precondition(index < endIndex) var builder = Builder() var node = root _root = nil while !node.isLeaf { - let slot = index[height: node.height] + let slot = index._path[node.height] precondition(slot < node.childCount, "Index out of bounds") node._innerSplit(at: slot, into: &builder) } - let slot = index[height: node.height] + let slot = index._path[node.height] precondition(slot < node.childCount, "Index out of bounds") let item = node._leafSplit(at: slot, into: &builder) + invalidateIndices() return (builder, item.value) } diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index aeaafcb9..326f423c 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -150,8 +150,17 @@ class TestRope: XCTestCase { Chunk(length: ($0 % 4) + 1, value: $0) } let rope = _Rope(ref) - XCTAssertTrue(rope.elementsEqual(ref)) - + + var it = rope.makeIterator() + var i = 0 + while let next = it.next() { + let expected = ref[i] + XCTAssertEqual(next, expected) + guard next == expected else { break } + i += 1 + } + XCTAssertEqual(i, ref.count) + let expectedLength = ref.reduce(into: 0) { $0 += $1.length } let actualLength = rope.reduce(into: 0) { $0 += $1.length } XCTAssertEqual(actualLength, expectedLength) diff --git a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme index 19a77614..c487bb69 100644 --- a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme +++ b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme @@ -20,6 +20,20 @@ ReferencedContainer = "container:.."> + + + + Date: Mon, 20 Feb 2023 16:50:14 -0800 Subject: [PATCH 030/113] Replace Rope iterator with indices in most index-like use cases --- .../BString/Basics/_BString+Contents.swift | 34 ++++-- .../BString/Basics/_BString+Iterators.swift | 114 ++++++++++-------- .../Operations/_BString+Initializers.swift | 8 +- .../Operations/_BString+Managing Breaks.swift | 53 ++++---- .../Rope/Conformances/_Rope+Sequence.swift | 49 +------- 5 files changed, 123 insertions(+), 135 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 9bc335ec..04c8e545 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -273,7 +273,7 @@ extension _BString { precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") guard offset > 0, offset < utf8Count else { return Index(_utf8Offset: offset) } - let (path, chunk) = path(to: i, preferEnd: true) + var (path, chunk) = path(to: i, preferEnd: true) var base = baseIndex(with: i, at: path.chunk) if chunk.hasBreaks { let first = chunk.firstBreak @@ -290,12 +290,14 @@ extension _BString { } } - var it = self.rope.makeIterator(from: path.rope) - while it.stepBackward() { - base = base._advanceUTF8(by: -it.current.utf8Count) - if it.current.hasBreaks { break } + var i = path.rope + while i > self.rope.startIndex { + self.rope.formIndex(before: &i) + chunk = self.rope[i] + base = base._advanceUTF8(by: -chunk.utf8Count) + if chunk.hasBreaks { break } } - return base._advanceUTF8(by: it.current.string._utf8Offset(of: it.current.lastBreak)) + return base._advanceUTF8(by: chunk.lastBreak._utf8Offset) } func unicodeScalarIndex(roundingDown i: Index) -> Index { @@ -337,15 +339,23 @@ extension _BString { } var s = String(c) var base = base - var it = self.rope.makeIterator(from: start.rope) + var i = start.rope + var j = start.chunk while true { - base = base?._advanceUTF8(by: it.current.utf8Count) - guard it.stepForward() else { break } - let chunk = it.current + base = base?._advanceUTF8(by: rope[i].utf8Count) + rope.formIndex(after: &i) + guard i < rope.endIndex else { + j = "".endIndex + break + } + let chunk = rope[i] s.append(contentsOf: chunk.prefix) - if chunk.hasBreaks { break } + if chunk.hasBreaks { + j = rope[i].firstBreak + break + } } - return (Character(s), Path(it.index, it.current.firstBreak), base) + return (Character(s), Path(i, j), base) } subscript(utf8 index: Index) -> UInt8 { diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index e914fbef..0c31e6ad 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -146,21 +146,23 @@ extension _BString.UnicodeScalarIterator: IteratorProtocol { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct CharacterIterator { - internal var _base: _Rope.Iterator + internal let _base: _BString + internal var _i: Rope.Index internal var _utf8BaseOffset: Int internal var _index: String.Index internal var _next: String.Index internal init(_ string: _BString) { + self._base = string + self._i = string.rope.startIndex self._utf8BaseOffset = 0 - self._base = string.rope.makeIterator() - guard !_base.isAtEnd else { + guard _i < string.rope.endIndex else { _index = "".startIndex _next = "".endIndex return } - let chunk = _base.current + let chunk = _base.rope[_i] assert(chunk.firstBreak == chunk.string.startIndex) self._index = chunk.firstBreak self._next = chunk.string[_index...].index(after: _index) @@ -170,19 +172,20 @@ extension _BString { _ string: _BString, from start: Index ) { + self._base = string self._utf8BaseOffset = start._utf8Offset if start == string.endIndex { - self._base = string.rope.makeIterator(from: string.rope.endIndex) + self._i = string.rope.endIndex self._index = "".startIndex self._next = "".endIndex return } let path = string.path(to: start, preferEnd: false).path - self._base = string.rope.makeIterator(from: path.rope) + self._i = path.rope self._utf8BaseOffset -= path.chunk._utf8Offset self._index = path.chunk - self._next = _base.current.wholeCharacters.index(after: path.chunk) + self._next = _base.rope[_i].wholeCharacters.index(after: path.chunk) } } @@ -204,53 +207,55 @@ extension _BString.CharacterIterator: IteratorProtocol { } internal var isAtStart: Bool { - _base.isAtStart && _index._utf8Offset == 0 + _i == _base.rope.startIndex && _index._utf8Offset == 0 } internal var current: Element { assert(!isAtEnd) - var r = _base.withCurrent { chunk -> (str: String, done: Bool) in - assert(_index >= chunk.firstBreak) - return (String(chunk.string[_index ..< _next]), _next < chunk.string.endIndex) + let chunk = _base.rope[_i] + var str = String(chunk.string[_index ..< _next]) + if _next < chunk.string.endIndex { return Character(str) } + + var i = _base.rope.index(after: _i) + while i < _base.rope.endIndex { + let chunk = _base.rope[i] + let b = chunk.firstBreak + str += chunk.string[.. Bool { guard !isAtEnd else { return false } - let chunk = _base.current + let chunk = _base.rope[_i] if _next < chunk.string.endIndex { _index = _next _next = chunk.wholeCharacters.index(after: _next) return true } - while true { - let c = _base.current.utf8Count - guard _base.stepForward() else { break } - _utf8BaseOffset += c - let chunk = _base.current - let i = chunk.firstBreak - if i < chunk.string.endIndex { - _index = i - _next = chunk.string[i...].index(after: i) + var baseOffset = _utf8BaseOffset + chunk.utf8Count + var i = _base.rope.index(after: _i) + while i < _base.rope.endIndex { + let chunk = _base.rope[i] + let b = chunk.firstBreak + if b < chunk.string.endIndex { + _i = i + _utf8BaseOffset = baseOffset + _index = b + _next = chunk.string[b...].index(after: b) return true } + baseOffset += chunk.utf8Count + _base.rope.formIndex(after: &i) } return false } mutating func stepBackward() -> Bool { if !isAtEnd { - let chunk = _base.current + let chunk = _base.rope[_i] let i = chunk.firstBreak if _index > i { _next = _index @@ -258,15 +263,21 @@ extension _BString.CharacterIterator: IteratorProtocol { return true } } - while _base.stepBackward() { - let chunk = _base.current - _utf8BaseOffset -= chunk.utf8Count + var i = _i + var baseOffset = _utf8BaseOffset + while i > _base.rope.startIndex { + _base.rope.formIndex(before: &i) + let chunk = _base.rope[i] + baseOffset -= chunk.utf8Count if chunk.hasBreaks { + _i = i + _utf8BaseOffset = baseOffset _next = chunk.string.endIndex _index = chunk.lastBreak return true } } + assert(_base.rope.isEmpty) return false } @@ -287,37 +298,38 @@ extension _BString.CharacterIterator { _utf8BaseOffset + _index._utf8Offset } + var index: _BString.Index { + _BString.Index(_utf8Offset: utf8Offset) + } + /// The UTF-8 offset range of the current character, measured from the start of the string. var utf8Range: Range { assert(!isAtEnd) let start = utf8Offset var end = _utf8BaseOffset - if _next < _base.current.string.endIndex { + var chunk = _base.rope[_i] + if _next < chunk.string.endIndex { end += _next._utf8Offset return Range(uncheckedBounds: (start, end)) } - var it = _base - while true { - end += it.current.utf8Count - guard it.stepForward() else { break } - let chunk = it.current - let i = chunk.firstBreak - if i < chunk.string.endIndex { - end += i._utf8Offset + end += chunk.utf8Count + var i = _base.rope.index(after: _i) + while i < _base.rope.endIndex { + chunk = _base.rope[i] + let b = chunk.firstBreak + if b < chunk.string.endIndex { + end += b._utf8Offset break } + end += chunk.utf8Count + _base.rope.formIndex(after: &i) } return Range(uncheckedBounds: (start, end)) } - var index: _BString.Index { - let utf8Base = _base.rope.offset(of: _base.index, in: _BString.UTF8Metric()) - return _BString.Index(_utf8Offset: utf8Base + _index._utf8Offset) - } - func isBelow(_ path: _BString.Path) -> Bool { - if self._base.index < path.rope { return true } - guard self._base.index == path.rope else { return false } + if _i < path.rope { return true } + guard _i == path.rope else { return false } return self._index < path.chunk } } diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index 7e16118a..9f98ce64 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -118,10 +118,10 @@ extension String { } self += start.chunk.string[start.path.chunk...] - - var it = big.rope.makeIterator(from: start.path.rope) - while it.stepForward(), it.index < end.path.rope { - self += it.current.string + var i = big.rope.index(after: start.path.rope) + while i < end.path.rope { + self += big.rope[i].string + big.rope.formIndex(after: &i) } self += end.chunk.string[.. rope.startIndex { + rope.formIndex(before: &i) + if rope[i].hasBreaks { break } } - precondition(it.index < end.rope) - let prev = Path(it.index, it.current.lastBreak) + precondition(i < end.rope) + let prev = Path(i, rope[i].lastBreak) // Collect grapheme breaking state. - var state = _CharacterRecognizer(partialCharacter: it.current.suffix) - while it.stepForward(), it.index < end.rope { - state.consumePartialCharacter(it.current.string[...]) + var state = _CharacterRecognizer(partialCharacter: rope[i].suffix) + rope.formIndex(after: &i) + while i < end.rope { + state.consumePartialCharacter(rope[i].string[...]) + rope.formIndex(after: &i) } - state.consumePartialCharacter(it.current.string[.. 0 { - var it = makeIterator(from: endIndex) - while it.stepBackward() { - if it.current.hasBreaks { break } - if it.index == index { break } + var i = endIndex + while i > startIndex { + formIndex(before: &i) + if self[i].hasBreaks { break } + if i == index { break } } - if it.index > index || it.current.lastBreak > i { - new = it.current.immediateLastBreakState! - while it.stepForward() { - new.consumePartialCharacter(it.current.string[...]) + if i > index || self[i].lastBreak > stringIndex { + new = self[i].immediateLastBreakState! + formIndex(after: &i) + while i < endIndex { + new.consumePartialCharacter(self[i].string[...]) + formIndex(after: &i) } old = new return } } - var it = makeIterator(from: index) - let suffix = it.current.string.unicodeScalars[i...].dropFirst() + + var i = index + let suffix = self[i].string.unicodeScalars[stringIndex...].dropFirst() new.consumePartialCharacter(suffix) - while it.stepForward() { - new.consumePartialCharacter(it.current.string[...]) + formIndex(after: &i) + while i < endIndex { + new.consumePartialCharacter(self[i].string[...]) + formIndex(after: &i) } old = new } diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift index 6fa10817..58600513 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift @@ -29,53 +29,10 @@ extension _Rope: Sequence { self.rope.ensureLeaf(in: &index) } - var isAtEnd: Bool { - index._leaf == nil - } - - var isAtStart: Bool { - index == rope.startIndex - } - - var current: Element { - guard let leaf = index._leaf else { - preconditionFailure("Cannot access current element in iterator at end") - } - return leaf.read { $0.children[index._path[0]].value } - } - - func withCurrent(_ body: (Element) -> R) -> R { - guard let leaf = index._leaf else { - preconditionFailure("Cannot access current element in iterator at end") - } - return leaf.read { body($0.children[index._path[0]].value) } - } - - mutating func stepForward() -> Bool { - let end = rope.endPath - guard index._path < end else { return false } - let next = rope.index(after: index) - guard next._path < end else { return false } - index = next - return true - } - - mutating func stepBackward() -> Bool { - guard index._path > rope.startPath else { return false } - rope.formIndex(before: &index) - return true - } - - mutating func stepToEnd() { - index = rope.endIndex - } - mutating func next() -> Element? { - guard !isAtEnd else { return nil } - let item = self.current - if !stepForward() { - stepToEnd() - } + guard let leaf = index._leaf else { return nil } + let item = leaf.read { $0.children[index._path[0]].value } + rope.formIndex(after: &index) return item } } From 575937f6ff1011efddc9aba2ab5b2bbde0c51d97 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Feb 2023 17:00:59 -0800 Subject: [PATCH 031/113] Remove _Rope._leaf(at:) --- .../RopeModule/Rope/Basics/_Rope+Node.swift | 12 +++++++++- .../Rope/Conformances/_Rope+Sequence.swift | 22 ------------------- 2 files changed, 11 insertions(+), 23 deletions(-) diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Node.swift b/Sources/RopeModule/Rope/Basics/_Rope+Node.swift index e5352e6c..1a3d56cc 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Node.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+Node.swift @@ -365,7 +365,17 @@ extension _Rope.Node { } return asUnmanagedLeaf } - +} + +extension _Rope { + func _unmanagedLeaf(at path: Path) -> UnmanagedLeaf? { + assert(path.height == self.height) + guard path < endPath else { return nil } + return root.unmanagedLeaf(at: path) + } +} + +extension _Rope.Node { var asUnmanagedLeaf: UnmanagedLeaf { assert(height == 0) return UnmanagedLeaf(unsafeDowncast(self.object, to: Storage.self)) diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift index 58600513..ac7ed686 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift @@ -37,25 +37,3 @@ extension _Rope: Sequence { } } } - -extension _Rope { - func _unmanagedLeaf(at path: Path) -> UnmanagedLeaf? { - assert(path.height == self.height) - guard path < endPath else { return nil } - return root.unmanagedLeaf(at: path) - } - - func _leaf(at path: Path) -> Node? { - assert(path.height == self.height) - guard _root != nil else { return nil } - var node = root - while true { - let h = node.height - let slot = path[h] - guard slot < node.childCount else { return nil } - if h == 0 { break } - node = node.readInner { $0.child(at: slot)! } - } - return node - } -} From 79bdcb66eb3154f7c96ac15a97be08ee3703cc2d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Feb 2023 16:50:13 -0800 Subject: [PATCH 032/113] Implement path caching in indices --- .../BString/Basics/_BString+Contents.swift | 229 +++++++++--------- .../BString/Basics/_BString+Index.swift | 201 +++++++++------ .../BString/Basics/_BString+Ingester.swift | 6 +- .../BString/Basics/_BString+Iterators.swift | 29 ++- .../BString/Basics/_BString+Path.swift | 92 ------- .../_BString+Chunk+Indexing by UTF16.swift | 5 +- .../BString/Chunk/_BString+Chunk.swift | 1 - .../Conformances/_BString+Comparisons.swift | 9 +- .../BString/Operations/_BString+Append.swift | 11 +- .../Operations/_BString+Initializers.swift | 42 ++-- .../BString/Operations/_BString+Insert.swift | 18 +- .../Operations/_BString+Managing Breaks.swift | 125 +++++----- .../Operations/_BString+RemoveSubrange.swift | 24 +- .../Operations/_BString+ReplaceSubrange.swift | 4 +- .../BString/Operations/_BString+Split.swift | 17 +- .../RopeModule/Rope/Basics/_RopePath.swift | 4 + .../Rope/Conformances/_Rope+Index.swift | 10 + .../Utilities/_CharacterRecognizer.swift | 9 +- 18 files changed, 410 insertions(+), 426 deletions(-) delete mode 100644 Sources/RopeModule/BString/Basics/_BString+Path.swift diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 04c8e545..f78f24f7 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -66,15 +66,24 @@ extension _BString { precondition(start <= endIndex && end <= endIndex, "Invalid index") guard start != end else { return 0 } assert(!isEmpty) - let a = path(to: Swift.min(start, end), preferEnd: false) - let b = path(to: Swift.max(start, end), preferEnd: true) - if a.path.rope == b.path.rope { - return metric.distance(from: a.path.chunk, to: b.path.chunk, in: a.chunk) - } + let a = resolve(Swift.min(start, end), preferEnd: false) + let b = resolve(Swift.max(start, end), preferEnd: true) var d = 0 - d += rope.distance(from: a.path.rope, to: b.path.rope, in: metric) - d -= metric.distance(from: a.chunk.string.startIndex, to: a.path.chunk, in: a.chunk) - d += metric.distance(from: b.chunk.string.startIndex, to: b.path.chunk, in: b.chunk) + + let ropeIndexA = a._rope! + let ropeIndexB = b._rope! + let chunkIndexA = a._chunkIndex + let chunkIndexB = b._chunkIndex + + if ropeIndexA == ropeIndexB { + d = metric.distance(from: chunkIndexA, to: chunkIndexB, in: rope[ropeIndexA]) + } else { + let chunkA = rope[ropeIndexA] + let chunkB = rope[ropeIndexB] + d += rope.distance(from: ropeIndexA, to: ropeIndexB, in: metric) + d -= metric.distance(from: chunkA.string.startIndex, to: chunkIndexA, in: chunkA) + d += metric.distance(from: chunkB.string.startIndex, to: chunkIndexB, in: chunkB) + } return start <= end ? d : -d } @@ -139,70 +148,45 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - func _path( - _ i: Index, - offsetBy distance: Int, - in metric: some _StringMetric - ) -> (path: Path, chunk: Chunk) { - var (path, chunk) = path(to: i, preferEnd: false) - var d = distance - let r = metric.formIndex(&path.chunk, offsetBy: &d, in: chunk) - if r.found { - return (path, chunk) - } - - if r.forward { - assert(distance >= 0) - assert(path.chunk == chunk.string.endIndex) - d += metric.nonnegativeSize(of: chunk.summary) - rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false) - precondition(path.rope < rope.endIndex) - chunk = rope[path.rope] - path.chunk = metric.index(at: d, in: chunk) - return (path, chunk) - } - - assert(distance <= 0) - assert(path.chunk == chunk.string.startIndex) - rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false) - chunk = rope[path.rope] - path.chunk = metric.index(at: d, in: chunk) - return (path, chunk) - } - func index( _ i: Index, offsetBy distance: Int, in metric: some _StringMetric ) -> Index { precondition(i <= endIndex, "Index out of bounds") - var (path, chunk) = path(to: i, preferEnd: i == endIndex || distance < 0) - let base = baseIndex(with: i, at: path.chunk) + let i = resolve(i, preferEnd: i == endIndex || distance < 0) + var ri = i._rope! + var ci = i._chunkIndex var d = distance - let r = metric.formIndex(&path.chunk, offsetBy: &d, in: chunk) + var chunk = rope[ri] + let r = metric.formIndex(&ci, offsetBy: &d, in: chunk) if r.found { - return index(base: base, offsetBy: path.chunk) + return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: ci) } - + if r.forward { assert(distance >= 0) - assert(path.chunk == chunk.string.endIndex) + assert(ci == chunk.string.endIndex) d += metric.nonnegativeSize(of: chunk.summary) - rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false) - if path.rope == rope.endIndex { - return Index(_utf8Offset: self.utf8Count) + let start = ri + rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false) + if ri == rope.endIndex { + return endIndex } - chunk = rope[path.rope] - path.chunk = metric.index(at: d, in: chunk) - return index(of: path) + chunk = rope[ri] + ci = metric.index(at: d, in: chunk) + let base = i._utf8BaseOffset + rope.distance(from: start, to: ri, in: UTF8Metric()) + return Index(baseUTF8Offset: base, rope: ri, chunk: ci) } - + assert(distance <= 0) - assert(path.chunk == chunk.string.startIndex) - rope.formIndex(&path.rope, offsetBy: &d, in: metric, preferEnd: false) - chunk = rope[path.rope] - path.chunk = metric.index(at: d, in: chunk) - return index(of: path) + assert(ci == chunk.string.startIndex) + let start = ri + rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false) + chunk = rope[ri] + ci = metric.index(at: d, in: chunk) + let base = i._utf8BaseOffset + rope.distance(from: start, to: ri, in: UTF8Metric()) + return Index(baseUTF8Offset: base, rope: ri, chunk: ci) } func characterIndex(_ i: Index, offsetBy distance: Int) -> Index { @@ -271,51 +255,57 @@ extension _BString { func characterIndex(roundingDown i: Index) -> Index { let offset = i._utf8Offset precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") - guard offset > 0, offset < utf8Count else { return Index(_utf8Offset: offset) } + guard offset > 0 else { return resolve(i, preferEnd: false) } + guard offset < utf8Count else { return resolve(i, preferEnd: true) } - var (path, chunk) = path(to: i, preferEnd: true) - var base = baseIndex(with: i, at: path.chunk) + let i = resolve(i, preferEnd: true) + var ri = i._rope! + let ci = i._chunkIndex + var chunk = rope[ri] if chunk.hasBreaks { let first = chunk.firstBreak let last = chunk.lastBreak - if path.chunk == first || path.chunk == last { - return i + if ci == first || ci == last { return i } + if ci > last { + return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: last) } - if path.chunk > chunk.lastBreak { - return base._advanceUTF8(by: chunk.string._utf8Offset(of: chunk.lastBreak)) - } - if path.chunk > chunk.firstBreak { - let j = chunk.string._index(roundingDown: path.chunk) - return base._advanceUTF8(by: chunk.string._utf8Offset(of: j)) + if ci > first { + let j = chunk.wholeCharacters._index(roundingDown: ci) + return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: j) } } - var i = path.rope - while i > self.rope.startIndex { - self.rope.formIndex(before: &i) - chunk = self.rope[i] - base = base._advanceUTF8(by: -chunk.utf8Count) + var baseOffset = i._utf8BaseOffset + while ri > self.rope.startIndex { + self.rope.formIndex(before: &ri) + chunk = self.rope[ri] + baseOffset -= chunk.utf8Count if chunk.hasBreaks { break } } - return base._advanceUTF8(by: chunk.lastBreak._utf8Offset) + return Index(baseUTF8Offset: baseOffset, rope: ri, chunk: chunk.lastBreak) } func unicodeScalarIndex(roundingDown i: Index) -> Index { precondition(i <= endIndex, "Index out of bounds") - guard i > startIndex, i < endIndex else { return Index(_utf8Offset: i._utf8Offset) } - let (path, chunk) = path(to: i, preferEnd: true) - let j = chunk.string.unicodeScalars._index(roundingDown: path.chunk) - return i._advanceUTF8(by: j._utf8Offset - path.chunk._utf8Offset) + guard i > startIndex else { return resolve(i, preferEnd: false) } + guard i < endIndex else { return endIndex } + + let start = self.resolve(i, preferEnd: false) + let ri = start._rope! + let chunk = self.rope[ri] + let ci = chunk.string.unicodeScalars._index(roundingDown: start._chunkIndex) + return Index(baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: ci) } func utf8Index(roundingDown i: Index) -> Index { precondition(i <= endIndex, "Index out of bounds") - // Clear any UTF-16 offset - return Index(_utf8Offset: i._utf8Offset) + var r = i + r._clearUTF16TrailingSurrogate() + return r } func utf16Index(roundingDown i: Index) -> Index { - if i._utf16Delta > 0 { + if i._isUTF16TrailingSurrogate { precondition(i <= endIndex, "Index out of bounds") return i } @@ -325,83 +315,80 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - func _character( - at start: Path, base: Index?, in chunk: Chunk - ) -> (character: Character, end: Path, base: Index?) { - let offset = chunk.string._utf8Offset(of: start.chunk) - let c = chunk.string[start.chunk] - let d = c.utf8.count - if offset + d < chunk.utf8Count { - return ( - character: c, - end: Path(start.rope, chunk.string._utf8Index(at: offset + d)), - base: base) + func _character(at start: Index) -> (character: Character, end: Index) { + precondition(start._utf8Offset < utf8Count, "Index out of bounds") + let start = resolve(start, preferEnd: false) + var ri = start._rope! + var ci = start._chunkIndex + var chunk = rope[ri] + let char = chunk.string[ci] + let endOffset = start._utf8ChunkOffset + char.utf8.count + if endOffset < chunk.utf8Count { + let endIndex = chunk.string._utf8Index(at: endOffset) + return (char, Index(baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: endIndex)) } - var s = String(c) - var base = base - var i = start.rope - var j = start.chunk + var s = String(char) + var base = start._utf8BaseOffset + chunk.utf8Count while true { - base = base?._advanceUTF8(by: rope[i].utf8Count) - rope.formIndex(after: &i) - guard i < rope.endIndex else { - j = "".endIndex + rope.formIndex(after: &ri) + guard ri < rope.endIndex else { + ci = "".endIndex break } - let chunk = rope[i] + chunk = rope[ri] s.append(contentsOf: chunk.prefix) if chunk.hasBreaks { - j = rope[i].firstBreak + ci = chunk.firstBreak break } + base += chunk.utf8Count } - return (Character(s), Path(i, j), base) + return (Character(s), Index(baseUTF8Offset: base, rope: ri, chunk: ci)) } subscript(utf8 index: Index) -> UInt8 { precondition(index < endIndex, "Index out of bounds") - let (path, chunk) = path(to: index, preferEnd: false) - return chunk.string.utf8[path.chunk] + let index = resolve(index, preferEnd: false) + return rope[index._rope!].string.utf8[index._chunkIndex] } subscript(utf8 offset: Int) -> UInt8 { - let (path, chunk) = _path(startIndex, offsetBy: offset, in: UTF8Metric()) - return chunk.string.utf8[path.chunk] + precondition(offset >= 0 && offset < utf8Count, "Offset out of bounds") + let index = utf8Index(at: offset) + return self[utf8: index] } subscript(utf16 index: Index) -> UInt16 { precondition(index < endIndex, "Index out of bounds") - let (path, chunk) = path(to: index, preferEnd: false) - return chunk.string.utf16[path.chunk] + let index = resolve(index, preferEnd: false) + return rope[index._rope!].string.utf16[index._chunkIndex] } subscript(utf16 offset: Int) -> UInt16 { - let (path, chunk) = _path(startIndex, offsetBy: offset, in: UTF16Metric()) - return chunk.string.utf16[path.chunk] + precondition(offset >= 0 && offset < utf16Count, "Offset out of bounds") + let index = utf16Index(at: offset) + return self[utf16: index] } subscript(character index: Index) -> Character { - precondition(index < endIndex, "Index out of bounds") - let (path, chunk) = path(to: index, preferEnd: false) - let base = baseIndex(with: index, at: path.chunk) - return _character(at: path, base: base, in: chunk).character + _character(at: index).character } subscript(character offset: Int) -> Character { - let (path, chunk) = _path(startIndex, offsetBy: offset, in: CharacterMetric()) - return _character(at: path, base: nil, in: chunk).character + precondition(offset >= 0 && offset < utf8Count, "Offset out of bounds") + return _character(at: Index(_utf8Offset: offset)).character } subscript(unicodeScalar index: Index) -> Unicode.Scalar { precondition(index < endIndex, "Index out of bounds") - let (path, chunk) = path(to: index, preferEnd: false) - return chunk.string.unicodeScalars[path.chunk] + let index = resolve(index, preferEnd: false) + return rope[index._rope!].string.unicodeScalars[index._chunkIndex] } subscript(unicodeScalar offset: Int) -> Unicode.Scalar { precondition(offset >= 0 && offset < unicodeScalarCount, "Offset out of bounds") - let (path, chunk) = _path(startIndex, offsetBy: offset, in: UnicodeScalarMetric()) - return chunk.string.unicodeScalars[path.chunk] + let index = unicodeScalarIndex(at: offset) + return self[unicodeScalar: index] } } diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift index ef649833..eb5bd871 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -14,55 +14,54 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct Index { - // The layout is similar to (and somewhat compatible with) String.Index. - // ┌──────────┬────────────────┬───────────────────────┐ - // │ b63:b16 │ b15:b14 │ b13:b0 │ - // ├──────────┼────────────────┼───────────────────────┤ - // │ position │ transc. offset │ reserved │ - // └──────────┴────────────────┴───────────────────────┘ - - internal var _rawBits: UInt64 - - internal init(_raw: UInt64) { + typealias Rope = _BString.Rope + + // ┌─────────────────────┬──────────────┬────────────────────┐ + // │ b63:b9 │ b8 │ b7:b0 │ + // ├─────────────────────┼──────────────┼────────────────────┤ + // │ UTF-8 global offset │ UTF-16 delta │ UTF-8 chunk offset │ + // └─────────────────────┴──────────────┴────────────────────┘ + var _rawBits: UInt64 + + /// A (possibly invalid) rope index. + var _rope: Rope.Index? + + internal init(_raw: UInt64, rope: Rope.Index?) { self._rawBits = _raw + self._rope = rope } } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index { + internal var _utf8Offset: Int { + Int(truncatingIfNeeded: _rawBits &>> 9) + } + + internal var _isUTF16TrailingSurrogate: Bool { + _orderingValue & 1 != 0 + } + + /// The base offset of the addressed chunk. Only valid if `_rope` is not nil. + internal var _utf8BaseOffset: Int { + _utf8Offset - _utf8ChunkOffset + } + + /// The offset within the addressed chunk. Only valid if `_rope` is not nil. + internal var _utf8ChunkOffset: Int { + assert(_rope != nil) + return Int(truncatingIfNeeded: _rawBits & 0xFF) + } + + internal var _chunkIndex: String.Index { + assert(_rope != nil) + return String.Index(_utf8Offset: _utf8ChunkOffset, utf16Delta: _isUTF16TrailingSurrogate ? 1 : 0) + } + @inline(__always) internal var _orderingValue: UInt64 { - _rawBits &>> 14 - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { - left._orderingValue == right._orderingValue - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index: Comparable { - internal static func <(left: Self, right: Self) -> Bool { - left._orderingValue < right._orderingValue - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index: Hashable { - internal func hash(into hasher: inout Hasher) { - hasher.combine(_orderingValue) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index: CustomStringConvertible { - internal var description: String { - let offset = _utf16Delta == 0 ? "" : "+\(_utf16Delta)" - return "\(_utf8Offset)[utf8]\(offset)" + _rawBits &>> 8 } } @@ -71,36 +70,102 @@ extension _BString.Index { @inline(__always) internal static func _bitsForUTF8Offset(_ utf8Offset: Int) -> UInt64 { let v = UInt64(truncatingIfNeeded: UInt(bitPattern: utf8Offset)) - assert(v &>> 48 == 0) - return v &<< 16 - } - - @inline(__always) - internal static func _bitsForUTF16Delta(_ utf16Delta: Int) -> UInt64 { - let v = UInt64(truncatingIfNeeded: UInt(bitPattern: utf16Delta)) - assert(v == v & 1) - return (v & 1) &<< 14 - } - - internal init(_utf8Offset: Int) { - _rawBits = Self._bitsForUTF8Offset(_utf8Offset) - } - - internal init(_utf8Offset: Int, utf16Delta: Int) { - _rawBits = Self._bitsForUTF8Offset(_utf8Offset) - _rawBits |= Self._bitsForUTF16Delta(utf16Delta) - } - - internal var _utf8Offset: Int { - Int(truncatingIfNeeded: _rawBits &>> 16) - } - - internal var _utf16Delta: Int { - Int(truncatingIfNeeded: _orderingValue & 0x3) + assert(v &>> 55 == 0) + return v &<< 9 } - internal func _advanceUTF8(by delta: Int) -> Self { - Self(_utf8Offset: _utf8Offset + delta) + @inline(__always) + internal static var _utf16TrailingSurrogateBits: UInt64 { 0x100 } + + internal mutating func _clearUTF16TrailingSurrogate() { + _rawBits &= ~Self._utf16TrailingSurrogateBits + } + + internal init(_utf8Offset: Int) { + _rawBits = Self._bitsForUTF8Offset(_utf8Offset) + _rope = nil + } + + internal init(_utf8Offset: Int, utf16TrailingSurrogate: Bool) { + _rawBits = Self._bitsForUTF8Offset(_utf8Offset) + if utf16TrailingSurrogate { + _rawBits |= Self._utf16TrailingSurrogateBits + } + _rope = nil + } + + internal init( + _utf8Offset: Int, utf16TrailingSurrogate: Bool = false, rope: Rope.Index, chunkOffset: Int + ) { + _rawBits = Self._bitsForUTF8Offset(_utf8Offset) + if utf16TrailingSurrogate { + _rawBits |= Self._utf16TrailingSurrogateBits + } + assert(chunkOffset >= 0 && chunkOffset <= 0xFF) + _rawBits |= UInt64(truncatingIfNeeded: chunkOffset) & 0xFF + self._rope = rope + } + + internal init(baseUTF8Offset: Int, rope: Rope.Index, chunk: String.Index) { + let chunkUTF8Offset = chunk._utf8Offset + self.init( + _utf8Offset: baseUTF8Offset + chunkUTF8Offset, + utf16TrailingSurrogate: chunk._utf16Delta > 0, + rope: rope, + chunkOffset: chunkUTF8Offset) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.Index: Equatable { + static func ==(left: Self, right: Self) -> Bool { + left._orderingValue == right._orderingValue + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.Index: Comparable { + static func <(left: Self, right: Self) -> Bool { + left._orderingValue < right._orderingValue + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.Index: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(_orderingValue) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.Index: CustomStringConvertible { + internal var description: String { + let utf16Offset = _isUTF16TrailingSurrogate ? "+1" : "" + return "\(_utf8Offset)[utf8]\(utf16Offset)" + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + func resolve(_ i: Index, preferEnd: Bool) -> Index { + if var ri = i._rope, rope.isValid(ri) { + if preferEnd { + guard i._utf8ChunkOffset == 0 else { return i } + rope.formIndex(before: &ri) + let length = rope[ri].utf8Count + let ci = String.Index(_utf8Offset: length) + return Index(baseUTF8Offset: i._utf8Offset - length, rope: ri, chunk: ci) + } + guard i._utf8ChunkOffset == rope[ri].utf8Count else { return i } + rope.formIndex(after: &ri) + let ci = String.Index(_utf8Offset: 0) + return Index(baseUTF8Offset: i._utf8Offset, rope: ri, chunk: ci) + } + + let (ri, chunkOffset) = rope.find( + at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) + let ci = String.Index(_utf8Offset: chunkOffset, utf16Delta: i._isUTF16TrailingSurrogate ? 1 : 0) + return Index(baseUTF8Offset: i._utf8Offset - ci._utf8Offset, rope: ri, chunk: ci) } } diff --git a/Sources/RopeModule/BString/Basics/_BString+Ingester.swift b/Sources/RopeModule/BString/Basics/_BString+Ingester.swift index 2bb9c36b..7950e810 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Ingester.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Ingester.swift @@ -17,10 +17,10 @@ extension _BString { forInserting input: __owned Substring, at index: Index, allowForwardPeek: Bool - ) -> (ingester: Ingester, start: Path, end: Path) { + ) -> Ingester { let hint = allowForwardPeek ? input.unicodeScalars.first : nil - let r = self._breakState(upTo: index, nextScalarHint: hint) - return (Ingester(input, startState: r.state), r.start, r.end) + let state = self._breakState(upTo: index, nextScalarHint: hint) + return Ingester(input, startState: state) } } diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index 0c31e6ad..4224d20c 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -119,10 +119,12 @@ extension _BString { } internal func makeUnicodeScalarIterator(from index: Index) -> UnicodeScalarIterator { - let (path, chunk) = self.path(to: index, preferEnd: false) - var base = self.rope.makeIterator(from: path.rope) + let i = resolve(index, preferEnd: index == endIndex) + let ropeIndex = i._rope! + let chunkIndex = i._chunkIndex + var base = self.rope.makeIterator(from: ropeIndex) _ = base.next() - return UnicodeScalarIterator(_base: base, chunk, path.chunk) + return UnicodeScalarIterator(_base: base, rope[ropeIndex], chunkIndex) } } @@ -181,11 +183,11 @@ extension _BString { self._next = "".endIndex return } - let path = string.path(to: start, preferEnd: false).path - self._i = path.rope - self._utf8BaseOffset -= path.chunk._utf8Offset - self._index = path.chunk - self._next = _base.rope[_i].wholeCharacters.index(after: path.chunk) + let i = string.resolve(start, preferEnd: false) + self._i = i._rope! + self._utf8BaseOffset = i._utf8BaseOffset + self._index = i._chunkIndex + self._next = _base.rope[_i].wholeCharacters.index(after: _index) } } @@ -327,10 +329,13 @@ extension _BString.CharacterIterator { return Range(uncheckedBounds: (start, end)) } - func isBelow(_ path: _BString.Path) -> Bool { - if _i < path.rope { return true } - guard _i == path.rope else { return false } - return self._index < path.chunk + func isBelow(_ index: _BString.Index) -> Bool { + assert(index._rope != nil) + let ropeIndex = index._rope! + let chunkIndex = index._chunkIndex + if _i < ropeIndex { return true } + guard _i == ropeIndex else { return false } + return self._index < chunkIndex } } diff --git a/Sources/RopeModule/BString/Basics/_BString+Path.swift b/Sources/RopeModule/BString/Basics/_BString+Path.swift deleted file mode 100644 index d6946c62..00000000 --- a/Sources/RopeModule/BString/Basics/_BString+Path.swift +++ /dev/null @@ -1,92 +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 { - struct Path { - var rope: Rope.Index - var _chunk: UInt16 - - init(startOf rope: Rope.Index) { - self.rope = rope - self._chunk = 0 - } - - init(_ rope: Rope.Index, _ chunk: String.Index) { - self.rope = rope - self._chunk = chunk._chunkData - } - - var chunk: String.Index { - get { - String.Index(_chunkData: _chunk) - } - set { - _chunk = newValue._chunkData - } - _modify { - var index = self.chunk - defer { - self.chunk = index - } - yield &index - } - } - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Path: CustomStringConvertible { - var description: String { - "\(rope).\(chunk._description)" - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - func path( - to i: Index, - preferEnd: Bool - ) -> (path: Path, chunk: Chunk) { - let (ropeIndex, remaining) = rope.find( - at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) - let chunk = rope[ropeIndex] - let chunkIndex = chunk.index(at: remaining, utf16Delta: i._utf16Delta) - return (Path(ropeIndex, chunkIndex), chunk) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - func baseIndex( - with index: Index, - at chunkIndex: String.Index - ) -> Index { - Index(_utf8Offset: index._utf8Offset - chunkIndex._utf8Offset) - } - - func index(base: Index, offsetBy index: String.Index) -> Index { - assert(index._canBeUTF8) - return Index( - _utf8Offset: base._utf8Offset + index._utf8Offset, - utf16Delta: index._utf16Delta) - } - - func index(of path: Path) -> Index { - let position = rope.distance(from: rope.startIndex, to: path.rope, in: UTF8Metric()) - let base = Index(_utf8Offset: position) - return index(base: base, offsetBy: path.chunk) - } -} - -#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift index 45473005..0982ab6d 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift @@ -14,14 +14,13 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Chunk { /// UTF-16 index lookup. - func index(at utf8Offset: Int, utf16Delta: Int) -> String.Index { + func index(at utf8Offset: Int, utf16TrailingSurrogate: Bool) -> String.Index { var index = string._utf8Index(at: utf8Offset) if - utf16Delta != 0, + utf16TrailingSurrogate, index < string.endIndex, string.utf8[index]._isUTF8NonBMPLeadingCodeUnit { - assert(utf16Delta == 1) index = string.utf16.index(after: index) } return index diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift index 09c25757..584315d2 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift @@ -15,7 +15,6 @@ extension _BString { struct Chunk { typealias Slice = (string: Substring, characters: Int, prefix: Int, suffix: Int) - typealias Path = _BString.Path var string: String var counts: Counts diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift index 3ab28258..3b519600 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift @@ -56,12 +56,12 @@ extension _BString { // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. var it1 = left.makeCharacterIterator(from: leftRange.lowerBound) - var it2 = right.makeCharacterIterator(from: rightRange.upperBound) + var it2 = right.makeCharacterIterator(from: rightRange.lowerBound) if leftRange._isEmptyUTF8 { return rightRange._isEmptyUTF8 } - let leftEnd = left.path(to: leftRange.upperBound, preferEnd: true).path - let rightEnd = right.path(to: rightRange.upperBound, preferEnd: true).path + let leftEnd = left.resolve(leftRange.upperBound, preferEnd: true) + let rightEnd = right.resolve(rightRange.upperBound, preferEnd: true) var a: Character? = nil var b: Character? = nil @@ -81,8 +81,7 @@ extension _BString { // 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 true } - guard self.characterCount == other.characterCount else { return false } + 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() diff --git a/Sources/RopeModule/BString/Operations/_BString+Append.swift b/Sources/RopeModule/BString/Operations/_BString+Append.swift index 8ad1e8ad..d0ebc487 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Append.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Append.swift @@ -27,7 +27,7 @@ extension _BString { self = Self(other) return } - var ingester = ingester(forInserting: other, at: endIndex, allowForwardPeek: true).ingester + var ingester = ingester(forInserting: other, at: endIndex, allowForwardPeek: true) let last = rope.index(before: rope.endIndex) if let final = rope[last].append(from: &ingester) { @@ -66,7 +66,7 @@ extension _BString { let hint = other._firstUnicodeScalar var other = other.rope var old = _CharacterRecognizer() - var new = self._breakState(upTo: endIndex, nextScalarHint: hint).state + var new = self._breakState(upTo: endIndex, nextScalarHint: hint) _ = other.resyncBreaks(old: &old, new: &new) _append(other) } @@ -81,7 +81,7 @@ extension _BString { var other = _BString(other, in: range) let hint = other._firstUnicodeScalar var old = _CharacterRecognizer() - var new = self._breakState(upTo: endIndex, nextScalarHint: hint).state + var new = self._breakState(upTo: endIndex, nextScalarHint: hint) _ = other.rope.resyncBreaks(old: &old, new: &new) _append(other.rope) } @@ -94,9 +94,8 @@ extension _BString { } let hint = self._firstUnicodeScalar var old = _CharacterRecognizer() - var new = other._breakState(upTo: other.endIndex, nextScalarHint: hint).state + var new = other._breakState(upTo: other.endIndex, nextScalarHint: hint) _ = self.rope.resyncBreaks(old: &old, new: &new) - _prepend(other.rope) } @@ -109,7 +108,7 @@ extension _BString { } let hint = self._firstUnicodeScalar var old = _CharacterRecognizer() - var new = extract._breakState(upTo: extract.endIndex, nextScalarHint: hint).state + var new = extract._breakState(upTo: extract.endIndex, nextScalarHint: hint) _ = self.rope.resyncBreaks(old: &old, new: &new) _prepend(extract.rope) } diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index 9f98ce64..da2fefb0 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -58,7 +58,7 @@ extension _BString { from: range.lowerBound._utf8Offset, to: range.upperBound._utf8Offset, in: UTF8Metric()) - var old = other._breakState(upTo: range.lowerBound).state + var old = other._breakState(upTo: range.lowerBound) var new = _CharacterRecognizer() _ = self.rope.resyncBreaks(old: &old, new: &new) } @@ -72,7 +72,7 @@ extension _BString { from: range.lowerBound._utf8Offset, to: range.upperBound._utf8Offset, in: UTF8Metric()) - var old = other._breakState(upTo: range.lowerBound).state + var old = other._breakState(upTo: range.lowerBound) var new = state self.rope.resyncBreaksToEnd(old: &old, new: &new) } @@ -98,32 +98,32 @@ extension String { internal init(_from big: _BString, in range: Range<_BString.Index>) { self.init() - let estimatedUTF8Size = range.upperBound._utf8Offset - range.lowerBound._utf8Offset - guard estimatedUTF8Size > 0 else { - // We can safely ignore UTF-16 offsets, as we're rounding down to scalar boundaries - // anyway. - return - } - // Note: if the range isn't scalar aligned, then this may be slightly under- or overestimating - // the actual size of the result. (Underestimations can be problematic due to String's - // exponential resizing. If those become an issue, consider adding +3 here.) - self.reserveCapacity(estimatedUTF8Size) - let start = big.path(to: range.lowerBound, preferEnd: false) - let end = big.path(to: range.upperBound, preferEnd: true) - - if start.path.rope == end.path.rope { - self += start.chunk.string[start.path.chunk ..< end.path.chunk] + var start = big.unicodeScalarIndex(roundingDown: range.lowerBound) + start = big.resolve(start, preferEnd: false) + + var end = big.unicodeScalarIndex(roundingDown: range.upperBound) + end = big.resolve(end, preferEnd: true) + + let utf8Capacity = end._utf8Offset - start._utf8Offset + guard utf8Capacity > 0 else { return } + + self.reserveCapacity(utf8Capacity) + + let startRopeIndex = start._rope! + let endRopeIndex = end._rope! + if startRopeIndex == endRopeIndex { + self += big.rope[startRopeIndex].string[start._chunkIndex ..< end._chunkIndex] return } - self += start.chunk.string[start.path.chunk...] - var i = big.rope.index(after: start.path.rope) - while i < end.path.rope { + self += big.rope[startRopeIndex].string[start._chunkIndex...] + var i = big.rope.index(after: startRopeIndex) + while i < endRopeIndex { self += big.rope[i].string big.rope.formIndex(after: &i) } - self += end.chunk.string[.. (prevBreak: Path, state: _CharacterRecognizer) { - guard end.rope > rope.startIndex || end._chunk > 0 else { - return (Path(startOf: rope.startIndex), _CharacterRecognizer()) + ) -> _CharacterRecognizer { + assert(index == unicodeScalarIndex(roundingDown: index)) + guard index > startIndex else { + return _CharacterRecognizer() + } + let index = resolve(index, preferEnd: true) + let ropeIndex = index._rope! + let chunkIndex = index._chunkIndex + let chunk = rope[ropeIndex] + + guard ropeIndex > rope.startIndex || chunkIndex > chunk.string.startIndex else { + return _CharacterRecognizer() } - if let next = nextScalarHint, end.chunk > chunk.string.startIndex { - let i = chunk.string.unicodeScalars.index(before: end.chunk) + if let next = nextScalarHint, chunkIndex > chunk.string.startIndex { + let i = chunk.string.unicodeScalars.index(before: chunkIndex) let prev = chunk.string.unicodeScalars[i] if _CharacterRecognizer.quickBreak(between: prev, and: next) == true { - return (end, _CharacterRecognizer()) + return _CharacterRecognizer() } } - if let r = chunk.immediateBreakState(upTo: end.chunk) { - return (Path(end.rope, r.prevBreak), r.state) + if let r = chunk.immediateBreakState(upTo: chunkIndex) { + return r.state } // Find chunk that includes the start of the character. - var i = end.rope - while i > rope.startIndex { - rope.formIndex(before: &i) - if rope[i].hasBreaks { break } + var ri = ropeIndex + while ri > rope.startIndex { + rope.formIndex(before: &ri) + if rope[ri].hasBreaks { break } } - precondition(i < end.rope) - let prev = Path(i, rope[i].lastBreak) + precondition(ri < ropeIndex) // Collect grapheme breaking state. - var state = _CharacterRecognizer(partialCharacter: rope[i].suffix) - rope.formIndex(after: &i) - while i < end.rope { - state.consumePartialCharacter(rope[i].string[...]) - rope.formIndex(after: &i) + var state = _CharacterRecognizer(partialCharacter: rope[ri].suffix) + rope.formIndex(after: &ri) + while ri < ropeIndex { + state.consumePartialCharacter(rope[ri].string[...]) + rope.formIndex(after: &ri) } - state.consumePartialCharacter(rope[end.rope].string[.. (start: Path, end: Path, state: _CharacterRecognizer) { - guard index > startIndex else { - let dummy = Path(startOf: rope.startIndex) - return (dummy, dummy, _CharacterRecognizer()) - } - let end = path(to: index, preferEnd: true) - let r = _breakState(upTo: end.path, in: end.chunk, nextScalarHint: nextScalarHint) - return (r.prevBreak, end.path, r.state) + state.consumePartialCharacter(chunk.string[.. Path? { + ) -> (ropeIndex: Rope.Index, chunkIndex: String.Index)? { guard index < endIndex else { return nil } - let p = path(to: index, preferEnd: false).path - var path = (rope: p.rope, chunk: p.chunk) - - let end = rope.mutatingForEach(from: &path.rope) { chunk in - let start = path.chunk - path.chunk = "".startIndex - return chunk.resyncBreaks(startingAt: start, old: &old, new: &new) + let i = resolve(index, preferEnd: false) + var ropeIndex = i._rope! + var chunkIndex = i._chunkIndex + let end = rope.mutatingForEach(from: &ropeIndex) { chunk in + let start = chunkIndex + chunkIndex = String.Index(_utf8Offset: 0) + if let i = chunk.resyncBreaks(startingAt: start, old: &old, new: &new) { + return i + } + return nil } guard let end else { return nil } - path.chunk = end - return Path(path.rope, path.chunk) + return (ropeIndex, end) } mutating func resyncBreaksToEnd( @@ -97,7 +93,7 @@ extension _BString { new: inout _CharacterRecognizer ) { guard let _ = resyncBreaks(startingAt: index, old: &old, new: &new) else { return } - let state = _breakState(upTo: endIndex).state + let state = _breakState(upTo: endIndex) old = state new = state } @@ -109,40 +105,35 @@ extension _BString.Rope { old: inout _CharacterRecognizer, new: inout _CharacterRecognizer ) -> Bool { - var index = startIndex - let r = self.mutatingForEach(from: &index) { - $0.resyncBreaksFromStart(old: &old, new: &new) - } - return r != nil + _resyncBreaks(old: &old, new: &new) != nil } mutating func _resyncBreaks( old: inout _CharacterRecognizer, new: inout _CharacterRecognizer - ) -> (path: Index, String.Index)? { - var index = startIndex - let r = self.mutatingForEach(from: &index) { + ) -> (ropeIndex: Index, chunkIndex: String.Index)? { + var ropeIndex = startIndex + let chunkIndex = self.mutatingForEach(from: &ropeIndex) { $0.resyncBreaksFromStart(old: &old, new: &new) } - guard let r else { return nil } - return (index, r) + guard let chunkIndex else { return nil } + return (ropeIndex, chunkIndex) } mutating func resyncBreaksToEnd( old: inout _CharacterRecognizer, new: inout _CharacterRecognizer ) { - guard let (index, stringIndex) = _resyncBreaks(old: &old, new: &new) else { return } + guard let (ropeIndex, chunkIndex) = _resyncBreaks(old: &old, new: &new) else { return } let chars = self.summary.characters if chars > 0 { var i = endIndex - while i > startIndex { + while i > ropeIndex { formIndex(before: &i) if self[i].hasBreaks { break } - if i == index { break } } - if i > index || self[i].lastBreak > stringIndex { + if i > ropeIndex || self[i].lastBreak > chunkIndex { new = self[i].immediateLastBreakState! formIndex(after: &i) while i < endIndex { @@ -154,13 +145,13 @@ extension _BString.Rope { } } - var i = index - let suffix = self[i].string.unicodeScalars[stringIndex...].dropFirst() + var ri = ropeIndex + let suffix = self[ri].string.unicodeScalars[chunkIndex...].dropFirst() new.consumePartialCharacter(suffix) - formIndex(after: &i) - while i < endIndex { - new.consumePartialCharacter(self[i].string[...]) - formIndex(after: &i) + formIndex(after: &ri) + while ri < endIndex { + new.consumePartialCharacter(self[ri].string[...]) + formIndex(after: &ri) } old = new } diff --git a/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift index ef6ffbce..d2c57039 100644 --- a/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift +++ b/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift @@ -25,22 +25,22 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { mutating func removeCharacter(at i: Index) -> Character { - let (start, chunk) = self.path(to: i, preferEnd: false) - let startBase = baseIndex(with: i, at: start.chunk) - let (character, end, endBase) = self._character(at: start, base: startBase, in: chunk) - let j = endBase!._advanceUTF8(by: end.chunk._utf8Offset) - self.removeSubrange(i ..< j) + let start = self.resolve(i, preferEnd: false) + let (character, end) = self._character(at: start) + self.removeSubrange(start ..< end) return character } mutating func removeUnicodeScalar(at i: Index) -> Unicode.Scalar { - let (path, chunk) = self.path(to: i, preferEnd: false) - assert(path.chunk < chunk.string.endIndex) - let base = baseIndex(with: i, at: path.chunk) - let scalar = chunk.string.unicodeScalars[path.chunk] - let end = chunk.string.unicodeScalars.index(after: path.chunk) - let j = index(base: base, offsetBy: end) - self.removeSubrange(i ..< j) + precondition(i < endIndex, "Index out of bounds") + let start = unicodeScalarIndex(roundingDown: i) + let ropeIndex = start._rope! + let chunkIndex = start._chunkIndex + let chunk = rope[ropeIndex] + let scalar = chunk.string.unicodeScalars[chunkIndex] + let next = chunk.string.unicodeScalars.index(after: chunkIndex) + let end = Index(baseUTF8Offset: start._utf8BaseOffset, rope: ropeIndex, chunk: next) + self.removeSubrange(start ..< end) return scalar } } diff --git a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift index 754e664c..7801ed1a 100644 --- a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift +++ b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift @@ -64,8 +64,8 @@ extension _BString { // FIXME: Don't split the indices twice -- they are currently split once here and once in the // builder initializer below. - let startState = _breakState(upTo: range.lowerBound).state - let endState = _breakState(upTo: range.upperBound).state + let startState = _breakState(upTo: range.lowerBound) + let endState = _breakState(upTo: range.upperBound) let b = rope.builder(removing: lower ..< upper, in: UTF8Metric()) return Builder(base: b, prefixEndState: startState, suffixStartState: endState) diff --git a/Sources/RopeModule/BString/Operations/_BString+Split.swift b/Sources/RopeModule/BString/Operations/_BString+Split.swift index e38675fa..694e0c96 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Split.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Split.swift @@ -16,20 +16,27 @@ extension _BString { mutating func split( at index: Index ) -> Builder { - let b = rope.builder(splittingAt: index._utf8Offset, in: UTF8Metric()) + let b = _ropeBuilder(at: index) let state = b.breakState() let builder = Builder(base: b, prefixEndState: state, suffixStartState: state) return builder } - - mutating func _split( - at path: Path, + + mutating func split( + at index: Index, state: _CharacterRecognizer ) -> Builder { - let b = rope.split(at: path.rope, path.chunk) + let b = _ropeBuilder(at: index) let builder = Builder(base: b, prefixEndState: state, suffixStartState: state) return builder } + + mutating func _ropeBuilder(at index: Index) -> Rope.Builder { + if let ri = index._rope, rope.isValid(ri) { + return rope.split(at: ri, index._chunkIndex) + } + return rope.builder(splittingAt: index._utf8Offset, in: UTF8Metric()) + } } #endif diff --git a/Sources/RopeModule/Rope/Basics/_RopePath.swift b/Sources/RopeModule/Rope/Basics/_RopePath.swift index a6cc8d01..13b4dce2 100644 --- a/Sources/RopeModule/Rope/Basics/_RopePath.swift +++ b/Sources/RopeModule/Rope/Basics/_RopePath.swift @@ -20,6 +20,10 @@ struct _RopePath { @inline(__always) static var _pathBitWidth: Int { 56 } + init(_value: UInt64) { + self._value = _value + } + init(height: UInt8) { self._value = UInt64(truncatingIfNeeded: height) assert((Int(height) + 1) * Summary.nodeSizeBitWidth <= Self._pathBitWidth) diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift index d003fc01..ac904dc9 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift @@ -29,6 +29,16 @@ extension _Rope { } } +extension _Rope.Index { + static var invalid: Self { + Self(version: _RopeVersion(0), path: _RopePath(_value: .max), leaf: nil) + } + + var isValid: Bool { + _path._value != .max + } +} + extension _Rope.Index: Equatable { static func ==(left: Self, right: Self) -> Bool { left._path == right._path diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift index faab4ef3..a095b9d2 100644 --- a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -72,7 +72,14 @@ extension _CharacterRecognizer { init(partialCharacter: Substring) { self.init(partialCharacter: partialCharacter.unicodeScalars) } - + + mutating func consumePartialCharacter(_ s: String) { + for scalar in s.unicodeScalars { + let b = hasBreak(before: scalar) + assert(!b) + } + } + mutating func consumePartialCharacter(_ s: Substring) { for scalar in s.unicodeScalars { let b = hasBreak(before: scalar) From 9bbdfdc49791d59233e24e3694c8007ae4ced496 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Feb 2023 17:19:48 -0800 Subject: [PATCH 033/113] Cosmetic updates to _BString.CharacterIterator --- .../BString/Basics/_BString+Iterators.swift | 77 ++++++++++--------- 1 file changed, 39 insertions(+), 38 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index 4224d20c..7fe9cf3c 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -149,25 +149,26 @@ extension _BString.UnicodeScalarIterator: IteratorProtocol { extension _BString { internal struct CharacterIterator { internal let _base: _BString - internal var _i: Rope.Index - internal var _utf8BaseOffset: Int - internal var _index: String.Index + internal var _ropeIndex: Rope.Index + internal var _chunkIndex: String.Index internal var _next: String.Index internal init(_ string: _BString) { self._base = string - self._i = string.rope.startIndex + self._ropeIndex = string.rope.startIndex + string.rope.ensureLeaf(in: &_ropeIndex) + self._utf8BaseOffset = 0 - guard _i < string.rope.endIndex else { - _index = "".startIndex + guard _ropeIndex < string.rope.endIndex else { + _chunkIndex = "".startIndex _next = "".endIndex return } - let chunk = _base.rope[_i] + let chunk = _base.rope[_ropeIndex] assert(chunk.firstBreak == chunk.string.startIndex) - self._index = chunk.firstBreak - self._next = chunk.string[_index...].index(after: _index) + self._chunkIndex = chunk.firstBreak + self._next = chunk.string[_chunkIndex...].index(after: _chunkIndex) } internal init( @@ -178,16 +179,16 @@ extension _BString { self._utf8BaseOffset = start._utf8Offset if start == string.endIndex { - self._i = string.rope.endIndex - self._index = "".startIndex + self._ropeIndex = string.rope.endIndex + self._chunkIndex = "".startIndex self._next = "".endIndex return } let i = string.resolve(start, preferEnd: false) - self._i = i._rope! + self._ropeIndex = i._rope! self._utf8BaseOffset = i._utf8BaseOffset - self._index = i._chunkIndex - self._next = _base.rope[_i].wholeCharacters.index(after: _index) + self._chunkIndex = i._chunkIndex + self._next = _base.rope[_ropeIndex].wholeCharacters.index(after: _chunkIndex) } } @@ -205,20 +206,20 @@ extension _BString.CharacterIterator: IteratorProtocol { internal typealias Element = Character internal var isAtEnd: Bool { - _index == _next + _chunkIndex == _next } internal var isAtStart: Bool { - _i == _base.rope.startIndex && _index._utf8Offset == 0 + _ropeIndex == _base.rope.startIndex && _chunkIndex._utf8Offset == 0 } internal var current: Element { assert(!isAtEnd) - let chunk = _base.rope[_i] - var str = String(chunk.string[_index ..< _next]) + let chunk = _base.rope[_ropeIndex] + var str = String(chunk.string[_chunkIndex ..< _next]) if _next < chunk.string.endIndex { return Character(str) } - var i = _base.rope.index(after: _i) + var i = _base.rope.index(after: _ropeIndex) while i < _base.rope.endIndex { let chunk = _base.rope[i] let b = chunk.firstBreak @@ -231,21 +232,21 @@ extension _BString.CharacterIterator: IteratorProtocol { mutating func stepForward() -> Bool { guard !isAtEnd else { return false } - let chunk = _base.rope[_i] + let chunk = _base.rope[_ropeIndex] if _next < chunk.string.endIndex { - _index = _next + _chunkIndex = _next _next = chunk.wholeCharacters.index(after: _next) return true } var baseOffset = _utf8BaseOffset + chunk.utf8Count - var i = _base.rope.index(after: _i) + var i = _base.rope.index(after: _ropeIndex) while i < _base.rope.endIndex { let chunk = _base.rope[i] let b = chunk.firstBreak if b < chunk.string.endIndex { - _i = i + _ropeIndex = i _utf8BaseOffset = baseOffset - _index = b + _chunkIndex = b _next = chunk.string[b...].index(after: b) return true } @@ -257,25 +258,25 @@ extension _BString.CharacterIterator: IteratorProtocol { mutating func stepBackward() -> Bool { if !isAtEnd { - let chunk = _base.rope[_i] + let chunk = _base.rope[_ropeIndex] let i = chunk.firstBreak - if _index > i { - _next = _index - _index = chunk.string[i...].index(before: _index) + if _chunkIndex > i { + _next = _chunkIndex + _chunkIndex = chunk.string[i...].index(before: _chunkIndex) return true } } - var i = _i + var i = _ropeIndex var baseOffset = _utf8BaseOffset while i > _base.rope.startIndex { _base.rope.formIndex(before: &i) let chunk = _base.rope[i] baseOffset -= chunk.utf8Count if chunk.hasBreaks { - _i = i + _ropeIndex = i _utf8BaseOffset = baseOffset _next = chunk.string.endIndex - _index = chunk.lastBreak + _chunkIndex = chunk.lastBreak return true } } @@ -287,7 +288,7 @@ extension _BString.CharacterIterator: IteratorProtocol { guard !isAtEnd else { return nil } let item = self.current if !stepForward() { - _index = _next + _chunkIndex = _next } return item } @@ -297,7 +298,7 @@ extension _BString.CharacterIterator: IteratorProtocol { extension _BString.CharacterIterator { // The UTF-8 offset of the current position, from the start of the string. var utf8Offset: Int { - _utf8BaseOffset + _index._utf8Offset + _utf8BaseOffset + _chunkIndex._utf8Offset } var index: _BString.Index { @@ -309,13 +310,13 @@ extension _BString.CharacterIterator { assert(!isAtEnd) let start = utf8Offset var end = _utf8BaseOffset - var chunk = _base.rope[_i] + var chunk = _base.rope[_ropeIndex] if _next < chunk.string.endIndex { end += _next._utf8Offset return Range(uncheckedBounds: (start, end)) } end += chunk.utf8Count - var i = _base.rope.index(after: _i) + var i = _base.rope.index(after: _ropeIndex) while i < _base.rope.endIndex { chunk = _base.rope[i] let b = chunk.firstBreak @@ -333,9 +334,9 @@ extension _BString.CharacterIterator { assert(index._rope != nil) let ropeIndex = index._rope! let chunkIndex = index._chunkIndex - if _i < ropeIndex { return true } - guard _i == ropeIndex else { return false } - return self._index < chunkIndex + if _ropeIndex < ropeIndex { return true } + guard _ropeIndex == ropeIndex else { return false } + return self._chunkIndex < chunkIndex } } From 605e45b9b94948ba557b62a25e55453444e136bb Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 28 Feb 2023 14:22:43 -0800 Subject: [PATCH 034/113] _BString: Additional fixes and new functionality - New methods for rounding up indices - Sendable conformances - Fix UTF-16 strings sometimes leaking into chunks - Iterator improvements / rewrites, incl. a chunked UTF-8 buffer iterator. - Support for comparing and hashing UTF-8 slices. --- .../BString/Basics/_BString+Contents.swift | 110 +++++++++++++++-- .../BString/Basics/_BString+Index.swift | 8 +- .../BString/Basics/_BString+Iterators.swift | 113 ++++++++++++++---- .../Chunk/_BString+Chunk+CordElement.swift | 1 + .../BString/Chunk/_BString+Chunk.swift | 7 +- .../Conformances/_BString+Comparisons.swift | 69 ++++++----- .../Conformances/_BString+Hashing.swift | 55 ++++++++- .../Rope/Conformances/_Rope+Index.swift | 2 +- .../Utilities/String.Index+ABI.swift | 5 +- .../Utilities/_CharacterRecognizer.swift | 47 +++----- 10 files changed, 316 insertions(+), 101 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index f78f24f7..97ec728f 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -202,9 +202,47 @@ extension _BString { } func utf8Index(_ i: Index, offsetBy distance: Int) -> Index { - let offset = i._utf8Offset + distance - precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") - return Index(_utf8Offset: offset) + index(i, offsetBy: distance, in: UTF8Metric()) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + func index( + _ i: Index, + offsetBy distance: Int, + limitedBy limit: Index, + in metric: some _StringMetric + ) -> Index? { + // FIXME: Do we need a direct implementation? + if distance >= 0 { + if limit >= i { + let d = self.distance(from: i, to: limit, in: metric) + if d < distance { return nil } + } + } else { + if limit <= i { + let d = self.distance(from: i, to: limit, in: metric) + if d > distance { return nil } + } + } + return self.index(i, offsetBy: distance, in: metric) + } + + func characterIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + index(i, offsetBy: distance, limitedBy: limit, in: CharacterMetric()) + } + + func unicodeScalarIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + index(i, offsetBy: distance, limitedBy: limit, in: UnicodeScalarMetric()) + } + + func utf16Index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + index(i, offsetBy: distance, limitedBy: limit, in: UTF16Metric()) + } + + func utf8Index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + index(i, offsetBy: distance, limitedBy: limit, in: UTF8Metric()) } } @@ -223,9 +261,19 @@ extension _BString { } func utf8Index(after i: Index) -> Index { - let offset = i._utf8Offset + 1 - precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") - return Index(_utf8Offset: offset) + precondition(i < endIndex, "Can't advance above end index") + let i = resolve(i, preferEnd: false) + let ri = i._rope! + var ci = i._chunkIndex + var chunk = rope[ri] + chunk.string.utf8.formIndex(after: &ci) + if ci == chunk.string.endIndex { + return Index( + baseUTF8Offset: i._utf8BaseOffset + chunk.utf8Count, + rope: rope.index(after: ri), + chunk: String.Index(_utf8Offset: 0)) + } + return Index(_utf8Offset: i._utf8Offset + 1, rope: ri, chunkOffset: ci._utf8Offset) } } @@ -244,9 +292,22 @@ extension _BString { } func utf8Index(before i: Index) -> Index { - let offset = i._utf8Offset - 1 - precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") - return Index(_utf8Offset: offset) + precondition(i > startIndex, "Can't advance below start index") + let i = resolve(i, preferEnd: true) + var ri = i._rope! + let ci = i._chunkIndex + if ci._utf8Offset > 0 { + return Index( + _utf8Offset: i._utf8Offset &- 1, + rope: ri, + chunkOffset: ci._utf8Offset &- 1) + } + rope.formIndex(before: &ri) + let chunk = rope[ri] + return Index( + baseUTF8Offset: i._utf8BaseOffset - chunk.utf8Count, + rope: ri, + chunk: String.Index(_utf8Offset: chunk.utf8Count - 1)) } } @@ -313,6 +374,37 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + func characterIndex(roundingUp i: Index) -> Index { + let j = characterIndex(roundingDown: i) + if i == j { return j } + return characterIndex(after: j) + } + + func unicodeScalarIndex(roundingUp i: Index) -> Index { + let j = unicodeScalarIndex(roundingDown: i) + if i == j { return j } + return unicodeScalarIndex(after: j) + } + + func utf8Index(roundingUp i: Index) -> Index { + // Note: this orders UTF-16 trailing surrogate indices in between the first and second byte + // of the UTF-8 encoding. + let j = utf8Index(roundingDown: i) + if i == j { return j } + return utf8Index(after: j) + } + + func utf16Index(roundingUp i: Index) -> Index { + // Note: if `i` addresses some byte in the middle of a non-BMP scalar then the result will + // point to the trailing surrogate. + let j = utf16Index(roundingDown: i) + if i == j { return j } + return utf16Index(after: j) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func _character(at start: Index) -> (character: Character, end: Index) { diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift index eb5bd871..b232fd39 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal struct Index { + internal struct Index: Sendable { typealias Rope = _BString.Rope // ┌─────────────────────┬──────────────┬────────────────────┐ @@ -56,7 +56,8 @@ extension _BString.Index { internal var _chunkIndex: String.Index { assert(_rope != nil) - return String.Index(_utf8Offset: _utf8ChunkOffset, utf16Delta: _isUTF16TrailingSurrogate ? 1 : 0) + return String.Index( + _utf8Offset: _utf8ChunkOffset, utf16TrailingSurrogate: _isUTF16TrailingSurrogate) } @inline(__always) @@ -164,7 +165,8 @@ extension _BString { let (ri, chunkOffset) = rope.find( at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) - let ci = String.Index(_utf8Offset: chunkOffset, utf16Delta: i._isUTF16TrailingSurrogate ? 1 : 0) + let ci = String.Index( + _utf8Offset: chunkOffset, utf16TrailingSurrogate: i._isUTF16TrailingSurrogate) return Index(baseUTF8Offset: i._utf8Offset - ci._utf8Offset, rope: ri, chunk: ci) } } diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index 7fe9cf3c..778e5a6a 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -38,18 +38,25 @@ extension _BString.ChunkIterator: IteratorProtocol { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct UTF8Iterator { - internal var _rope: Rope.Iterator - internal var _chunk: String.UTF8View.Iterator - - internal init(_base: Rope.Iterator) { - self._rope = _base - let str = self._rope.next()?.string ?? "" - self._chunk = str.utf8.makeIterator() + internal let _base: _BString + internal var _index: _BString.Index + + internal init(_base: _BString, from index: _BString.Index) { + self._base = _base + if index < _base.endIndex { + self._index = _base.resolve(index, preferEnd: false) + } else { + self._index = index + } } } - + internal func makeUTF8Iterator() -> UTF8Iterator { - UTF8Iterator(_base: self.rope.makeIterator()) + UTF8Iterator(_base: self, from: self.startIndex) + } + + internal func makeUTF8Iterator(from index: Index) -> UTF8Iterator { + UTF8Iterator(_base: self, from: index) } } @@ -58,12 +65,56 @@ extension _BString.UTF8Iterator: IteratorProtocol { internal typealias Element = UInt8 internal mutating func next() -> UInt8? { - if let codeUnit = _chunk.next() { - return codeUnit + guard _index < _base.endIndex else { return nil } + // Hand-optimized from `_base.subscript(utf8:)` and `_base.utf8Index(after:)`. + var ri = _index._rope! + var ci = _index._chunkIndex + let chunk = _base.rope[ri] + let result = chunk.string.utf8[ci] + + chunk.string.utf8.formIndex(after: &ci) + if ci < chunk.string.endIndex { + _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) + } else { + _index = _BString.Index( + baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, + rope: _base.rope.index(after: ri), + chunk: String.Index(_utf8Offset: 0)) } - guard let chunk = _rope.next() else { return nil } - _chunk = chunk.string.utf8.makeIterator() - return _chunk.next()! + return result + } + + internal mutating func next( + maximumCount: Int, + with body: (UnsafeBufferPointer) -> (consumed: Int, result: R) + ) -> R { + guard _index < _base.endIndex else { + let r = body(UnsafeBufferPointer(start: nil, count: 0)) + precondition(r.consumed == 0) + return r.result + } + var ri = _index._rope! + var ci = _index._utf8ChunkOffset + var utf8Offset = _index._utf8Offset + var string = _base.rope[ri].string + let (haveMore, result) = string.withUTF8 { buffer in + let slice = buffer[ci...].prefix(maximumCount) + assert(!slice.isEmpty) + let (consumed, result) = body(UnsafeBufferPointer(rebasing: slice)) + precondition(consumed >= 0 && consumed <= slice.count) + utf8Offset += consumed + ci += consumed + return (ci < buffer.count, result) + } + if haveMore { + _index = _BString.Index(_utf8Offset: utf8Offset, rope: ri, chunkOffset: ci) + } else { + _index = _BString.Index( + baseUTF8Offset: _index._utf8BaseOffset + string.utf8.count, + rope: _base.rope.index(after: ri), + chunk: String.Index(_utf8Offset: 0)) + } + return result } } @@ -280,7 +331,6 @@ extension _BString.CharacterIterator: IteratorProtocol { return true } } - assert(_base.rope.isEmpty) return false } @@ -302,7 +352,27 @@ extension _BString.CharacterIterator { } var index: _BString.Index { - _BString.Index(_utf8Offset: utf8Offset) + _BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _chunkIndex) + } + + internal var nextIndex: _BString.Index { + assert(!isAtEnd) + let chunk = _base.rope[_ropeIndex] + if _next < chunk.string.endIndex { + return _BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _next) + } + var i = _base.rope.index(after: _ropeIndex) + var base = _utf8BaseOffset + while i < _base.rope.endIndex { + let chunk = _base.rope[i] + let b = chunk.firstBreak + if b < chunk.string.endIndex { + return _BString.Index(baseUTF8Offset: base, rope: i, chunk: b) + } + base += chunk.utf8Count + _base.rope.formIndex(after: &i) + } + return _base.endIndex } /// The UTF-8 offset range of the current character, measured from the start of the string. @@ -330,13 +400,12 @@ extension _BString.CharacterIterator { return Range(uncheckedBounds: (start, end)) } + func isAbove(_ index: _BString.Index) -> Bool { + self.utf8Offset > index._utf8Offset + } + func isBelow(_ index: _BString.Index) -> Bool { - assert(index._rope != nil) - let ropeIndex = index._rope! - let chunkIndex = index._chunkIndex - if _ropeIndex < ropeIndex { return true } - guard _ropeIndex == ropeIndex else { return false } - return self._chunkIndex < chunkIndex + self.utf8Offset < index._utf8Offset } } diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift index bd009ef5..8f704210 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift @@ -26,6 +26,7 @@ extension _BString.Chunk: _RopeElement { func invariantCheck() { #if DEBUG + precondition(string.endIndex._canBeUTF8) let c = utf8Count if c == 0 { precondition(counts == Counts(), "Non-empty counts") diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift b/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift index 584315d2..aeddaa60 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift +++ b/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift @@ -26,6 +26,7 @@ extension _BString { init(_ string: String, _ counts: Counts) { self.string = string + self.string.makeContiguousUTF8() self.counts = counts invariantCheck() } @@ -38,9 +39,9 @@ extension _BString { init(_ slice: Slice) { self.string = String(slice.string) - var slice = slice - slice.string = self.string[...] - self.counts = Counts(slice) + self.string.makeContiguousUTF8() + self.counts = Counts((self.string[...], slice.characters, slice.prefix, slice.suffix)) + invariantCheck() } } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift index 3b519600..f22ad5ac 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparisons.swift @@ -103,46 +103,61 @@ extension _BString { /// Lexicographically compare the UTF-8 representations of `left` to `right`, returning a Boolean /// value indicating whether `left` is equal to `right`. internal func utf8IsEqual(to other: Self) -> Bool { - guard self.rope.summary == other.rope.summary else { return false } if self.isIdentical(to: other) { return true } + guard self.rope.summary == other.rope.summary else { 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()?[...] ?? "" - } - guard s1.isEmpty == s2.isEmpty else { return false } - if s1.isEmpty { break } - let c = Swift.min(s1.utf8.count, s2.utf8.count) - assert(c > 0) - let stop = s1.withUTF8 { b1 in - s2.withUTF8 { b2 in - for i in 0 ..< c { - guard b1[i] == b2[i] else { - return true - } - } - return false + var it1 = self.makeUTF8Iterator() + var it2 = other.makeUTF8Iterator() + var remaining = self.utf8Count + + while remaining > 0 { + let consumed = it1.next(maximumCount: remaining) { b1 in + let consumed = it2.next(maximumCount: b1.count) { b2 in + guard b2.elementsEqual(b1.prefix(b2.count)) else { return (0, 0) } + return (b2.count, b2.count) } + return (consumed, consumed) } - if stop { return false } - s1 = s1.suffix(from: s1._utf8Index(at: c)) - s2 = s2.suffix(from: s2._utf8Index(at: c)) + guard consumed > 0 else { return false } + remaining -= consumed } return true } + internal static func utf8IsEqual( + _ left: Self, + in leftRange: Range, + to right: Self, + in rightRange: Range + ) -> Bool { + let leftUTF8Count = left.utf8Distance(from: leftRange.lowerBound, to: leftRange.upperBound) + let rightUTF8Count = right.utf8Distance(from: rightRange.lowerBound, to: rightRange.upperBound) + guard leftUTF8Count == rightUTF8Count else { return false } + + var remaining = leftUTF8Count + var it1 = left.makeUTF8Iterator(from: leftRange.lowerBound) + var it2 = right.makeUTF8Iterator(from: rightRange.lowerBound) + + while remaining > 0 { + let consumed = it1.next(maximumCount: remaining) { b1 in + let consumed = it2.next(maximumCount: b1.count) { b2 in + guard b2.elementsEqual(b1.prefix(b2.count)) else { return (0, 0) } + return (b2.count, b2.count) + } + return (consumed, consumed) + } + guard consumed > 0 else { return false } + remaining -= consumed + } + 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 { diff --git a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift index 6871c8fb..6f6e806e 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift @@ -26,7 +26,7 @@ extension _BString { } hasher.combine(0xFF as UInt8) } - + internal func hashCharacters(into hasher: inout Hasher, from range: Range) { var it = self.makeCharacterIterator(from: range.lowerBound) let endOffset = range.upperBound._utf8Offset @@ -37,10 +37,13 @@ extension _BString { s.removeSubrange(i...) } s._withNFCCodeUnits { hasher.combine($0) } + if it.utf8Offset >= endOffset { + break + } } hasher.combine(0xFF as UInt8) } - + /// Feed the UTF-8 encoding of `self` into hasher, with a terminating byte. internal func hashUTF8(into hasher: inout Hasher) { for chunk in self.rope { @@ -48,8 +51,54 @@ extension _BString { string.withUTF8 { hasher.combine(bytes: .init($0)) } - hasher.combine(0xFF as UInt8) } + hasher.combine(0xFF as UInt8) + } + + /// Feed the UTF-8 encoding of `self[start..= 0 && utf16Delta <= 1) - let transcodedOffset: UInt64 = (utf16Delta != 0 ? 1 &<< 14 : 0) + init(_utf8Offset: Int, utf16TrailingSurrogate: Bool) { + let transcodedOffset: UInt64 = (utf16TrailingSurrogate ? 1 &<< 14 : 0) self.init(_rawBits: (UInt64(_utf8Offset) &<< 16) | transcodedOffset | Self._abi_utf8Bit) } } diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift index a095b9d2..5818e1cf 100644 --- a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -19,40 +19,27 @@ extension _CharacterRecognizer { mutating func firstBreak( in str: Substring ) -> Range? { - #if true - var str = str - let scalarRange = str.withUTF8 { buffer in + let r = str.utf8.withContiguousStorageIfAvailable { buffer in self._firstBreak(inUncheckedUnsafeUTF8Buffer: buffer) } - guard let scalarRange else { return nil } - let lower = str._utf8Index(at: scalarRange.lowerBound) - let upper = str._utf8Index(at: scalarRange.upperBound) - return lower ..< upper - #else - guard !str.isEmpty else { return nil } - let c = self.string.utf8.count - if c == 0 { - // Report a break before the first scalar at start - let lower = str.startIndex - let upper = str.unicodeScalars.index(after: lower) - self.string = String(str.unicodeScalars[lower]) + if let r { + guard let scalarRange = r else { return nil } + let lower = str._utf8Index(at: scalarRange.lowerBound) + let upper = str._utf8Index(at: scalarRange.upperBound) return lower ..< upper } - - self.string += str - let i = self.string.index(after: self.string.startIndex) - if i == self.string.endIndex { return nil } - - // Keep first scalar following break; discard everything else. - let offset = self.string._utf8Offset(of: i) - precondition(offset >= c) - self.string = String(self.string.unicodeScalars[i]) - let scalarWidth = self.string.utf8.count - - let lower = str._utf8Index(at: offset - c) - let upper = str._utf8Index(at: offset - c + scalarWidth) - return lower ..< upper - #endif + guard !str.isEmpty else { return nil } + + var i = str.startIndex + while i < str.endIndex { + let next = str.unicodeScalars.index(after: i) + let scalar = str.unicodeScalars[i] + if self.hasBreak(before: scalar) { + return i ..< next + } + i = next + } + return nil } } From fe54fdaa47f36da6e7012b33c718d876724f8e72 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 28 Feb 2023 15:28:13 -0800 Subject: [PATCH 035/113] More fixes. --- .../RopeModule/BString/Basics/_BString+Contents.swift | 9 +++++++-- Sources/RopeModule/BString/Basics/_BString+Index.swift | 2 +- Sources/RopeModule/Rope/Operations/_Rope+Find.swift | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 97ec728f..20e822b7 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -154,6 +154,10 @@ extension _BString { in metric: some _StringMetric ) -> Index { precondition(i <= endIndex, "Index out of bounds") + if isEmpty { + precondition(distance == 0, "Index out of bounds") + return startIndex + } let i = resolve(i, preferEnd: i == endIndex || distance < 0) var ri = i._rope! var ci = i._chunkIndex @@ -265,7 +269,7 @@ extension _BString { let i = resolve(i, preferEnd: false) let ri = i._rope! var ci = i._chunkIndex - var chunk = rope[ri] + let chunk = rope[ri] chunk.string.utf8.formIndex(after: &ci) if ci == chunk.string.endIndex { return Index( @@ -360,9 +364,10 @@ extension _BString { func utf8Index(roundingDown i: Index) -> Index { precondition(i <= endIndex, "Index out of bounds") + guard i < endIndex else { return endIndex } var r = i r._clearUTF16TrailingSurrogate() - return r + return resolve(r, preferEnd: false) } func utf16Index(roundingDown i: Index) -> Index { diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift index b232fd39..d16c7521 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -151,7 +151,7 @@ extension _BString { func resolve(_ i: Index, preferEnd: Bool) -> Index { if var ri = i._rope, rope.isValid(ri) { if preferEnd { - guard i._utf8ChunkOffset == 0 else { return i } + guard i._utf8ChunkOffset == 0, i._utf8Offset > 0 else { return i } rope.formIndex(before: &ri) let length = rope[ri].utf8Count let ci = String.Index(_utf8Offset: length) diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift index 3da974d9..bac1fa54 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift @@ -17,7 +17,7 @@ extension _Rope { ) -> (index: Index, remaining: Int) { let wholeSize = _root == nil ? 0 : metric.size(of: root.summary) precondition(position >= 0 && position <= wholeSize, "Position out of bounds") - guard preferEnd || position < wholeSize else { + guard !isEmpty, preferEnd || position < wholeSize else { return (endIndex, position) } var position = position From 85a43d9ac6c9948eee7215f293dd4b9747958c9e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 2 Mar 2023 16:28:23 -0800 Subject: [PATCH 036/113] _BString: Add a substring types and actual collection views This is more of a technical workaround, as it allows running generic algorithms on these things. That said, we could embrace this in general, and sink the `utf8Index(after:)`, `characterIndex(before:)` etc function down into these views, instead of having them on the top level. --- .../BString/Views/_BString.UTF8View.swift | 89 +++++++++++++ .../BString/Views/_BSubstring.UTF8View.swift | 119 ++++++++++++++++++ .../BString/Views/_BSubstring.swift | 63 ++++++++++ .../Utilities/Optional Utilities.swift | 2 +- 4 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 Sources/RopeModule/BString/Views/_BString.UTF8View.swift create mode 100644 Sources/RopeModule/BString/Views/_BSubstring.UTF8View.swift create mode 100644 Sources/RopeModule/BString/Views/_BSubstring.swift diff --git a/Sources/RopeModule/BString/Views/_BString.UTF8View.swift b/Sources/RopeModule/BString/Views/_BString.UTF8View.swift new file mode 100644 index 00000000..552f1f0b --- /dev/null +++ b/Sources/RopeModule/BString/Views/_BString.UTF8View.swift @@ -0,0 +1,89 @@ +//===----------------------------------------------------------------------===// +// +// 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 UTF8View { + var _base: _BString + + @inline(__always) + init(_base: _BString) { + self._base = _base + } + } + + @inline(__always) + internal var utf8: UTF8View { + UTF8View(_base: self) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF8View: Equatable { + internal static func ==(left: Self, right: Self) -> Bool { + left._base.utf8IsEqual(to: right._base) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF8View: Hashable { + internal func hash(into hasher: inout Hasher) { + _base.hashUTF8(into: &hasher) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF8View: BidirectionalCollection { + typealias Index = _BString.Index + typealias Element = UInt8 + typealias SubSequence = _BSubstring.UTF8View + + @inline(__always) + internal var startIndex: Index { _base.startIndex } + + @inline(__always) + internal var endIndex: Index { _base.endIndex } + + @inline(__always) + internal func index(after i: Index) -> Index { + _base.utf8Index(after: i) + } + + @inline(__always) + internal func index(before i: Index) -> Index { + _base.utf8Index(before: i) + } + + @inline(__always) + internal func index(_ i: Index, offsetBy distance: Int) -> Index { + _base.utf8Index(i, offsetBy: distance) + } + + internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _base.utf8Index(i, offsetBy: distance, limitedBy: limit) + } + + internal func distance(from start: Index, to end: Index) -> Int { + _base.utf8Distance(from: start, to: end) + } + + internal subscript(position: Index) -> UInt8 { + _base[utf8: position] + } + + internal subscript(bounds: Range) -> _BSubstring.UTF8View { + _BSubstring.UTF8View(_base, in: bounds) + } +} + +#endif diff --git a/Sources/RopeModule/BString/Views/_BSubstring.UTF8View.swift b/Sources/RopeModule/BString/Views/_BSubstring.UTF8View.swift new file mode 100644 index 00000000..109341ce --- /dev/null +++ b/Sources/RopeModule/BString/Views/_BSubstring.UTF8View.swift @@ -0,0 +1,119 @@ +//===----------------------------------------------------------------------===// +// +// 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 UTF8View { + 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.utf8Index(roundingDown: bounds.lowerBound) + let upper = base.utf8Index(roundingDown: bounds.upperBound) + self._bounds = Range(uncheckedBounds: (lower, upper)) + } + + internal init(_substring: _BSubstring) { + self.init(_unchecked: _substring._base, in: _substring._bounds) + } + } + + internal var utf8: UTF8View { + UTF8View(_substring: self) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF8View { + internal var base: _BString.UTF8View { _base.utf8 } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF8View: Equatable { + internal static func ==(left: Self, right: Self) -> Bool { + _BString.utf8IsEqual(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.UTF8View: Hashable { + internal func hash(into hasher: inout Hasher) { + _base.hashUTF8(into: &hasher, from: _bounds.lowerBound, to: _bounds.upperBound) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF8View: BidirectionalCollection { + typealias Index = _BString.Index + typealias Element = UInt8 + typealias SubSequence = Self + + @inline(__always) + internal var startIndex: Index { _bounds.lowerBound } + + @inline(__always) + internal var endIndex: Index { _bounds.upperBound } + + @inline(__always) + internal func index(after i: Index) -> Index { + precondition(i < endIndex, "Can't advance above end index") + return _base.utf8Index(after: i) + } + + @inline(__always) + internal func index(before i: Index) -> Index { + precondition(i > startIndex, "Can't advance below start index") + return _base.utf8Index(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.utf8Index(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.utf8Index(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.utf8Distance(from: start, to: end) + } + + subscript(position: Index) -> UInt8 { + precondition(position >= startIndex && position < endIndex, "Index out of bounds") + return _base[utf8: position] + } + + 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.swift b/Sources/RopeModule/BString/Views/_BSubstring.swift new file mode 100644 index 00000000..849d510f --- /dev/null +++ b/Sources/RopeModule/BString/Views/_BSubstring.swift @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// +// 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, *) +struct _BSubstring { + var _base: _BString + var _bounds: Range + + init(_unchecked base: _BString, in bounds: Range) { + self._base = base + self._bounds = bounds + } + + init(_ base: _BString, in bounds: Range) { + self._base = base + // Sub-character slicing could change character boundaries in the tree, requiring + // resyncing metadata. This would not be acceptable to do during slicing, so let's + // round substring bounds down to the nearest character. + let start = base.characterIndex(roundingDown: bounds.lowerBound) + let end = base.characterIndex(roundingDown: bounds.upperBound) + self._bounds = Range(uncheckedBounds: (start, end)) + } +} + +@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 } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring { + typealias Index = _BString.Index + + internal var startIndex: Index { _bounds.lowerBound } + + internal var endIndex: Index { _bounds.upperBound } + + internal subscript(bounds: Range) -> _BSubstring { + precondition( + bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex, + "Range out of bounds") + return _BSubstring(self._base, in: bounds) + } +} + +#endif diff --git a/Sources/RopeModule/Utilities/Optional Utilities.swift b/Sources/RopeModule/Utilities/Optional Utilities.swift index fc64884f..16e8ed35 100644 --- a/Sources/RopeModule/Utilities/Optional Utilities.swift +++ b/Sources/RopeModule/Utilities/Optional Utilities.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension Optional { - mutating func _take() -> Self { + internal mutating func _take() -> Self { let r = self self = nil return r From 4f2024c44d9dcd718b5d34b23e9b5b5a4f49ab50 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 2 Mar 2023 18:32:07 -0800 Subject: [PATCH 037/113] _BString: Elaborate on the swift 5.8 dependency a bit --- Sources/RopeModule/BString/Basics/_BString.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/RopeModule/BString/Basics/_BString.swift b/Sources/RopeModule/BString/Basics/_BString.swift index cda99f64..f6220e5b 100644 --- a/Sources/RopeModule/BString/Basics/_BString.swift +++ b/Sources/RopeModule/BString/Basics/_BString.swift @@ -29,7 +29,9 @@ internal struct _BString: Sendable { #else -@available(*, unavailable, message: "_BString requires Swift 5.8") +// `_BString` depends on fixes and newly exposed functionality that landed in +// version 5.8 of the Swift Standard Library. +@available(*, unavailable, message: "_BString depends on version 5.8 of the Swift Standard Library") internal struct _BString: Sendable {} #endif From 7444bb24cb053f506f56c7891058155dfeb53250 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 6 Mar 2023 13:04:29 -0800 Subject: [PATCH 038/113] =?UTF-8?q?=5FCharacterRecognizer=20don=E2=80=99t?= =?UTF-8?q?=20use=20conformances=20that=20aren=E2=80=99t=20in=20the=20Xcod?= =?UTF-8?q?e=2014.3=20beta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BString/Basics/_BString+Builder.swift | 2 +- .../BString/Basics/_BString+Iterators.swift | 4 ++-- .../Operations/_BString+Managing Breaks.swift | 4 ++-- .../RopeModule/Utilities/_CharacterRecognizer.swift | 13 +++++++++++++ 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Builder.swift b/Sources/RopeModule/BString/Basics/_BString+Builder.swift index fd33db18..114f4387 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Builder.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Builder.swift @@ -113,7 +113,7 @@ extension _BString.Builder { } mutating func append(from ingester: inout Ingester) { - assert(ingester.state == self.prefixEndState) + //assert(ingester.state._isKnownEqual(to: self.prefixEndState)) if var prefix = base.prefix._take() { if let first = ingester.nextSlice(maxUTF8Count: prefix.value.availableSpace) { prefix.value._append(first) diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index 778e5a6a..f24e6258 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -67,7 +67,7 @@ extension _BString.UTF8Iterator: IteratorProtocol { internal mutating func next() -> UInt8? { guard _index < _base.endIndex else { return nil } // Hand-optimized from `_base.subscript(utf8:)` and `_base.utf8Index(after:)`. - var ri = _index._rope! + let ri = _index._rope! var ci = _index._chunkIndex let chunk = _base.rope[ri] let result = chunk.string.utf8[ci] @@ -93,7 +93,7 @@ extension _BString.UTF8Iterator: IteratorProtocol { precondition(r.consumed == 0) return r.result } - var ri = _index._rope! + let ri = _index._rope! var ci = _index._utf8ChunkOffset var utf8Offset = _index._utf8Offset var string = _base.rope[ri].string diff --git a/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift b/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift index 9b5e282f..80035b5c 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift @@ -193,7 +193,7 @@ extension _BString.Chunk { case (true, true): break loop // Resync complete ✨ case (false, false): - if old == new { break loop } + if old._isKnownEqual(to: new) { break loop } case (false, true): counts._characters += 1 case (true, false): @@ -259,7 +259,7 @@ extension _BString.Chunk { if i < lastBreak { new = _CharacterRecognizer(partialCharacter: string[lastBreak...]) } else { - assert(old == new) + //assert(old == new) let j = string.unicodeScalars.index(after: i) new.consumePartialCharacter(string[j...]) } diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift index 5818e1cf..7a96716e 100644 --- a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -14,6 +14,19 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) internal typealias _CharacterRecognizer = Unicode._CharacterRecognizer +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _CharacterRecognizer { + internal func _isKnownEqual(to other: Self) -> Bool { +#if swift(>=5.9) + if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { // SwiftStdlib 5.9 + return self == other + } +#endif + return false + } +} + + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _CharacterRecognizer { mutating func firstBreak( From b5e3bee275c0dd27532fde3791c8c67c51bc8cd1 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 6 Mar 2023 16:39:06 -0800 Subject: [PATCH 039/113] _BString.Index: Add alignment bits Use them to speed up index rounding. (And, somewhat questionably, subscripting.) --- .../BString/Basics/_BString+Contents.swift | 58 +++++--- .../BString/Basics/_BString+Index.swift | 128 +++++++++++++----- .../BString/Basics/_BString+Ingester.swift | 2 +- .../Utilities/String.Index+ABI.swift | 15 +- 4 files changed, 145 insertions(+), 58 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 20e822b7..6c4016e6 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -194,11 +194,11 @@ extension _BString { } func characterIndex(_ i: Index, offsetBy distance: Int) -> Index { - index(i, offsetBy: distance, in: CharacterMetric()) + index(i, offsetBy: distance, in: CharacterMetric())._knownCharacterAligned() } func unicodeScalarIndex(_ i: Index, offsetBy distance: Int) -> Index { - index(i, offsetBy: distance, in: UnicodeScalarMetric()) + index(i, offsetBy: distance, in: UnicodeScalarMetric())._knownScalarAligned() } func utf16Index(_ i: Index, offsetBy distance: Int) -> Index { @@ -234,11 +234,17 @@ extension _BString { } func characterIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - index(i, offsetBy: distance, limitedBy: limit, in: CharacterMetric()) + guard let j = index(i, offsetBy: distance, limitedBy: limit, in: CharacterMetric()) else { + return nil + } + return j._knownCharacterAligned() } func unicodeScalarIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - index(i, offsetBy: distance, limitedBy: limit, in: UnicodeScalarMetric()) + guard let j = index(i, offsetBy: distance, limitedBy: limit, in: UnicodeScalarMetric()) else { + return nil + } + return j._knownScalarAligned() } func utf16Index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { @@ -253,11 +259,11 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func characterIndex(after i: Index) -> Index { - index(i, offsetBy: 1, in: CharacterMetric()) + index(i, offsetBy: 1, in: CharacterMetric())._knownCharacterAligned() } func unicodeScalarIndex(after i: Index) -> Index { - index(i, offsetBy: 1, in: UnicodeScalarMetric()) + index(i, offsetBy: 1, in: UnicodeScalarMetric())._knownScalarAligned() } func utf16Index(after i: Index) -> Index { @@ -284,11 +290,11 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func characterIndex(before i: Index) -> Index { - index(i, offsetBy: -1, in: CharacterMetric()) + index(i, offsetBy: -1, in: CharacterMetric())._knownCharacterAligned() } func unicodeScalarIndex(before i: Index) -> Index { - index(i, offsetBy: -1, in: UnicodeScalarMetric()) + index(i, offsetBy: -1, in: UnicodeScalarMetric())._knownScalarAligned() } func utf16Index(before i: Index) -> Index { @@ -320,10 +326,12 @@ extension _BString { func characterIndex(roundingDown i: Index) -> Index { let offset = i._utf8Offset precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") - guard offset > 0 else { return resolve(i, preferEnd: false) } - guard offset < utf8Count else { return resolve(i, preferEnd: true) } + guard offset > 0 else { return resolve(i, preferEnd: false)._knownCharacterAligned() } + guard offset < utf8Count else { return resolve(i, preferEnd: true)._knownCharacterAligned() } let i = resolve(i, preferEnd: true) + guard !i._isKnownCharacterAligned else { return i } + var ri = i._rope! let ci = i._chunkIndex var chunk = rope[ri] @@ -332,11 +340,13 @@ extension _BString { let last = chunk.lastBreak if ci == first || ci == last { return i } if ci > last { - return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: last) + return Index( + baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: last + )._knownCharacterAligned() } if ci > first { let j = chunk.wholeCharacters._index(roundingDown: ci) - return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: j) + return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: j)._knownCharacterAligned() } } @@ -347,26 +357,31 @@ extension _BString { baseOffset -= chunk.utf8Count if chunk.hasBreaks { break } } - return Index(baseUTF8Offset: baseOffset, rope: ri, chunk: chunk.lastBreak) + return Index( + baseUTF8Offset: baseOffset, rope: ri, chunk: chunk.lastBreak + )._knownCharacterAligned() } func unicodeScalarIndex(roundingDown i: Index) -> Index { precondition(i <= endIndex, "Index out of bounds") - guard i > startIndex else { return resolve(i, preferEnd: false) } - guard i < endIndex else { return endIndex } + guard i > startIndex else { return resolve(i, preferEnd: false)._knownCharacterAligned() } + guard i < endIndex else { return resolve(i, preferEnd: true)._knownCharacterAligned() } let start = self.resolve(i, preferEnd: false) + guard !i._isKnownScalarAligned else { return i } let ri = start._rope! let chunk = self.rope[ri] let ci = chunk.string.unicodeScalars._index(roundingDown: start._chunkIndex) - return Index(baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: ci) + return Index(baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: ci)._knownScalarAligned() } func utf8Index(roundingDown i: Index) -> Index { precondition(i <= endIndex, "Index out of bounds") guard i < endIndex else { return endIndex } var r = i - r._clearUTF16TrailingSurrogate() + if i._isUTF16TrailingSurrogate { + r._clearUTF16TrailingSurrogate() + } return resolve(r, preferEnd: false) } @@ -421,8 +436,11 @@ extension _BString { let char = chunk.string[ci] let endOffset = start._utf8ChunkOffset + char.utf8.count if endOffset < chunk.utf8Count { - let endIndex = chunk.string._utf8Index(at: endOffset) - return (char, Index(baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: endIndex)) + let endStringIndex = chunk.string._utf8Index(at: endOffset) + let endIndex = Index( + baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: endStringIndex + )._knownCharacterAligned() + return (char, endIndex) } var s = String(char) var base = start._utf8BaseOffset + chunk.utf8Count @@ -440,7 +458,7 @@ extension _BString { } base += chunk.utf8Count } - return (Character(s), Index(baseUTF8Offset: base, rope: ri, chunk: ci)) + return (Character(s), Index(baseUTF8Offset: base, rope: ri, chunk: ci)._knownCharacterAligned()) } subscript(utf8 index: Index) -> UInt8 { diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift index d16c7521..8dca907a 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -16,11 +16,18 @@ extension _BString { internal struct Index: Sendable { typealias Rope = _BString.Rope - // ┌─────────────────────┬──────────────┬────────────────────┐ - // │ b63:b9 │ b8 │ b7:b0 │ - // ├─────────────────────┼──────────────┼────────────────────┤ - // │ UTF-8 global offset │ UTF-16 delta │ UTF-8 chunk offset │ - // └─────────────────────┴──────────────┴────────────────────┘ + // ┌───────────────────────────────┬───┬───────────┬────────────────────┐ + // │ b63:b11 │b10│ b9:b8 │ b7:b0 │ + // ├───────────────────────────────┼───┼───────────┼────────────────────┤ + // │ UTF-8 global offset │ T │ alignment │ UTF-8 chunk offset │ + // └───────────────────────────────┴───┴───────────┴────────────────────┘ + // b10 (T): UTF-16 trailing surrogate indicator + // b9: isCharacterAligned + // b8: isScalarAligned + // + // 100: UTF-16 trailing surrogate + // 001: Index known to be scalar aligned + // 011: Index known to be Character aligned var _rawBits: UInt64 /// A (possibly invalid) rope index. @@ -35,17 +42,32 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index { + @inline(__always) + internal static func _bitsForUTF8Offset(_ utf8Offset: Int) -> UInt64 { + let v = UInt64(truncatingIfNeeded: UInt(bitPattern: utf8Offset)) + assert(v &>> 53 == 0) + return v &<< 11 + } + + @inline(__always) + internal static var _flagsMask: UInt64 { 0x700 } + + @inline(__always) + internal static var _utf16TrailingSurrogateBits: UInt64 { 0x400 } + + @inline(__always) + internal static var _characterAlignmentBits: UInt64 { 0x300 } + + @inline(__always) + internal static var _scalarAlignmentBits: UInt64 { 0x100 } + internal var _utf8Offset: Int { - Int(truncatingIfNeeded: _rawBits &>> 9) + Int(truncatingIfNeeded: _rawBits &>> 11) } - internal var _isUTF16TrailingSurrogate: Bool { - _orderingValue & 1 != 0 - } - - /// The base offset of the addressed chunk. Only valid if `_rope` is not nil. - internal var _utf8BaseOffset: Int { - _utf8Offset - _utf8ChunkOffset + @inline(__always) + internal var _orderingValue: UInt64 { + _rawBits &>> 10 } /// The offset within the addressed chunk. Only valid if `_rope` is not nil. @@ -54,32 +76,71 @@ extension _BString.Index { return Int(truncatingIfNeeded: _rawBits & 0xFF) } - internal var _chunkIndex: String.Index { - assert(_rope != nil) - return String.Index( - _utf8Offset: _utf8ChunkOffset, utf16TrailingSurrogate: _isUTF16TrailingSurrogate) + /// The base offset of the addressed chunk. Only valid if `_rope` is not nil. + internal var _utf8BaseOffset: Int { + _utf8Offset - _utf8ChunkOffset } @inline(__always) - internal var _orderingValue: UInt64 { - _rawBits &>> 8 + internal var _flags: UInt64 { + get { + _rawBits & Self._flagsMask + } + set { + assert(newValue & ~Self._flagsMask == 0) + _rawBits &= ~Self._flagsMask + _rawBits |= newValue + } + } +} + +extension String.Index { + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) + func _copyingAlignmentBits(from i: _BString.Index) -> String.Index { + var bits = _abi_rawBits & ~3 + bits |= (i._flags &>> 8) & 3 + return String.Index(_rawBits: bits) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index { - @inline(__always) - internal static func _bitsForUTF8Offset(_ utf8Offset: Int) -> UInt64 { - let v = UInt64(truncatingIfNeeded: UInt(bitPattern: utf8Offset)) - assert(v &>> 55 == 0) - return v &<< 9 + internal var _chunkIndex: String.Index { + assert(_rope != nil) + return String.Index( + _utf8Offset: _utf8ChunkOffset, utf16TrailingSurrogate: _isUTF16TrailingSurrogate + )._copyingAlignmentBits(from: self) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.Index { + internal mutating func _clearUTF16TrailingSurrogate() { + _flags = 0 } - @inline(__always) - internal static var _utf16TrailingSurrogateBits: UInt64 { 0x100 } + internal var _isUTF16TrailingSurrogate: Bool { + _orderingValue & 1 != 0 + } - internal mutating func _clearUTF16TrailingSurrogate() { - _rawBits &= ~Self._utf16TrailingSurrogateBits + internal func _knownScalarAligned() -> Self { + var copy = self + copy._flags = Self._scalarAlignmentBits + return copy + } + + internal func _knownCharacterAligned() -> Self { + var copy = self + copy._flags = Self._characterAlignmentBits + return copy + } + + internal var _isKnownScalarAligned: Bool { + _rawBits & Self._scalarAlignmentBits != 0 + } + + internal var _isKnownCharacterAligned: Bool { + _rawBits & Self._characterAlignmentBits != 0 } internal init(_utf8Offset: Int) { @@ -111,7 +172,7 @@ extension _BString.Index { let chunkUTF8Offset = chunk._utf8Offset self.init( _utf8Offset: baseUTF8Offset + chunkUTF8Offset, - utf16TrailingSurrogate: chunk._utf16Delta > 0, + utf16TrailingSurrogate: chunk._isUTF16TrailingSurrogate, rope: rope, chunkOffset: chunkUTF8Offset) } @@ -155,12 +216,16 @@ extension _BString { rope.formIndex(before: &ri) let length = rope[ri].utf8Count let ci = String.Index(_utf8Offset: length) - return Index(baseUTF8Offset: i._utf8Offset - length, rope: ri, chunk: ci) + var j = Index(baseUTF8Offset: i._utf8Offset - length, rope: ri, chunk: ci) + j._flags = i._flags + return j } guard i._utf8ChunkOffset == rope[ri].utf8Count else { return i } rope.formIndex(after: &ri) let ci = String.Index(_utf8Offset: 0) - return Index(baseUTF8Offset: i._utf8Offset, rope: ri, chunk: ci) + var j = Index(baseUTF8Offset: i._utf8Offset, rope: ri, chunk: ci) + j._flags = i._flags + return j } let (ri, chunkOffset) = rope.find( @@ -170,5 +235,4 @@ extension _BString { return Index(baseUTF8Offset: i._utf8Offset - ci._utf8Offset, rope: ri, chunk: ci) } } - #endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Ingester.swift b/Sources/RopeModule/BString/Basics/_BString+Ingester.swift index 7950e810..46beb84b 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Ingester.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Ingester.swift @@ -145,7 +145,7 @@ extension String { maxUTF8Count: Int ) -> Range? { assert(maxUTF8Count >= 0) - assert(i._isScalarAligned) + assert(i._isKnownScalarAligned) guard i < limit else { return nil } let end = self.utf8.index(i, offsetBy: maxUTF8Count, limitedBy: limit) ?? limit let j = self.unicodeScalars._index(roundingDown: end) diff --git a/Sources/RopeModule/Utilities/String.Index+ABI.swift b/Sources/RopeModule/Utilities/String.Index+ABI.swift index 6c18996d..193db89d 100644 --- a/Sources/RopeModule/Utilities/String.Index+ABI.swift +++ b/Sources/RopeModule/Utilities/String.Index+ABI.swift @@ -50,15 +50,20 @@ extension String.Index { _encodingBits != Self._abi_utf16Bit } - var _isScalarAligned: Bool { + var _isKnownScalarAligned: Bool { 0 != _abi_rawBits & Self._abi_scalarAlignmentBit } - var _isCharacterAligned: Bool { + var _isKnownCharacterAligned: Bool { 0 != _abi_rawBits & Self._abi_characterAlignmentBit } - var _characterAligned: String.Index { + var _knownCharacterAligned: String.Index { + let r = _abi_rawBits | Self._abi_characterAlignmentBit | Self._abi_scalarAlignmentBit + return unsafeBitCast(r, to: String.Index.self) + } + + var _knownScalarAligned: String.Index { let r = _abi_rawBits | Self._abi_characterAlignmentBit | Self._abi_scalarAlignmentBit return unsafeBitCast(r, to: String.Index.self) } @@ -72,11 +77,11 @@ extension String.Index { } @inline(__always) - var _utf16Delta: Int { + var _isUTF16TrailingSurrogate: Bool { assert(_canBeUTF8) let r = _abi_transcodedOffset assert(r <= 1) - return r + return r > 0 } @inline(__always) From 28727f7c56bed67562a0d8471b207e45275a5101 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 6 Mar 2023 19:03:55 -0800 Subject: [PATCH 040/113] _BString: Implement views MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Having all core functionality exposed by the top-level type is not a bad idea; unfortunately substrings are tricky to get right, so it’s better to implement that out of the box. --- .../BString/Basics/_BString+Contents.swift | 10 +- .../Views/_BString+CharacterView.swift | 91 +++++++++++ .../BString/Views/_BString+UTF16View.swift | 91 +++++++++++ ...UTF8View.swift => _BString+UTF8View.swift} | 2 + .../Views/_BString+UnicodeScalarView.swift | 91 +++++++++++ .../Views/_BSubstring+CharacterView.swift | 123 +++++++++++++++ .../BString/Views/_BSubstring+UTF16View.swift | 149 ++++++++++++++++++ ...8View.swift => _BSubstring+UTF8View.swift} | 8 +- .../Views/_BSubstring+UnicodeScalarView.swift | 123 +++++++++++++++ Tests/RopeModuleTests/SampleStrings.swift | 6 +- Tests/RopeModuleTests/TestBString2.swift | 40 +++++ 11 files changed, 726 insertions(+), 8 deletions(-) create mode 100644 Sources/RopeModule/BString/Views/_BString+CharacterView.swift create mode 100644 Sources/RopeModule/BString/Views/_BString+UTF16View.swift rename Sources/RopeModule/BString/Views/{_BString.UTF8View.swift => _BString+UTF8View.swift} (98%) create mode 100644 Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift create mode 100644 Sources/RopeModule/BString/Views/_BSubstring+CharacterView.swift create mode 100644 Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift rename Sources/RopeModule/BString/Views/{_BSubstring.UTF8View.swift => _BSubstring+UTF8View.swift} (95%) create mode 100644 Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift create mode 100644 Tests/RopeModuleTests/TestBString2.swift diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 6c4016e6..9691ca71 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -40,11 +40,11 @@ extension _BString { } var startIndex: Index { - Index(_utf8Offset: 0) + Index(_utf8Offset: 0)._knownCharacterAligned() } var endIndex: Index { - Index(_utf8Offset: utf8Count) + Index(_utf8Offset: utf8Count)._knownCharacterAligned() } } @@ -158,6 +158,7 @@ extension _BString { precondition(distance == 0, "Index out of bounds") return startIndex } + if i == endIndex, distance == 0 { return i } let i = resolve(i, preferEnd: i == endIndex || distance < 0) var ri = i._rope! var ci = i._chunkIndex @@ -387,8 +388,9 @@ extension _BString { func utf16Index(roundingDown i: Index) -> Index { if i._isUTF16TrailingSurrogate { - precondition(i <= endIndex, "Index out of bounds") - return i + precondition(i < endIndex, "Index out of bounds") + // (We know i can't be the endIndex -- it addresses a trailing surrogate.) + return self.resolve(i, preferEnd: false) } return unicodeScalarIndex(roundingDown: i) } diff --git a/Sources/RopeModule/BString/Views/_BString+CharacterView.swift b/Sources/RopeModule/BString/Views/_BString+CharacterView.swift new file mode 100644 index 00000000..7aef3b27 --- /dev/null +++ b/Sources/RopeModule/BString/Views/_BString+CharacterView.swift @@ -0,0 +1,91 @@ +//===----------------------------------------------------------------------===// +// +// 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 new file mode 100644 index 00000000..edcc9ab6 --- /dev/null +++ b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift @@ -0,0 +1,91 @@ +//===----------------------------------------------------------------------===// +// +// 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 UTF16View { + var _base: _BString + + @inline(__always) + init(_base: _BString) { + self._base = _base + } + } + + @inline(__always) + internal var utf16: UTF16View { + UTF16View(_base: self) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF16View: Equatable { + internal static func ==(left: Self, right: Self) -> Bool { + left._base.utf8IsEqual(to: right._base) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF16View: Hashable { + internal func hash(into hasher: inout Hasher) { + _base.hashUTF8(into: &hasher) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF16View: BidirectionalCollection { + typealias Index = _BString.Index + typealias Element = UInt16 + typealias SubSequence = _BSubstring.UTF16View + + @inline(__always) + internal var startIndex: Index { _base.startIndex } + + @inline(__always) + internal var endIndex: Index { _base.endIndex } + + internal var count: Int { _base.utf16Count } + + @inline(__always) + internal func index(after i: Index) -> Index { + _base.utf16Index(after: i) + } + + @inline(__always) + internal func index(before i: Index) -> Index { + _base.utf16Index(before: i) + } + + @inline(__always) + internal func index(_ i: Index, offsetBy distance: Int) -> Index { + _base.utf16Index(i, offsetBy: distance) + } + + internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _base.utf16Index(i, offsetBy: distance, limitedBy: limit) + } + + internal func distance(from start: Index, to end: Index) -> Int { + _base.utf16Distance(from: start, to: end) + } + + internal subscript(position: Index) -> UInt16 { + _base[utf16: position] + } + + internal subscript(bounds: Range) -> _BSubstring.UTF16View { + _BSubstring.UTF16View(_base, in: bounds) + } +} + +#endif diff --git a/Sources/RopeModule/BString/Views/_BString.UTF8View.swift b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift similarity index 98% rename from Sources/RopeModule/BString/Views/_BString.UTF8View.swift rename to Sources/RopeModule/BString/Views/_BString+UTF8View.swift index 552f1f0b..6a6d9cc7 100644 --- a/Sources/RopeModule/BString/Views/_BString.UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift @@ -54,6 +54,8 @@ extension _BString.UTF8View: BidirectionalCollection { @inline(__always) internal var endIndex: Index { _base.endIndex } + internal var count: Int { _base.utf8Count } + @inline(__always) internal func index(after i: Index) -> Index { _base.utf8Index(after: i) diff --git a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift new file mode 100644 index 00000000..9c3e7a95 --- /dev/null +++ b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift @@ -0,0 +1,91 @@ +//===----------------------------------------------------------------------===// +// +// 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 UnicodeScalarView { + var _base: _BString + + @inline(__always) + init(_base: _BString) { + self._base = _base + } + } + + @inline(__always) + internal var unicodeScalars: UnicodeScalarView { + UnicodeScalarView(_base: self) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UnicodeScalarView: Equatable { + internal static func ==(left: Self, right: Self) -> Bool { + left._base.utf8IsEqual(to: right._base) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UnicodeScalarView: Hashable { + internal func hash(into hasher: inout Hasher) { + _base.hashUTF8(into: &hasher) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UnicodeScalarView: BidirectionalCollection { + typealias Index = _BString.Index + typealias Element = UnicodeScalar + typealias SubSequence = _BSubstring.UnicodeScalarView + + @inline(__always) + internal var startIndex: Index { _base.startIndex } + + @inline(__always) + internal var endIndex: Index { _base.endIndex } + + internal var count: Int { _base.unicodeScalarCount } + + @inline(__always) + internal func index(after i: Index) -> Index { + _base.unicodeScalarIndex(after: i) + } + + @inline(__always) + internal func index(before i: Index) -> Index { + _base.unicodeScalarIndex(before: i) + } + + @inline(__always) + internal func index(_ i: Index, offsetBy distance: Int) -> Index { + _base.unicodeScalarIndex(i, offsetBy: distance) + } + + internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _base.unicodeScalarIndex(i, offsetBy: distance, limitedBy: limit) + } + + internal func distance(from start: Index, to end: Index) -> Int { + _base.unicodeScalarDistance(from: start, to: end) + } + + internal subscript(position: Index) -> UnicodeScalar { + _base[unicodeScalar: position] + } + + internal subscript(bounds: Range) -> _BSubstring.UnicodeScalarView { + _BSubstring.UnicodeScalarView(_base, in: bounds) + } +} + +#endif diff --git a/Sources/RopeModule/BString/Views/_BSubstring+CharacterView.swift b/Sources/RopeModule/BString/Views/_BSubstring+CharacterView.swift new file mode 100644 index 00000000..6d17656a --- /dev/null +++ b/Sources/RopeModule/BString/Views/_BSubstring+CharacterView.swift @@ -0,0 +1,123 @@ +//===----------------------------------------------------------------------===// +// +// 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 new file mode 100644 index 00000000..1a889f16 --- /dev/null +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift @@ -0,0 +1,149 @@ +//===----------------------------------------------------------------------===// +// +// 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 UTF16View { + 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.utf16Index(roundingDown: bounds.lowerBound) + let upper = base.utf16Index(roundingDown: bounds.upperBound) + self._bounds = Range(uncheckedBounds: (lower, upper)) + } + + internal init(_substring: _BSubstring) { + self.init(_unchecked: _substring._base, in: _substring._bounds) + } + } + + internal var utf16: UTF16View { + UTF16View(_substring: self) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF16View { + internal var base: _BString.UTF16View { _base.utf16 } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF16View: Equatable { + internal static func ==(left: Self, right: Self) -> Bool { + var i1 = left._bounds.lowerBound + var i2 = right._bounds.lowerBound + + var j1 = left._bounds.upperBound + var j2 = right._bounds.upperBound + + // Compare first code units, if they're trailing surrogates. + guard i1._isUTF16TrailingSurrogate == i2._isUTF16TrailingSurrogate else { return false } + if i1._isUTF16TrailingSurrogate { + guard left[i1] == right[i2] else { return false } + left.formIndex(after: &i1) + left.formIndex(after: &i2) + } + guard i1 < j1, i2 < j2 else { return i1 == j1 && i2 == j2 } + + // Compare last code units, if they're trailing surrogates. + guard j1._isUTF16TrailingSurrogate == j2._isUTF16TrailingSurrogate else { return false } + if j1._isUTF16TrailingSurrogate { + left.formIndex(before: &j1) + right.formIndex(before: &j2) + guard left[j1] == right[j2] else { return false} + } + + return _BString.utf8IsEqual(left._base, in: i1 ..< j1, to: right._base, in: i2 ..< j2) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF16View: Hashable { + internal func hash(into hasher: inout Hasher) { + for codeUnit in self { + hasher.combine(codeUnit) + } + hasher.combine(0xFFFF as UInt16) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF16View: BidirectionalCollection { + typealias Index = _BString.Index + typealias Element = UInt16 + 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.utf16Index(after: i) + } + + @inline(__always) + internal func index(before i: Index) -> Index { + precondition(i > startIndex, "Can't advance below start index") + return _base.utf16Index(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.utf16Index(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.utf16Index(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.utf16Distance(from: start, to: end) + } + + internal subscript(position: Index) -> UInt16 { + precondition(position >= startIndex && position < endIndex, "Index out of bounds") + return _base[utf16: 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.UTF8View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift similarity index 95% rename from Sources/RopeModule/BString/Views/_BSubstring.UTF8View.swift rename to Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift index 109341ce..549494d4 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift @@ -70,6 +70,10 @@ extension _BSubstring.UTF8View: BidirectionalCollection { @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") @@ -103,12 +107,12 @@ extension _BSubstring.UTF8View: BidirectionalCollection { return _base.utf8Distance(from: start, to: end) } - subscript(position: Index) -> UInt8 { + internal subscript(position: Index) -> UInt8 { precondition(position >= startIndex && position < endIndex, "Index out of bounds") return _base[utf8: position] } - subscript(bounds: Range) -> Self { + internal subscript(bounds: Range) -> Self { precondition( bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex, "Range out of bounds") diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift new file mode 100644 index 00000000..6c7ef34a --- /dev/null +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -0,0 +1,123 @@ +//===----------------------------------------------------------------------===// +// +// 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 UnicodeScalarView { + 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.unicodeScalarIndex(roundingDown: bounds.lowerBound) + let upper = base.unicodeScalarIndex(roundingDown: bounds.upperBound) + self._bounds = Range(uncheckedBounds: (lower, upper)) + } + + internal init(_substring: _BSubstring) { + self.init(_unchecked: _substring._base, in: _substring._bounds) + } + } + + internal var unicodeScalars: UnicodeScalarView { + UnicodeScalarView(_substring: self) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UnicodeScalarView { + internal var base: _BString.UnicodeScalarView { _base.unicodeScalars } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UnicodeScalarView: Equatable { + internal static func ==(left: Self, right: Self) -> Bool { + _BString.utf8IsEqual(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.UnicodeScalarView: Hashable { + internal func hash(into hasher: inout Hasher) { + _base.hashUTF8(into: &hasher, from: _bounds.lowerBound, to: _bounds.upperBound) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UnicodeScalarView: BidirectionalCollection { + typealias Index = _BString.Index + typealias Element = UnicodeScalar + 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.unicodeScalarIndex(after: i) + } + + @inline(__always) + internal func index(before i: Index) -> Index { + precondition(i > startIndex, "Can't advance below start index") + return _base.unicodeScalarIndex(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.unicodeScalarIndex(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.unicodeScalarIndex(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.unicodeScalarDistance(from: start, to: end) + } + + internal subscript(position: Index) -> UnicodeScalar { + precondition(position >= startIndex && position < endIndex, "Index out of bounds") + return _base[unicodeScalar: 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/Tests/RopeModuleTests/SampleStrings.swift b/Tests/RopeModuleTests/SampleStrings.swift index 086c3261..92965b03 100644 --- a/Tests/RopeModuleTests/SampleStrings.swift +++ b/Tests/RopeModuleTests/SampleStrings.swift @@ -9,8 +9,7 @@ // //===----------------------------------------------------------------------===// -let sampleString = - #""" +let sampleString = #""" The powerful programming language that is also easy to learn. Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is \# @@ -54,6 +53,9 @@ let sampleString = T̸h̴e̶ ̵p̷o̷w̶e̵r̷f̸u̷l̷ ̵p̴r̷o̷g̶r̷a̸m̸m̶i̸n̴g̴ ̷l̶a̴n̸g̵u̵a̶g̸e̶ ̸t̶h̴a̵t̵ ̶i̷s̶ ̵a̷l̴s̸o̷ ̵e̵a̷s̷y̴ ̵t̵o̷ ̷l̷e̶a̵r̴n̸.̵ """# +let shortSample = #""" + Swift 👨‍👨‍👧‍👧 简洁 c̴̭̈͘ǫ̷̯͋̊d̸͖̩̈̈́ḛ̴́ 🇺🇸🇨🇦🇺🇸 코드 + """# func randomStride( from start: Int, diff --git a/Tests/RopeModuleTests/TestBString2.swift b/Tests/RopeModuleTests/TestBString2.swift new file mode 100644 index 00000000..91c8b894 --- /dev/null +++ b/Tests/RopeModuleTests/TestBString2.swift @@ -0,0 +1,40 @@ +//===----------------------------------------------------------------------===// +// +// 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) && DEBUG +import _CollectionsTestSupport +import XCTest +@testable import RopeModule + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +class TestBString2: CollectionTestCase { + func testUTF8View() { + let str = _BString(shortSample) + checkBidirectionalCollection(str.utf8, expectedContents: shortSample.utf8) + } + + func testUTF16View() { + let str = _BString(shortSample) + checkBidirectionalCollection(str.utf16, expectedContents: shortSample.utf16) + } + + func testUnicodeScalarView() { + let str = _BString(shortSample) + checkBidirectionalCollection(str.unicodeScalars, expectedContents: shortSample.unicodeScalars) + } + + func testCharacterView() { + let str = _BString(shortSample) + checkBidirectionalCollection(str.characters, expectedContents: shortSample) + } +} + +#endif From e0f8305a99d8c9ec7cfbf5f8cba52993932f0d18 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 8 Mar 2023 15:51:13 -0800 Subject: [PATCH 041/113] _BString.hashUTF8(into:from:end:): Fix typo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The original code accidentally used `start` instead of `end` to normalize the end of the range, so it did not actually hash any actual string contents. - While we’re here, extract the task of iterating over substring chunks into a reusable standalone method. --- .../BString/Basics/_BString+Contents.swift | 35 ++++++++++++++++ .../Conformances/_BString+Hashing.swift | 41 ++----------------- 2 files changed, 39 insertions(+), 37 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 9691ca71..008b973f 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -509,4 +509,39 @@ extension _BString { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + func _foreachChunk( + from start: Index, + to end: Index, + _ body: (Substring) -> Void + ) { + precondition(start <= end) + guard start < end else { return } + let start = resolve(start, preferEnd: false) + let end = resolve(end, preferEnd: true) + + var ri = start._rope! + let endRopeIndex = end._rope! + + if ri == endRopeIndex { + let str = self.rope[ri].string + body(str[start._chunkIndex ..< end._chunkIndex]) + return + } + + let firstChunk = self.rope[ri].string + body(firstChunk[start._chunkIndex...]) + + rope.formIndex(after: &ri) + while ri < endRopeIndex { + var string = rope[ri].string + body(string[...]) + } + + let lastChunk = self.rope[ri].string + body(lastChunk[.. Date: Wed, 8 Mar 2023 18:44:39 -0800 Subject: [PATCH 042/113] _BString: Fix character index rounding; use it when accessing character data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Oops, `_BString.subscript(character:)` failed to round down to a character boundary before trying to access the addressed character. It also resolved the index with `preferEnd` set to true, which isn’t what we actually want. --- .../BString/Basics/_BString+Contents.swift | 7 ++- .../BString/Basics/_BString+Index.swift | 12 ++-- Tests/RopeModuleTests/TestBString.swift | 60 +++++++++++++++++++ 3 files changed, 70 insertions(+), 9 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 008b973f..2bdb2701 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -330,7 +330,7 @@ extension _BString { guard offset > 0 else { return resolve(i, preferEnd: false)._knownCharacterAligned() } guard offset < utf8Count else { return resolve(i, preferEnd: true)._knownCharacterAligned() } - let i = resolve(i, preferEnd: true) + let i = resolve(i, preferEnd: false) guard !i._isKnownCharacterAligned else { return i } var ri = i._rope! @@ -430,12 +430,13 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func _character(at start: Index) -> (character: Character, end: Index) { + let start = characterIndex(roundingDown: start) precondition(start._utf8Offset < utf8Count, "Index out of bounds") - let start = resolve(start, preferEnd: false) + var ri = start._rope! var ci = start._chunkIndex var chunk = rope[ri] - let char = chunk.string[ci] + let char = chunk.wholeCharacters[ci] let endOffset = start._utf8ChunkOffset + char.utf8.count if endOffset < chunk.utf8Count { let endStringIndex = chunk.string._utf8Index(at: endOffset) diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift index 8dca907a..1c9add4a 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -56,10 +56,10 @@ extension _BString.Index { internal static var _utf16TrailingSurrogateBits: UInt64 { 0x400 } @inline(__always) - internal static var _characterAlignmentBits: UInt64 { 0x300 } + internal static var _characterAlignmentBit: UInt64 { 0x200 } @inline(__always) - internal static var _scalarAlignmentBits: UInt64 { 0x100 } + internal static var _scalarAlignmentBit: UInt64 { 0x100 } internal var _utf8Offset: Int { Int(truncatingIfNeeded: _rawBits &>> 11) @@ -125,22 +125,22 @@ extension _BString.Index { internal func _knownScalarAligned() -> Self { var copy = self - copy._flags = Self._scalarAlignmentBits + copy._flags = Self._scalarAlignmentBit return copy } internal func _knownCharacterAligned() -> Self { var copy = self - copy._flags = Self._characterAlignmentBits + copy._flags = Self._characterAlignmentBit | Self._scalarAlignmentBit return copy } internal var _isKnownScalarAligned: Bool { - _rawBits & Self._scalarAlignmentBits != 0 + _rawBits & Self._scalarAlignmentBit != 0 } internal var _isKnownCharacterAligned: Bool { - _rawBits & Self._characterAlignmentBits != 0 + _rawBits & Self._characterAlignmentBit != 0 } internal init(_utf8Offset: Int) { diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 59d6d371..50737dd7 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -433,5 +433,65 @@ class TestBString: XCTestCase { checkCharacterIndices(flat, big) } } + + func testCharacterIndexRounding() { + let ref = sampleString + let str = _BString(ref) + + func check( + _ indices: some Sequence<_BString.Index>, + file: StaticString = #file, + line: UInt = #line + ) { + var current = str.startIndex + var next = str.characterIndex(after: current) + for i in indices { + if i >= next { + current = next + next = str.characterIndex(after: current) + } + let j = str.characterIndex(roundingDown: i) + XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + XCTAssertEqual(str[character: i], str[character: j], "i: \(i)", file: file, line: line) + } + XCTAssertEqual(next, str.endIndex, "end", file: file, line: line) + } + + check(str.utf8.indices) + check(str.utf16.indices) + check(str.unicodeScalars.indices) + check(str.characters.indices) + XCTAssertEqual(str.characterIndex(roundingDown: str.endIndex), str.endIndex) + + } + + func testUnicodeScalarIndexRounding() { + let ref = sampleString + let str = _BString(ref) + + func check( + _ indices: some Sequence<_BString.Index>, + file: StaticString = #file, + line: UInt = #line + ) { + var current = str.startIndex + var next = str.unicodeScalarIndex(after: current) + for i in indices { + while i >= next { + current = next + next = str.unicodeScalarIndex(after: current) + } + let j = str.unicodeScalarIndex(roundingDown: i) + XCTAssertEqual(j, current, "\(i)", file: file, line: line) + XCTAssertEqual(str[unicodeScalar: i], str[unicodeScalar: j], "i: \(i)", file: file, line: line) + } + } + + check(str.utf8.indices) + check(str.utf16.indices) + check(str.unicodeScalars.indices) + check(str.characters.indices) + XCTAssertEqual(str.unicodeScalarIndex(roundingDown: str.endIndex), str.endIndex) + } } #endif From a10439bc324c9e5aca8fdbb19946ebe9af14eb75 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 17:58:20 -0800 Subject: [PATCH 043/113] _BString, _BSubstring: Merge character views into top-level types. Add RangeReplaceableCollection conformances. This emulates the standard String. --- .../BString/Basics/_BString+Contents.swift | 17 +- .../RopeModule/BString/Basics/_BString.swift | 4 - .../_BString+BidirectionalCollection.swift | 64 +++++ .../Conformances/_BString+Comparable.swift | 95 ++++++++ .../_BString+CustomStringConvertible.swift | 21 ++ ...arisons.swift => _BString+Equatable.swift} | 80 +------ ..._BString+ExpressibleByStringLiteral.swift} | 7 - .../Conformances/_BString+Hashing.swift | 7 + .../_BString+LosslessStringConvertible.swift | 19 ++ .../_BString+RangeReplaceableCollection.swift | 223 ++++++++++++++++++ .../Conformances/_BString+Sequence.swift | 25 ++ .../_BString+TextOutputStream.swift | 30 +++ .../BString/Operations/_BString+Append.swift | 20 +- .../Operations/_BString+Initializers.swift | 41 +--- .../BString/Operations/_BString+Insert.swift | 16 +- .../Operations/_BString+RemoveSubrange.swift | 2 +- .../Operations/_BString+ReplaceSubrange.swift | 15 +- .../Views/_BString+CharacterView.swift | 91 ------- .../BString/Views/_BString+UTF16View.swift | 2 +- .../BString/Views/_BString+UTF8View.swift | 2 +- .../Views/_BString+UnicodeScalarView.swift | 215 ++++++++++++++++- .../Views/_BSubstring+CharacterView.swift | 123 ---------- .../BString/Views/_BSubstring+UTF16View.swift | 2 +- .../BString/Views/_BSubstring+UTF8View.swift | 2 +- .../Views/_BSubstring+UnicodeScalarView.swift | 130 +++++++++- .../BString/Views/_BSubstring.swift | 155 +++++++++++- .../BigString/BigString+CharacterView.swift | 10 +- .../BigString+UnicodeScalarView.swift | 131 ++++++---- Tests/RopeModuleTests/TestBString.swift | 85 ++++++- Tests/RopeModuleTests/TestBString2.swift | 2 +- 30 files changed, 1195 insertions(+), 441 deletions(-) create mode 100644 Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift create mode 100644 Sources/RopeModule/BString/Conformances/_BString+Comparable.swift create mode 100644 Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift rename Sources/RopeModule/BString/Conformances/{_BString+Comparisons.swift => _BString+Equatable.swift} (67%) rename Sources/RopeModule/BString/Conformances/{_BString+Conformances.swift => _BString+ExpressibleByStringLiteral.swift} (78%) create mode 100644 Sources/RopeModule/BString/Conformances/_BString+LosslessStringConvertible.swift create mode 100644 Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift create mode 100644 Sources/RopeModule/BString/Conformances/_BString+Sequence.swift create mode 100644 Sources/RopeModule/BString/Conformances/_BString+TextOutputStream.swift delete mode 100644 Sources/RopeModule/BString/Views/_BString+CharacterView.swift delete mode 100644 Sources/RopeModule/BString/Views/_BSubstring+CharacterView.swift 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) } } From 59b5c634d00f1eb95704282bd6f1df95c6582d5f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 18:00:14 -0800 Subject: [PATCH 044/113] _Rope.UnsafeHandle._removeChild(at:): Fix buffer overflow uncovered by ASan --- Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift b/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift index 33ec4191..cb87196a 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift @@ -124,7 +124,7 @@ extension _Rope.UnsafeHandle { assertMutable() assert(slot >= 0 && slot < childCount) let result = (_start + slot).move() - (_start + slot).moveInitialize(from: _start + slot + 1, count: childCount - slot) + (_start + slot).moveInitialize(from: _start + slot + 1, count: childCount - slot - 1) childCount -= 1 return result } From 118239806868f4700e2098bb77f95ae5c06fe6ac Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 18:49:48 -0800 Subject: [PATCH 045/113] _BString: Give each view a custom iterator by hooking up the existing implementations --- .../BString/Basics/_BString+Contents.swift | 4 +- .../BString/Basics/_BString+Iterators.swift | 100 ++++++++++-------- .../BString/Views/_BString+UTF16View.swift | 11 +- .../BString/Views/_BString+UTF8View.swift | 11 +- .../Views/_BString+UnicodeScalarView.swift | 11 +- .../BString/Views/_BSubstring+UTF16View.swift | 25 ++++- .../BString/Views/_BSubstring+UTF8View.swift | 25 ++++- .../Views/_BSubstring+UnicodeScalarView.swift | 25 ++++- .../BString/Views/_BSubstring.swift | 25 ++++- 9 files changed, 182 insertions(+), 55 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 6380f1b6..2f0ec453 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -316,7 +316,7 @@ extension _BString { guard offset < utf8Count else { return resolve(i, preferEnd: true)._knownCharacterAligned() } let i = resolve(i, preferEnd: false) - guard !i._isKnownCharacterAligned else { return i } + guard !i._isKnownCharacterAligned else { return resolve(i, preferEnd: false) } var ri = i._rope! let ci = i._chunkIndex @@ -354,7 +354,7 @@ extension _BString { guard i < endIndex else { return resolve(i, preferEnd: true)._knownCharacterAligned() } let start = self.resolve(i, preferEnd: false) - guard !i._isKnownScalarAligned else { return i } + guard !i._isKnownScalarAligned else { return resolve(i, preferEnd: false) } let ri = start._rope! let chunk = self.rope[ri] let ci = chunk.string.unicodeScalars._index(roundingDown: start._chunkIndex) diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index f24e6258..a38f97e5 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -41,13 +41,9 @@ extension _BString { internal let _base: _BString internal var _index: _BString.Index - internal init(_base: _BString, from index: _BString.Index) { + internal init(_base: _BString, from start: _BString.Index) { self._base = _base - if index < _base.endIndex { - self._index = _base.resolve(index, preferEnd: false) - } else { - self._index = index - } + self._index = _base.utf8Index(roundingDown: start) } } @@ -55,8 +51,8 @@ extension _BString { UTF8Iterator(_base: self, from: self.startIndex) } - internal func makeUTF8Iterator(from index: Index) -> UTF8Iterator { - UTF8Iterator(_base: self, from: index) + internal func makeUTF8Iterator(from start: Index) -> UTF8Iterator { + UTF8Iterator(_base: self, from: start) } } @@ -121,18 +117,21 @@ extension _BString.UTF8Iterator: IteratorProtocol { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct UTF16Iterator { - internal var _rope: Rope.Iterator - internal var _chunk: String.UTF16View.Iterator - - internal init(_base: Rope.Iterator) { - self._rope = _base - let str = self._rope.next()?.string ?? "" - self._chunk = str.utf16.makeIterator() + internal let _base: _BString + internal var _index: _BString.Index + + internal init(_base: _BString, from start: _BString.Index) { + self._base = _base + self._index = _base.utf16Index(roundingDown: start) } } - + internal func makeUTF16Iterator() -> UTF16Iterator { - UTF16Iterator(_base: self.rope.makeIterator()) + UTF16Iterator(_base: self, from: self.startIndex) + } + + internal func makeUTF16Iterator(from start: Index) -> UTF16Iterator { + UTF16Iterator(_base: self, from: start) } } @@ -141,41 +140,43 @@ extension _BString.UTF16Iterator: IteratorProtocol { internal typealias Element = UInt16 internal mutating func next() -> UInt16? { - if let codeUnit = _chunk.next() { - return codeUnit + guard _index < _base.endIndex else { return nil } + let ri = _index._rope! + var ci = _index._chunkIndex + let chunk = _base.rope[ri] + let result = chunk.string.utf16[ci] + + chunk.string.utf16.formIndex(after: &ci) + if ci < chunk.string.endIndex { + _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) + } else { + _index = _BString.Index( + baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, + rope: _base.rope.index(after: ri), + chunk: String.Index(_utf8Offset: 0)) } - guard let chunk = _rope.next() else { return nil } - _chunk = chunk.string.utf16.makeIterator() - return _chunk.next()! + return result } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { internal struct UnicodeScalarIterator { - internal var _rope: Rope.Iterator - // FIXME: Change to using String.UnicodeScalarView.Iterator once makeIterator(from:) is a thing - internal var _chunk: String.UnicodeScalarView - internal var _index: String.Index + internal let _base: _BString + internal var _index: _BString.Index - internal init(_base: Rope.Iterator, _ chunk: Chunk, _ index: String.Index) { - self._rope = _base - self._chunk = chunk.string.unicodeScalars - self._index = index + internal init(_base: _BString, from start: _BString.Index) { + self._base = _base + self._index = _base.unicodeScalarIndex(roundingDown: start) } } internal func makeUnicodeScalarIterator() -> UnicodeScalarIterator { - makeUnicodeScalarIterator(from: startIndex) + UnicodeScalarIterator(_base: self, from: startIndex) } - internal func makeUnicodeScalarIterator(from index: Index) -> UnicodeScalarIterator { - let i = resolve(index, preferEnd: index == endIndex) - let ropeIndex = i._rope! - let chunkIndex = i._chunkIndex - var base = self.rope.makeIterator(from: ropeIndex) - _ = base.next() - return UnicodeScalarIterator(_base: base, rope[ropeIndex], chunkIndex) + internal func makeUnicodeScalarIterator(from start: Index) -> UnicodeScalarIterator { + UnicodeScalarIterator(_base: self, from: start) } } @@ -184,15 +185,22 @@ extension _BString.UnicodeScalarIterator: IteratorProtocol { internal typealias Element = Unicode.Scalar internal mutating func next() -> Unicode.Scalar? { - if _index == _chunk.endIndex { - guard let chunk = _rope.next() else { return nil } - _chunk = chunk.string.unicodeScalars - _index = _chunk.startIndex - assert(_index < _chunk.endIndex) + guard _index < _base.endIndex else { return nil } + let ri = _index._rope! + var ci = _index._chunkIndex + let chunk = _base.rope[ri] + let result = chunk.string.unicodeScalars[ci] + + chunk.string.unicodeScalars.formIndex(after: &ci) + if ci < chunk.string.endIndex { + _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) + } else { + _index = _BString.Index( + baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, + rope: _base.rope.index(after: ri), + chunk: String.Index(_utf8Offset: 0)) } - let scalar = _chunk[_index] - _index = _chunk.index(after: _index) - return scalar + return result } } diff --git a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift index 412ca1a3..05789503 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift @@ -42,10 +42,19 @@ extension _BString.UTF16View: Hashable { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF16View: Sequence { + typealias Element = UInt16 + typealias Iterator = _BString.UTF16Iterator + + internal func makeIterator() -> _BString.UTF16Iterator { + _base.makeUTF16Iterator() + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF16View: BidirectionalCollection { typealias Index = _BString.Index - typealias Element = UInt16 typealias SubSequence = _BSubstring.UTF16View @inline(__always) diff --git a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift index 561f5edd..c917ef41 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift @@ -42,10 +42,19 @@ extension _BString.UTF8View: Hashable { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF8View: Sequence { + typealias Element = UInt8 + typealias Iterator = _BString.UTF8Iterator + + internal func makeIterator() -> _BString.UTF8Iterator { + _base.makeUTF8Iterator() + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF8View: BidirectionalCollection { typealias Index = _BString.Index - typealias Element = UInt8 typealias SubSequence = _BSubstring.UTF8View @inline(__always) diff --git a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift index f281bf47..05cd8e18 100644 --- a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift @@ -46,10 +46,19 @@ extension _BString.UnicodeScalarView: Hashable { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UnicodeScalarView: Sequence { + typealias Element = UnicodeScalar + typealias Iterator = _BString.UnicodeScalarIterator + + internal func makeIterator() -> _BString.UnicodeScalarIterator { + _base.makeUnicodeScalarIterator() + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: BidirectionalCollection { typealias Index = _BString.Index - typealias Element = UnicodeScalar typealias SubSequence = _BSubstring.UnicodeScalarView @inline(__always) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift index b64bd08b..2e1908f9 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift @@ -84,10 +84,33 @@ extension _BSubstring.UTF16View: Hashable { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF16View: Sequence { + typealias Element = UInt16 + + internal struct Iterator: IteratorProtocol { + var _it: _BString.UTF16Iterator + var _end: _BString.Index + + init(_substring: _BSubstring.UTF16View) { + self._it = _substring._base.makeUTF16Iterator(from: _substring.startIndex) + self._end = _substring.endIndex + } + + internal mutating func next() -> UInt16? { + guard _it._index < _end else { return nil } + return _it.next() + } + } + + internal func makeIterator() -> Iterator { + Iterator(_substring: self) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF16View: BidirectionalCollection { typealias Index = _BString.Index - typealias Element = UInt16 typealias SubSequence = Self @inline(__always) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift index 7c50124e..9de02d48 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift @@ -58,10 +58,33 @@ extension _BSubstring.UTF8View: Hashable { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF8View: Sequence { + typealias Element = UInt8 + + internal struct Iterator: IteratorProtocol { + var _it: _BString.UTF8Iterator + var _end: _BString.Index + + init(_substring: _BSubstring.UTF8View) { + self._it = _substring._base.makeUTF8Iterator(from: _substring.startIndex) + self._end = _substring.endIndex + } + + internal mutating func next() -> UInt8? { + guard _it._index < _end else { return nil } + return _it.next() + } + } + + internal func makeIterator() -> Iterator { + Iterator(_substring: self) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF8View: BidirectionalCollection { typealias Index = _BString.Index - typealias Element = UInt8 typealias SubSequence = Self @inline(__always) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift index 7e477c2b..581f5484 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -65,10 +65,33 @@ extension _BSubstring.UnicodeScalarView: Hashable { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UnicodeScalarView: Sequence { + typealias Element = UnicodeScalar + + internal struct Iterator: IteratorProtocol { + var _it: _BString.UnicodeScalarIterator + let _end: _BString.Index + + internal init(_substring: _BSubstring.UnicodeScalarView) { + self._it = _substring._base.makeUnicodeScalarIterator(from: _substring.startIndex) + self._end = _substring._base.resolve(_substring.endIndex, preferEnd: true) + } + + internal mutating func next() -> UnicodeScalar? { + guard _it._index < _end else { return nil } + return _it.next() + } + } + + internal func makeIterator() -> Iterator { + Iterator(_substring: self) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: BidirectionalCollection { typealias Index = _BString.Index - typealias Element = UnicodeScalar typealias SubSequence = Self @inline(__always) diff --git a/Sources/RopeModule/BString/Views/_BSubstring.swift b/Sources/RopeModule/BString/Views/_BSubstring.swift index ed80ed1e..3c9e2402 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring.swift @@ -79,10 +79,33 @@ extension _BSubstring: Hashable { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: Sequence { + typealias Element = Character + + internal struct Iterator: IteratorProtocol { + let _end: _BString.Index + var _it: _BString.Iterator + + init(_substring: _BSubstring) { + self._it = _substring._base.makeCharacterIterator(from: _substring.startIndex) + self._end = _substring.endIndex + } + + internal mutating func next() -> Character? { + guard _it.isBelow(_end) else { return nil } + return _it.next() + } + } + + internal func makeIterator() -> Iterator { + Iterator(_substring: self) + } +} + @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) From abf5dfd260209dc550a826d745a2a03bde6ddcab Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 18:55:27 -0800 Subject: [PATCH 046/113] _BSubstring: Conform to Comparable --- .../Conformances/_BString+Comparable.swift | 13 ++------ .../BString/Views/_BSubstring.swift | 30 +++++++++++++++++++ .../BigString/BigString+CharacterView.swift | 2 +- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift index cb2a67a5..565e43ce 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift @@ -14,22 +14,15 @@ @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 } + if left.isIdentical(to: right) { return false } // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. - var it1 = self.makeCharacterIterator() - var it2 = other.makeCharacterIterator() + var it1 = left.makeIterator() + var it2 = right.makeIterator() while true { switch (it1.next(), it2.next()) { case (nil, nil): return false diff --git a/Sources/RopeModule/BString/Views/_BSubstring.swift b/Sources/RopeModule/BString/Views/_BSubstring.swift index 3c9e2402..b8ae1c7a 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring.swift @@ -70,6 +70,11 @@ extension _BSubstring: Equatable { internal static func ==(left: Self, right: Self) -> Bool { _BString.characterwiseIsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) } + + internal func isIdentical(to other: Self) -> Bool { + guard self._base.isIdentical(to: other._base) else { return false } + return self._bounds == other._bounds + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) @@ -79,6 +84,31 @@ extension _BSubstring: Hashable { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: Comparable { + internal static func < (left: Self, right: 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 left.isIdentical(to: right) { return false } + // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. + var it1 = left.makeIterator() + var it2 = right.makeIterator() + 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 _BSubstring: Sequence { typealias Element = Character diff --git a/Sources/RopeModule/BigString/BigString+CharacterView.swift b/Sources/RopeModule/BigString/BigString+CharacterView.swift index d51acb8c..b6ec0eb8 100644 --- a/Sources/RopeModule/BigString/BigString+CharacterView.swift +++ b/Sources/RopeModule/BigString/BigString+CharacterView.swift @@ -60,7 +60,7 @@ extension BigString: Equatable { @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.characterwiseIsLess(than: right._guts) + left._guts < right._guts } } From 258d22947c90574c4b734d0258d0d13de5a3ff86 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 19:13:47 -0800 Subject: [PATCH 047/113] _BString: Review Equatable implementations --- .../Conformances/_BString+Equatable.swift | 63 ++++++------------- .../BString/Views/_BString+UTF16View.swift | 2 +- .../BString/Views/_BString+UTF8View.swift | 2 +- .../Views/_BString+UnicodeScalarView.swift | 2 +- .../BString/Views/_BSubstring.swift | 21 ++++++- .../BigString/BigString+UTF16View.swift | 2 +- .../BigString/BigString+UTF8View.swift | 2 +- .../BigString+UnicodeScalarView.swift | 2 +- 8 files changed, 46 insertions(+), 50 deletions(-) diff --git a/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift b/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift index 2d5c231c..f87ed408 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift @@ -21,23 +21,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 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 // 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 true } - guard self.characterCount == other.characterCount else { return false } + if left.isIdentical(to: right) { return true } + guard left.characterCount == right.characterCount else { return false } // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. - var it1 = self.makeCharacterIterator() - var it2 = other.makeCharacterIterator() + var it1 = left.makeCharacterIterator() + var it2 = right.makeCharacterIterator() var a: Character? = nil var b: Character? = nil repeat { @@ -47,38 +40,23 @@ extension _BString { } while a != nil return true } +} +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + @available(*, deprecated, renamed: "==") + internal func characterwiseIsEqual(to other: Self) -> Bool { + self == other + } + + @available(*, deprecated, message: "Use _BSubstring.==") internal static func characterwiseIsEqual( _ left: Self, in leftRange: Range, to right: Self, in rightRange: Range ) -> Bool { - // FIXME: Implement properly normalized comparisons & hashing. - // This is somewhat tricky as we shouldn't just normalize individual pieces of the string - // split up on random Character boundaries -- Unicode does not promise that - // norm(a + c) == norm(a) + norm(b) in this case. - // To do this properly, we'll probably need to expose new stdlib entry points. :-/ - if left.isIdentical(to: right), leftRange == rightRange { return true } - - // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. - var it1 = left.makeCharacterIterator(from: leftRange.lowerBound) - var it2 = right.makeCharacterIterator(from: rightRange.lowerBound) - - if leftRange._isEmptyUTF8 { return rightRange._isEmptyUTF8 } - - let leftEnd = left.resolve(leftRange.upperBound, preferEnd: true) - let rightEnd = right.resolve(rightRange.upperBound, preferEnd: true) - - var a: Character? = nil - var b: Character? = nil - while it1.isBelow(leftEnd), it2.isBelow(rightEnd) { - a = it1.next() - b = it2.next() - assert(a != nil && b != nil) - guard a == b else { return false } - } - return !it1.isBelow(leftEnd) && !it2.isBelow(rightEnd) + _BSubstring(_unchecked: left, in: leftRange) == _BSubstring(_unchecked: right, in: rightRange) } } @@ -86,18 +64,18 @@ extension _BString { extension _BString { /// Lexicographically compare the UTF-8 representations of `left` to `right`, returning a Boolean /// value indicating whether `left` is equal to `right`. - internal func utf8IsEqual(to other: Self) -> Bool { - if self.isIdentical(to: other) { return true } - guard self.rope.summary == other.rope.summary else { return false } + internal static func utf8IsEqual(_ left: Self, to right: Self) -> Bool { + if left.isIdentical(to: right) { return true } + guard left.rope.summary == right.rope.summary else { 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.makeUTF8Iterator() - var it2 = other.makeUTF8Iterator() - var remaining = self.utf8Count + var it1 = left.makeUTF8Iterator() + var it2 = right.makeUTF8Iterator() + var remaining = left.utf8Count while remaining > 0 { let consumed = it1.next(maximumCount: remaining) { b1 in @@ -139,7 +117,6 @@ extension _BString { remaining -= consumed } return true - } } diff --git a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift index 05789503..dcc05ff5 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift @@ -31,7 +31,7 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF16View: Equatable { internal static func ==(left: Self, right: Self) -> Bool { - left._base.utf8IsEqual(to: right._base) + _BString.utf8IsEqual(left._base, to: right._base) } } diff --git a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift index c917ef41..ada4bd0f 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift @@ -31,7 +31,7 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF8View: Equatable { internal static func ==(left: Self, right: Self) -> Bool { - left._base.utf8IsEqual(to: right._base) + _BString.utf8IsEqual(left._base, to: right._base) } } diff --git a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift index 05cd8e18..addadd13 100644 --- a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift @@ -35,7 +35,7 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: Equatable { internal static func ==(left: Self, right: Self) -> Bool { - left._base.utf8IsEqual(to: right._base) + _BString.utf8IsEqual(left._base, to: right._base) } } diff --git a/Sources/RopeModule/BString/Views/_BSubstring.swift b/Sources/RopeModule/BString/Views/_BSubstring.swift index b8ae1c7a..b4b46602 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring.swift @@ -68,7 +68,26 @@ extension _BSubstring: LosslessStringConvertible { @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) + // FIXME: Implement properly normalized comparisons & hashing. + // This is somewhat tricky as we shouldn't just normalize individual pieces of the string + // split up on random Character boundaries -- Unicode does not promise that + // norm(a + c) == norm(a) + norm(b) in this case. + // To do this properly, we'll probably need to expose new stdlib entry points. :-/ + if left.isIdentical(to: right) { return true } + + guard left.count == right.count else { return false } + + // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. + var it1 = left.makeIterator() + var it2 = right.makeIterator() + var a: Character? = nil + var b: Character? = nil + repeat { + a = it1.next() + b = it2.next() + guard a == b else { return false } + } while a != nil + return true } internal func isIdentical(to other: Self) -> Bool { diff --git a/Sources/RopeModule/BigString/BigString+UTF16View.swift b/Sources/RopeModule/BigString/BigString+UTF16View.swift index b6da68f9..56dba619 100644 --- a/Sources/RopeModule/BigString/BigString+UTF16View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF16View.swift @@ -61,7 +61,7 @@ extension BigString.UTF16View: CustomStringConvertible { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: Equatable { public static func ==(left: Self, right: Self) -> Bool { - left._guts.utf8IsEqual(to: right._guts) + _BString.utf8IsEqual(left._guts, to: right._guts) } } diff --git a/Sources/RopeModule/BigString/BigString+UTF8View.swift b/Sources/RopeModule/BigString/BigString+UTF8View.swift index 9f789113..bc2855db 100644 --- a/Sources/RopeModule/BigString/BigString+UTF8View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF8View.swift @@ -61,7 +61,7 @@ extension BigString.UTF8View: CustomStringConvertible { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: Equatable { public static func ==(left: Self, right: Self) -> Bool { - left._guts.utf8IsEqual(to: right._guts) + _BString.utf8IsEqual(left._guts, to: right._guts) } } diff --git a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift index 91708379..953f0047 100644 --- a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift @@ -63,7 +63,7 @@ extension BigString.UnicodeScalarView: CustomStringConvertible { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: Equatable { public static func ==(left: Self, right: Self) -> Bool { - left._guts.utf8IsEqual(to: right._guts) + _BString.utf8IsEqual(left._guts, to: right._guts) } } From 03d7c43c22760aea7df7e96f18ee31ffd778a638 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 19:26:43 -0800 Subject: [PATCH 048/113] _BString: Add index rounding methods to all views --- .../_BString+BidirectionalCollection.swift | 11 +++++++++++ .../BString/Views/_BString+UTF16View.swift | 11 +++++++++++ .../BString/Views/_BString+UTF8View.swift | 11 +++++++++++ .../BString/Views/_BString+UnicodeScalarView.swift | 11 +++++++++++ .../BString/Views/_BSubstring+UTF16View.swift | 13 +++++++++++++ .../BString/Views/_BSubstring+UTF8View.swift | 13 +++++++++++++ .../Views/_BSubstring+UnicodeScalarView.swift | 13 +++++++++++++ Sources/RopeModule/BString/Views/_BSubstring.swift | 13 +++++++++++++ 8 files changed, 96 insertions(+) diff --git a/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift b/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift index 77871d55..6e0c4840 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift @@ -61,4 +61,15 @@ extension _BString: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + internal func index(roundingDown i: Index) -> Index { + characterIndex(roundingDown: i) + } + + internal func index(roundingUp i: Index) -> Index { + characterIndex(roundingUp: i) + } +} + #endif diff --git a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift index dcc05ff5..e57dee59 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift @@ -97,4 +97,15 @@ extension _BString.UTF16View: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF16View { + internal func index(roundingDown i: Index) -> Index { + _base.utf16Index(roundingDown: i) + } + + internal func index(roundingUp i: Index) -> Index { + _base.utf16Index(roundingUp: i) + } +} + #endif diff --git a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift index ada4bd0f..57eadd6b 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift @@ -97,4 +97,15 @@ extension _BString.UTF8View: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF8View { + internal func index(roundingDown i: Index) -> Index { + _base.utf8Index(roundingDown: i) + } + + internal func index(roundingUp i: Index) -> Index { + _base.utf8Index(roundingUp: i) + } +} + #endif diff --git a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift index addadd13..1ecd7b26 100644 --- a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift @@ -101,6 +101,17 @@ extension _BString.UnicodeScalarView: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UnicodeScalarView { + internal func index(roundingDown i: Index) -> Index { + _base.unicodeScalarIndex(roundingDown: i) + } + + internal func index(roundingUp i: Index) -> Index { + _base.unicodeScalarIndex(roundingUp: i) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: RangeReplaceableCollection { internal init() { diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift index 2e1908f9..28876789 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift @@ -169,4 +169,17 @@ extension _BSubstring.UTF16View: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF16View { + internal func index(roundingDown i: Index) -> Index { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + return _base.utf16Index(roundingDown: i) + } + + internal func index(roundingUp i: Index) -> Index { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + return _base.utf16Index(roundingUp: i) + } +} + #endif diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift index 9de02d48..3a195739 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift @@ -143,4 +143,17 @@ extension _BSubstring.UTF8View: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UTF8View { + internal func index(roundingDown i: Index) -> Index { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + return _base.utf8Index(roundingDown: i) + } + + internal func index(roundingUp i: Index) -> Index { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + return _base.utf8Index(roundingUp: i) + } +} + #endif diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift index 581f5484..3e7a4271 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -150,6 +150,19 @@ extension _BSubstring.UnicodeScalarView: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UnicodeScalarView { + internal func index(roundingDown i: Index) -> Index { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + return _base.unicodeScalarIndex(roundingDown: i) + } + + internal func index(roundingUp i: Index) -> Index { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + return _base.unicodeScalarIndex(roundingUp: i) + } +} + @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 diff --git a/Sources/RopeModule/BString/Views/_BSubstring.swift b/Sources/RopeModule/BString/Views/_BSubstring.swift index b4b46602..a975678f 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring.swift @@ -213,6 +213,19 @@ extension _BSubstring: BidirectionalCollection { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring { + internal func index(roundingDown i: Index) -> Index { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + return _base.characterIndex(roundingDown: i) + } + + internal func index(roundingUp i: Index) -> Index { + precondition(i >= startIndex && i <= endIndex, "Index out of bounds") + return _base.characterIndex(roundingUp: i) + } +} + @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 From 05f8f9b8876d0f12efe3b7d0d5d7d96761f96031 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 19:27:06 -0800 Subject: [PATCH 049/113] _BString: Modernize tests --- Tests/RopeModuleTests/TestBString.swift | 88 ++++++++++++------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 0426301a..1db14a97 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -41,10 +41,10 @@ class TestBString: XCTestCase { func test_empty() { let s = _BString() s.invariantCheck() - XCTAssertEqual(s.characterCount, 0) - XCTAssertEqual(s.unicodeScalarCount, 0) - XCTAssertEqual(s.utf16Count, 0) - XCTAssertEqual(s.utf8Count, 0) + XCTAssertEqual(s.count, 0) + XCTAssertEqual(s.unicodeScalars.count, 0) + XCTAssertEqual(s.utf16.count, 0) + XCTAssertEqual(s.utf8.count, 0) XCTAssertTrue(s.isEmpty) XCTAssertEqual(s.startIndex, s.endIndex) XCTAssertEqual(s.startIndex._utf8Offset, 0) @@ -54,11 +54,11 @@ class TestBString: XCTestCase { let big = _BString(sampleString) big.invariantCheck() - XCTAssertEqual(big.characterCount, sampleString.count) - XCTAssertEqual(big.unicodeScalarCount, sampleString.unicodeScalars.count) - XCTAssertEqual(big.utf16Count, sampleString.utf16.count) - XCTAssertEqual(big.utf8Count, sampleString.utf8.count) - + XCTAssertEqual(big.count, sampleString.count) + XCTAssertEqual(big.unicodeScalars.count, sampleString.unicodeScalars.count) + XCTAssertEqual(big.utf16.count, sampleString.utf16.count) + XCTAssertEqual(big.utf8.count, sampleString.utf8.count) + let flat = String(_from: big) XCTAssertEqual(flat, sampleString) } @@ -71,7 +71,7 @@ class TestBString: XCTestCase { ) -> (flat: [String.Index], big: [_BString.Index]) { // Check iterators var it1 = flat.makeIterator() - var it2 = big.makeCharacterIterator() + var it2 = big.makeIterator() while true { let a = it1.next() let b = it2.next() @@ -86,14 +86,14 @@ class TestBString: XCTestCase { let indices1 = Array(flat.indices) + [flat.endIndex] let indices2 = Array( sequence(first: big.startIndex) { - $0 == big.endIndex ? nil : big.characterIndex(after: $0) + $0 == big.endIndex ? nil : big.index(after: $0) } ) XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) for i in 0 ..< min(indices1.count, indices2.count) { let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8Distance(from: big.startIndex, to: indices2[i]) + let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) } return (indices1, indices2) @@ -107,7 +107,7 @@ class TestBString: XCTestCase { ) -> (flat: [String.Index], big: [_BString.Index]) { // Check iterators var it1 = flat.unicodeScalars.makeIterator() - var it2 = big.makeUnicodeScalarIterator() + var it2 = big.unicodeScalars.makeIterator() while true { let a = it1.next() let b = it2.next() @@ -122,14 +122,14 @@ class TestBString: XCTestCase { let indices1 = Array(flat.unicodeScalars.indices) + [flat.unicodeScalars.endIndex] let indices2 = Array( sequence(first: big.startIndex) { - $0 == big.endIndex ? nil : big.unicodeScalarIndex(after: $0) + $0 == big.endIndex ? nil : big.unicodeScalars.index(after: $0) } ) XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) for i in 0 ..< min(indices1.count, indices2.count) { let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8Distance(from: big.startIndex, to: indices2[i]) + let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) } return (indices1, indices2) @@ -143,7 +143,7 @@ class TestBString: XCTestCase { ) -> (flat: [String.Index], big: [_BString.Index]) { // Check iterators var it1 = flat.utf8.makeIterator() - var it2 = big.makeUTF8Iterator() + var it2 = big.utf8.makeIterator() while true { let a = it1.next() let b = it2.next() @@ -158,14 +158,14 @@ class TestBString: XCTestCase { let indices1 = Array(flat.utf8.indices) + [flat.utf8.endIndex] let indices2 = Array( sequence(first: big.startIndex) { - $0 == big.endIndex ? nil : big.utf8Index(after: $0) + $0 == big.endIndex ? nil : big.utf8.index(after: $0) } ) XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) for i in 0 ..< min(indices1.count, indices2.count) { let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8Distance(from: big.startIndex, to: indices2[i]) + let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) } return (indices1, indices2) @@ -179,7 +179,7 @@ class TestBString: XCTestCase { ) -> (flat: [String.Index], big: [_BString.Index]) { // Check iterators var it1 = flat.utf16.makeIterator() - var it2 = big.makeUTF16Iterator() + var it2 = big.utf16.makeIterator() while true { let a = it1.next() let b = it2.next() @@ -194,14 +194,14 @@ class TestBString: XCTestCase { let indices1 = Array(flat.utf16.indices) + [flat.utf16.endIndex] let indices2 = Array( sequence(first: big.startIndex) { - $0 == big.endIndex ? nil : big.utf16Index(after: $0) + $0 == big.endIndex ? nil : big.utf16.index(after: $0) } ) XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) for i in 0 ..< min(indices1.count, indices2.count) { let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8Distance(from: big.startIndex, to: indices2[i]) + let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]._description), i2: \(indices2[i])", file: file, line: line) } return (indices1, indices2) @@ -221,7 +221,7 @@ class TestBString: XCTestCase { let a = String(sampleString[i1 ..< j1]) let i2 = indices2[i] - let j2 = big.characterIndex(i2, offsetBy: j - i) + let j2 = big.index(i2, offsetBy: j - i) let b = String(_from: big, in: i2 ..< j2) XCTAssertEqual(b, a) } @@ -240,7 +240,7 @@ class TestBString: XCTestCase { let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) let i2 = indices2[i] - let j2 = big.unicodeScalarIndex(i2, offsetBy: j - i) + let j2 = big.unicodeScalars.index(i2, offsetBy: j - i) let b = String(_from: big, in: i2 ..< j2) XCTAssertEqual(b, a) } @@ -259,7 +259,7 @@ class TestBString: XCTestCase { let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) let i2 = indices2[i] - let j2 = big.utf16Index(i2, offsetBy: j - i) + let j2 = big.utf16.index(i2, offsetBy: j - i) let b = String(_from: big, in: i2 ..< j2) XCTAssertEqual(b, a) } @@ -278,7 +278,7 @@ class TestBString: XCTestCase { let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) let i2 = indices2[i] - let j2 = big.utf8Index(i2, offsetBy: j - i) + let j2 = big.utf8.index(i2, offsetBy: j - i) let b = String(_from: big, in: i2 ..< j2) XCTAssertEqual(b, a) } @@ -303,7 +303,7 @@ class TestBString: XCTestCase { checkUTF8Indices(flat, big) checkScalarIndices(flat, big) checkCharacterIndices(flat, big) - XCTAssertTrue(big.utf8IsEqual(to: ref)) + XCTAssertTrue(big.utf8 == ref.utf8) } } @@ -327,7 +327,7 @@ class TestBString: XCTestCase { checkUTF8Indices(flat, big) checkScalarIndices(flat, big) checkCharacterIndices(flat, big) - XCTAssertTrue(big.utf8IsEqual(to: ref)) + XCTAssertTrue(big.utf8 == ref.utf8) } } @@ -366,7 +366,7 @@ class TestBString: XCTestCase { let j = smol._utf8Index(at: utf8Offset) smol.insert(contentsOf: piece.str, at: j) - let index = big.utf8Index(big.startIndex, offsetBy: utf8Offset) + let index = big.utf8.index(big.startIndex, offsetBy: utf8Offset) //print("\(i)/\(pieces.count): i: \(piece.i), start: \(index), str: \(piece.str._properDebugDescription)") big.insert(contentsOf: piece.str, at: index) @@ -381,7 +381,7 @@ class TestBString: XCTestCase { } } big.invariantCheck() - XCTAssertTrue(big.utf8IsEqual(to: ref)) + XCTAssertTrue(big.utf8 == ref.utf8) checkUTF8Indices(flat, big) checkUTF16Indices(flat, big) checkScalarIndices(flat, big) @@ -426,7 +426,7 @@ class TestBString: XCTestCase { } } big.invariantCheck() - XCTAssertTrue(big.utf8IsEqual(to: ref)) + XCTAssertTrue(big.utf8 == ref.utf8) checkUTF8Indices(flat, big) checkUTF16Indices(flat, big) checkScalarIndices(flat, big) @@ -444,13 +444,13 @@ class TestBString: XCTestCase { line: UInt = #line ) { var current = str.startIndex - var next = str.characterIndex(after: current) + var next = str.index(after: current) for i in indices { if i >= next { current = next - next = str.characterIndex(after: current) + next = str.index(after: current) } - let j = str.characterIndex(roundingDown: i) + let j = str.index(roundingDown: i) XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) XCTAssertEqual(str[character: i], str[character: j], "i: \(i)", file: file, line: line) } @@ -461,7 +461,7 @@ class TestBString: XCTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.characterIndex(roundingDown: str.endIndex), str.endIndex) + XCTAssertEqual(str.index(roundingDown: str.endIndex), str.endIndex) } @@ -476,10 +476,10 @@ class TestBString: XCTestCase { ) { var current = str.startIndex for i in indices { - let j = str.characterIndex(roundingUp: i) + let j = str.index(roundingUp: i) XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) while i >= current { - current = str.characterIndex(after: current) + current = str.index(after: current) } } XCTAssertEqual(current, str.endIndex, "end", file: file, line: line) @@ -489,7 +489,7 @@ class TestBString: XCTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.characterIndex(roundingDown: str.endIndex), str.endIndex) + XCTAssertEqual(str.index(roundingDown: str.endIndex), str.endIndex) } @@ -503,13 +503,13 @@ class TestBString: XCTestCase { line: UInt = #line ) { var current = str.startIndex - var next = str.unicodeScalarIndex(after: current) + var next = str.unicodeScalars.index(after: current) for i in indices { while i >= next { current = next - next = str.unicodeScalarIndex(after: current) + next = str.unicodeScalars.index(after: current) } - let j = str.unicodeScalarIndex(roundingDown: i) + let j = str.unicodeScalars.index(roundingDown: i) XCTAssertEqual(j, current, "\(i)", file: file, line: line) XCTAssertEqual(str[unicodeScalar: i], str[unicodeScalar: j], "i: \(i)", file: file, line: line) } @@ -519,7 +519,7 @@ class TestBString: XCTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.unicodeScalarIndex(roundingDown: str.endIndex), str.endIndex) + XCTAssertEqual(str.unicodeScalars.index(roundingDown: str.endIndex), str.endIndex) } func testUnicodeScalarIndexRoundingUp() { @@ -534,9 +534,9 @@ class TestBString: XCTestCase { var current = str.startIndex for i in indices { while i > current { - current = str.unicodeScalarIndex(after: current) + current = str.unicodeScalars.index(after: current) } - let j = str.unicodeScalarIndex(roundingUp: i) + let j = str.unicodeScalars.index(roundingUp: i) XCTAssertEqual(j, current, "\(i)", file: file, line: line) } } @@ -545,7 +545,7 @@ class TestBString: XCTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.unicodeScalarIndex(roundingDown: str.endIndex), str.endIndex) + XCTAssertEqual(str.unicodeScalars.index(roundingDown: str.endIndex), str.endIndex) } func testSubstringMutationIndexRounding() { From 6a7f53c3da992cdb03097c0b7cc149fc4be4e123 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 20:17:00 -0800 Subject: [PATCH 050/113] _BString: Add conversion initializers from all views --- .../BString/Views/_BString+UTF16View.swift | 4 ++++ .../BString/Views/_BString+UTF8View.swift | 4 ++++ .../BString/Views/_BSubstring+UTF16View.swift | 13 +++++++++++++ .../BString/Views/_BSubstring+UTF8View.swift | 13 +++++++++++++ .../Views/_BSubstring+UnicodeScalarView.swift | 4 ++-- 5 files changed, 36 insertions(+), 2 deletions(-) diff --git a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift index e57dee59..faf34b2d 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift @@ -26,6 +26,10 @@ extension _BString { internal var utf16: UTF16View { UTF16View(_base: self) } + + internal init(_ utf16: UTF16View) { + self = utf16._base + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift index 57eadd6b..ccdc4646 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift @@ -26,6 +26,10 @@ extension _BString { internal var utf8: UTF8View { UTF8View(_base: self) } + + internal init(_ utf8: UTF8View) { + self = utf8._base + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift index 28876789..e16b68e3 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift @@ -39,6 +39,19 @@ extension _BSubstring { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + internal init?(_ utf16: _BSubstring.UTF16View) { + guard + !utf16.startIndex._isUTF16TrailingSurrogate, + !utf16.endIndex._isUTF16TrailingSurrogate + else { + return nil + } + self.init(_from: utf16._base, in: utf16._bounds) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF16View { internal var base: _BString.UTF16View { _base.utf16 } diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift index 3a195739..f8c83458 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift @@ -39,6 +39,19 @@ extension _BSubstring { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + internal init?(_ utf8: _BSubstring.UTF8View) { + guard + utf8._base.unicodeScalars.index(roundingDown: utf8.startIndex) == utf8.startIndex, + utf8._base.unicodeScalars.index(roundingDown: utf8.endIndex) == utf8.endIndex + else { + return nil + } + self.init(_from: utf8._base, in: utf8._bounds) + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF8View { internal var base: _BString.UTF8View { _base.utf8 } diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift index 3e7a4271..212fefe5 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -41,8 +41,8 @@ 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) + internal init(_ unicodeScalars: _BSubstring.UnicodeScalarView) { + self.init(_from: unicodeScalars._base, in: unicodeScalars._bounds) } } From cffcd517a2c471bf9fa8ded3cbcd00389f69abaf Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 20:17:32 -0800 Subject: [PATCH 051/113] BigString: Start modernizing --- .../BigString/BigString+CharacterView.swift | 2 +- .../BigString/BigString+UTF16View.swift | 46 ++--- .../BigString/BigString+UTF8View.swift | 46 ++--- .../BigString+UnicodeScalarView.swift | 193 +++--------------- Sources/RopeModule/BigString/BigString.swift | 6 +- 5 files changed, 62 insertions(+), 231 deletions(-) diff --git a/Sources/RopeModule/BigString/BigString+CharacterView.swift b/Sources/RopeModule/BigString/BigString+CharacterView.swift index b6ec0eb8..efa611f1 100644 --- a/Sources/RopeModule/BigString/BigString+CharacterView.swift +++ b/Sources/RopeModule/BigString/BigString+CharacterView.swift @@ -53,7 +53,7 @@ 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.characterwiseIsEqual(to: right._guts) + left._guts == right._guts } } diff --git a/Sources/RopeModule/BigString/BigString+UTF16View.swift b/Sources/RopeModule/BigString/BigString+UTF16View.swift index 56dba619..6815601f 100644 --- a/Sources/RopeModule/BigString/BigString+UTF16View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF16View.swift @@ -14,35 +14,22 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public struct UTF16View { - internal var _guts: _BString + internal var _guts: _BString.UTF16View - internal init(_guts: _BString) { + internal init(_guts: _BString.UTF16View) { self._guts = _guts } } public var utf16: UTF16View { - get { - UTF16View(_guts: _guts) - } - set { - _guts = newValue._guts - } - _modify { - var view = UTF16View(_guts: _guts) - self._guts = .init() - defer { - self._guts = view._guts - } - yield &view - } + UTF16View(_guts: _guts.utf16) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public init(_ content: UTF16View) { - self._guts = content._guts + self._guts = _BString(content._guts) } } @@ -61,21 +48,14 @@ extension BigString.UTF16View: CustomStringConvertible { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: Equatable { public static func ==(left: Self, right: Self) -> Bool { - _BString.utf8IsEqual(left._guts, to: right._guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF16View: Comparable { - public static func <(left: Self, right: Self) -> Bool { - left._guts.utf8IsLess(than: right._guts) + left._guts == right._guts } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: Hashable { public func hash(into hasher: inout Hasher) { - _guts.hashUTF8(into: &hasher) + _guts.hash(into: &hasher) } } @@ -96,7 +76,7 @@ extension BigString.UTF16View: Sequence { } public func makeIterator() -> Iterator { - Iterator(_base: self._guts.makeUTF16Iterator()) + Iterator(_base: self._guts.makeIterator()) } } @@ -106,7 +86,7 @@ extension BigString.UTF16View: BidirectionalCollection { public typealias Element = UInt16 public var count: Int { - _guts.utf16Count + _guts.count } public var startIndex: Index { @@ -118,23 +98,23 @@ extension BigString.UTF16View: BidirectionalCollection { } public func index(after i: Index) -> Index { - Index(_guts.utf16Index(after: i._value)) + Index(_guts.index(after: i._value)) } public func index(before i: Index) -> Index { - Index(_guts.utf16Index(before: i._value)) + Index(_guts.index(before: i._value)) } public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.utf16Index(i._value, offsetBy: distance)) + Index(_guts.index(i._value, offsetBy: distance)) } public func distance(from start: Index, to end: Index) -> Int { - _guts.utf16Distance(from: start._value, to: end._value) + _guts.distance(from: start._value, to: end._value) } public subscript(position: Index) -> UInt16 { - _guts[utf16: position._value] + _guts[position._value] } } diff --git a/Sources/RopeModule/BigString/BigString+UTF8View.swift b/Sources/RopeModule/BigString/BigString+UTF8View.swift index bc2855db..d05336eb 100644 --- a/Sources/RopeModule/BigString/BigString+UTF8View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF8View.swift @@ -14,35 +14,22 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public struct UTF8View { - internal var _guts: _BString + internal var _guts: _BString.UTF8View - internal init(_guts: _BString) { + internal init(_guts: _BString.UTF8View) { self._guts = _guts } } public var utf8: UTF8View { - get { - UTF8View(_guts: _guts) - } - set { - _guts = newValue._guts - } - _modify { - var view = UTF8View(_guts: _guts) - self._guts = .init() - defer { - self._guts = view._guts - } - yield &view - } + UTF8View(_guts: _guts.utf8) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public init(_ content: UTF8View) { - self._guts = content._guts + self._guts = _BString(content._guts) } } @@ -61,21 +48,14 @@ extension BigString.UTF8View: CustomStringConvertible { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: Equatable { public static func ==(left: Self, right: Self) -> Bool { - _BString.utf8IsEqual(left._guts, to: right._guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF8View: Comparable { - public static func <(left: Self, right: Self) -> Bool { - left._guts.utf8IsLess(than: right._guts) + left._guts == right._guts } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: Hashable { public func hash(into hasher: inout Hasher) { - _guts.hashUTF8(into: &hasher) + _guts.hash(into: &hasher) } } @@ -96,7 +76,7 @@ extension BigString.UTF8View: Sequence { } public func makeIterator() -> Iterator { - Iterator(_base: self._guts.makeUTF8Iterator()) + Iterator(_base: self._guts.makeIterator()) } } @@ -106,7 +86,7 @@ extension BigString.UTF8View: BidirectionalCollection { public typealias Element = UInt8 public var count: Int { - _guts.utf8Count + _guts.count } public var startIndex: Index { @@ -118,23 +98,23 @@ extension BigString.UTF8View: BidirectionalCollection { } public func index(after i: Index) -> Index { - Index(_guts.utf8Index(after: i._value)) + Index(_guts.index(after: i._value)) } public func index(before i: Index) -> Index { - Index(_guts.utf8Index(before: i._value)) + Index(_guts.index(before: i._value)) } public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.utf8Index(i._value, offsetBy: distance)) + Index(_guts.index(i._value, offsetBy: distance)) } public func distance(from start: Index, to end: Index) -> Int { - _guts.utf8Distance(from: start._value, to: end._value) + _guts.distance(from: start._value, to: end._value) } public subscript(position: Index) -> UInt8 { - _guts[utf8: position._value] + _guts[position._value] } } diff --git a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift index 953f0047..ec3229d7 100644 --- a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift @@ -14,25 +14,25 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public struct UnicodeScalarView { - var _guts: _BString - - init(_guts: _BString) { + var _guts: _BString.UnicodeScalarView + + init(_guts: _BString.UnicodeScalarView) { self._guts = _guts } } public var unicodeScalars: UnicodeScalarView { get { - UnicodeScalarView(_guts: _guts) + UnicodeScalarView(_guts: _guts.unicodeScalars) } set { - _guts = newValue._guts + _guts = newValue._guts._base } _modify { - var view = UnicodeScalarView(_guts: _guts) + var view = UnicodeScalarView(_guts: _guts.unicodeScalars) self._guts = .init() defer { - self._guts = view._guts + self._guts = view._guts._base } yield &view } @@ -42,42 +42,35 @@ extension BigString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public init(_ content: UnicodeScalarView) { - self._guts = content._guts + self._guts = _BString(content._guts) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: ExpressibleByStringLiteral { public init(stringLiteral value: String) { - self.init(_guts: _BString(value)) + self.init(_guts: _BString(value).unicodeScalars) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: CustomStringConvertible { public var description: String { - String(_from: _guts) + String(_from: _guts._base) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: Equatable { public static func ==(left: Self, right: Self) -> Bool { - _BString.utf8IsEqual(left._guts, to: right._guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UnicodeScalarView: Comparable { - public static func <(left: Self, right: Self) -> Bool { - left._guts.utf8IsLess(than: right._guts) + left._guts == right._guts } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: Hashable { public func hash(into hasher: inout Hasher) { - _guts.hashUTF8(into: &hasher) + _guts.hash(into: &hasher) } } @@ -98,7 +91,7 @@ extension BigString.UnicodeScalarView: Sequence { } public func makeIterator() -> Iterator { - Iterator(_base: _guts.makeUnicodeScalarIterator()) + Iterator(_base: _guts.makeIterator()) } } @@ -108,7 +101,7 @@ extension BigString.UnicodeScalarView: BidirectionalCollection { public typealias Index = BigString.Index public var count: Int { - _guts.unicodeScalarCount + _guts.count } public var startIndex: Index { @@ -120,23 +113,23 @@ extension BigString.UnicodeScalarView: BidirectionalCollection { } public func index(after i: Index) -> Index { - Index(_guts.unicodeScalarIndex(after: i._value)) + Index(_guts.index(after: i._value)) } public func index(before i: Index) -> Index { - Index(_guts.unicodeScalarIndex(after: i._value)) + Index(_guts.index(after: i._value)) } public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.unicodeScalarIndex(i._value, offsetBy: distance)) + Index(_guts.index(i._value, offsetBy: distance)) } public func distance(from start: Index, to end: Index) -> Int { - _guts.unicodeScalarDistance(from: start._value, to: end._value) + _guts.distance(from: start._value, to: end._value) } public subscript(index: Index) -> Unicode.Scalar { - _guts[unicodeScalar: index._value] + _guts[index._value] } } @@ -151,38 +144,7 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { _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( - _ subrange: Range, - with newElements: __owned String.UnicodeScalarView - ) { - _guts.replaceSubrange(subrange._base, with: String(newElements)) - } - - public mutating func replaceSubrange( - _ subrange: Range, - with newElements: __owned Substring.UnicodeScalarView - ) { - _guts.replaceSubrange(subrange._base, with: Substring(newElements)) - } - - public mutating func replaceSubrange( - _ subrange: Range, - with newElements: __owned BigString.UnicodeScalarView - ) { - _guts.replaceSubrange(subrange._base, with: newElements._guts) + _guts.replaceSubrange(subrange._base, with: newElements) } public mutating func reserveCapacity(_ n: Int) {} @@ -197,43 +159,15 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { self._guts = elements._guts 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) + self._guts = _BString.UnicodeScalarView(elements) } - public init(_ elements: String.UnicodeScalarView) { - self._guts = _BString(_from: String(elements)) + public init(repeating scalar: UnicodeScalar, count: Int) { + self._guts = _BString.UnicodeScalarView(repeating: scalar, count: count) } - public init(_ elements: Substring.UnicodeScalarView) { - self._guts = _BString(_from: Substring(elements)) - } - - public init(_ elements: Self) { - self._guts = elements._guts - } - - public init(_ elements: Self.SubSequence) { - let lower = elements.startIndex._value - let upper = elements.endIndex._value - self._guts = _BString(_from: elements.base._guts, in: lower ..< upper) - } - - public init(repeating scalar: Unicode.Scalar, count: Int) { - self._guts = _BString(repeating: _BString(String(scalar)), count: count) - } - - public mutating func append(_ newElement: __owned Element) { - _guts.append(contentsOf: String(newElement)) + public mutating func append(_ newElement: __owned UnicodeScalar) { + _guts.append(newElement) } public mutating func append( @@ -246,44 +180,15 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { } 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) + let range = newElements.startIndex ..< newElements.endIndex + _guts.append(contentsOf: newElements.base._guts[range._base]) 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) { - _guts.append(contentsOf: String(newElements)) - } - - public mutating func append(contentsOf newElements: __owned Substring.UnicodeScalarView) { - _guts.append(contentsOf: Substring(newElements)) - } - - public mutating func append(contentsOf newElements: __owned Self) { - _guts.append(contentsOf: newElements._guts) - } - - 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) } public mutating func insert(_ newElement: __owned Unicode.Scalar, at i: Index) { - _guts.insert(contentsOf: String(newElement), at: i._value) + _guts.insert(newElement, at: i._value) } public mutating func insert>( @@ -296,46 +201,16 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { } 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) + let range = newElements.startIndex ..< newElements.endIndex + self._guts.insert(contentsOf: newElements.base._guts[range._base], 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) { - _guts.insert(contentsOf: String(newElements), at: i._value) - } - - public mutating func insert(contentsOf newElements: Substring.UnicodeScalarView, at i: Index) { - _guts.insert(contentsOf: Substring(newElements), at: i._value) - } - - public mutating func insert(contentsOf newElements: Self, at i: Index) { - _guts.insert(contentsOf: newElements._guts, at: i._value) - } - - 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, at: i._value) } @discardableResult public mutating func remove(at i: Index) -> Unicode.Scalar { - _guts.removeUnicodeScalar(at: i._value) + _guts.remove(at: i._value) } public mutating func removeSubrange(_ bounds: Range) { @@ -343,7 +218,7 @@ extension BigString.UnicodeScalarView: RangeReplaceableCollection { } public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - _guts = _BString() + _guts.removeAll(keepingCapacity: keepCapacity) } } diff --git a/Sources/RopeModule/BigString/BigString.swift b/Sources/RopeModule/BigString/BigString.swift index e52722b1..62a03d94 100644 --- a/Sources/RopeModule/BigString/BigString.swift +++ b/Sources/RopeModule/BigString/BigString.swift @@ -69,11 +69,7 @@ extension String { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String.UnicodeScalarView { public init(_ big: BigString.UnicodeScalarView) { - self = String(_from: big._guts).unicodeScalars - } - - public init(_ big: BigString.UnicodeScalarView.SubSequence) { - self = String().unicodeScalars + self = String(_from: big._guts._base).unicodeScalars } } From 22113290f1eea1fea51cb15e2f487d440c019528 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 Mar 2023 20:18:13 -0800 Subject: [PATCH 052/113] _BString: Adjust substring mutation test to actually exercise Unicode weirdness --- Tests/RopeModuleTests/TestBString.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 1db14a97..423291d7 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -564,10 +564,10 @@ class TestBString: XCTestCase { 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🇺🇸🇨🇦🇺🇸🇨🇦") + var s3: _BSubstring = b3.prefix(6) + 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, "Foo🇭🇺🇸🇨🇦🇺") // Regional indicators "HUSCAUSCA" XCTAssertEqual(s3.base, "Foo🇭🇺🇸🇨🇦🇺🇸🇨\u{1f1e6}bar") } } From 033bf17f9d8e96f673fe633463fc386a824e2529 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 13 Mar 2023 13:54:15 -0700 Subject: [PATCH 053/113] _BString: Add UTF-8 and UTF-16 index rounding tests UTF-16 index rounding is a semantic mess; the behavior is emulating the stdlib, and it seems far more useful than if we went with a semantically consistent definition. --- Tests/RopeModuleTests/TestBString.swift | 120 +++++++++++++++++++++++- 1 file changed, 119 insertions(+), 1 deletion(-) diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 423291d7..228d8bf8 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -537,7 +537,7 @@ class TestBString: XCTestCase { current = str.unicodeScalars.index(after: current) } let j = str.unicodeScalars.index(roundingUp: i) - XCTAssertEqual(j, current, "\(i)", file: file, line: line) + XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) } } @@ -548,6 +548,124 @@ class TestBString: XCTestCase { XCTAssertEqual(str.unicodeScalars.index(roundingDown: str.endIndex), str.endIndex) } + func testUTF8IndexRoundingDown() { + let ref = sampleString + let str = _BString(ref) + + func check( + _ indices: some Sequence<_BString.Index>, + file: StaticString = #file, + line: UInt = #line + ) { + var current = str.startIndex + var next = str.utf8.index(after: current) + for i in indices { + while i >= next { + current = next + next = str.utf8.index(after: current) + } + let j = str.utf8.index(roundingDown: i) + XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + XCTAssertEqual(str[utf8: i], str[utf8: j], "i: \(i)", file: file, line: line) + } + } + + check(str.utf8.indices) + check(str.utf16.indices) + check(str.unicodeScalars.indices) + check(str.indices) + XCTAssertEqual(str.utf8.index(roundingDown: str.endIndex), str.endIndex) + } + + func testUTF8IndexRoundingUp() { + 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.utf8.index(after: current) + } + let j = str.utf8.index(roundingUp: i) + XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + } + } + + check(str.utf8.indices) + check(str.utf16.indices) + check(str.unicodeScalars.indices) + check(str.indices) + XCTAssertEqual(str.utf8.index(roundingDown: str.endIndex), str.endIndex) + } + + func testUTF16IndexRoundingDown() { + let ref = sampleString + let str = _BString(ref) + + func check( + _ indices: some Sequence<_BString.Index>, + file: StaticString = #file, + line: UInt = #line + ) { + var current = str.startIndex + // Note: UTF-16 index rounding is not rounding in the usual sense -- it rounds UTF-8 indices + // down to the nearest scalar boundary, not the nearest UTF-16 index. This is because + // UTF-16 indices addressing trailing surrogates are ordered below UTF-8 continuation bytes, + // but this rounds those down to the scalar. + var next = str.unicodeScalars.index(after: current) // Note: intentionally not utf16 + for i in indices { + while i >= next { + current = next + next = str.unicodeScalars.index(after: current) // Note: intentionally not utf16 + } + let j = str.utf16.index(roundingDown: i) + if i._isUTF16TrailingSurrogate { + XCTAssertEqual(j, i, "i: \(i)", file: file, line: line) + } else { + XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + } + XCTAssertEqual(str[utf16: i], str[utf16: j], "i: \(i)", file: file, line: line) + } + } + + check(str.utf8.indices) + check(str.utf16.indices) + check(str.unicodeScalars.indices) + check(str.indices) + XCTAssertEqual(str.utf16.index(roundingDown: str.endIndex), str.endIndex) + } + + func testUTF1t6IndexRoundingUp() { + 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.utf8.index(after: current) + } + let j = str.utf8.index(roundingUp: i) + XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + } + } + + check(str.utf8.indices) + check(str.utf16.indices) + check(str.unicodeScalars.indices) + check(str.indices) + XCTAssertEqual(str.utf8.index(roundingDown: str.endIndex), str.endIndex) + } + func testSubstringMutationIndexRounding() { let b1: _BString = "Foobar" var s1 = b1.suffix(3) From d79a752fc86a03c353537dc2964959ac7198c37c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 13 Mar 2023 18:49:12 -0700 Subject: [PATCH 054/113] _BString: Review views & add missing functionality/shortcuts --- ...BString+CustomDebugStringConvertible.swift | 21 +++++ .../_BString+RangeReplaceableCollection.swift | 28 +++--- .../Operations/_BString+Initializers.swift | 12 +++ .../Views/_BString+UnicodeScalarView.swift | 25 +++++- .../Views/_BSubstring+UnicodeScalarView.swift | 60 +++++++------ .../BString/Views/_BSubstring.swift | 87 ++++++++++++++++++- Tests/RopeModuleTests/TestBString.swift | 27 ++++++ Tests/RopeModuleTests/TestBString2.swift | 29 ++++++- 8 files changed, 243 insertions(+), 46 deletions(-) create mode 100644 Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift diff --git a/Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift b/Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift new file mode 100644 index 00000000..5ff96a31 --- /dev/null +++ b/Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.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: CustomDebugStringConvertible { + internal var debugDescription: String { + description.debugDescription + } +} + +#endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift b/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift index 7bf4da19..62382c8b 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift @@ -21,19 +21,19 @@ extension _BString: RangeReplaceableCollection { // Do nothing. } - internal mutating func replaceSubrange>( - _ subrange: Range, with newElements: __owned C + internal mutating func replaceSubrange>( // Note: Sequence, not Collection + _ subrange: Range, with newElements: __owned S ) { - if C.self == String.self { + if S.self == String.self { let newElements = _identityCast(newElements, to: String.self) self._replaceSubrange(subrange, with: newElements) - } else if C.self == Substring.self { + } else if S.self == Substring.self { let newElements = _identityCast(newElements, to: Substring.self) self._replaceSubrange(subrange, with: newElements) - } else if C.self == _BString.self { + } else if S.self == _BString.self { let newElements = _identityCast(newElements, to: _BString.self) self._replaceSubrange(subrange, with: newElements) - } else if C.self == _BSubstring.self { + } else if S.self == _BSubstring.self { let newElements = _identityCast(newElements, to: _BSubstring.self) self._replaceSubrange(subrange, with: newElements) } else { @@ -128,6 +128,10 @@ extension _BString: RangeReplaceableCollection { } } + internal init(repeating value: _BSubstring, count: Int) { + self.init(repeating: _BString(value), count: count) + } + internal mutating func append(_ newElement: __owned Character) { append(contentsOf: String(newElement)) } @@ -170,19 +174,19 @@ extension _BString: RangeReplaceableCollection { insert(contentsOf: String(newElement), at: i) } - internal mutating func insert>( - contentsOf newElements: __owned C, at i: Index + internal mutating func insert>( // Note: Sequence, not Collection + contentsOf newElements: __owned S, at i: Index ) { - if C.self == String.self { + if S.self == String.self { let newElements = _identityCast(newElements, to: String.self) insert(contentsOf: newElements, at: i) - } else if C.self == Substring.self { + } else if S.self == Substring.self { let newElements = _identityCast(newElements, to: Substring.self) insert(contentsOf: newElements, at: i) - } else if C.self == _BString.self { + } else if S.self == _BString.self { let newElements = _identityCast(newElements, to: _BString.self) insert(contentsOf: newElements, at: i) - } else if C.self == _BSubstring.self { + } else if S.self == _BSubstring.self { let newElements = _identityCast(newElements, to: _BSubstring.self) insert(contentsOf: newElements, at: i) } else { diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index b0c9a82c..b9ecb469 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -133,6 +133,18 @@ extension String { } self += big.rope[endRopeIndex].string[.. Bool { @@ -122,7 +143,7 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { // Do nothing. } - internal mutating func replaceSubrange>( + internal mutating func replaceSubrange>( // Note: Sequence, not Collection _ subrange: Range, with newElements: __owned C ) { if C.self == String.UnicodeScalarView.self { @@ -259,7 +280,7 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { _base.insert(contentsOf: String(newElement), at: i) } - internal mutating func insert>( + internal mutating func insert>( // Note: Sequence, not Collection contentsOf newElements: __owned C, at i: Index ) { if C.self == String.UnicodeScalarView.self { diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift index 212fefe5..355935d7 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -51,6 +51,27 @@ extension _BSubstring.UnicodeScalarView { internal var base: _BString.UnicodeScalarView { _base.unicodeScalars } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UnicodeScalarView: ExpressibleByStringLiteral { + internal init(stringLiteral value: String) { + self.init(value.unicodeScalars) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring.UnicodeScalarView: 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.UnicodeScalarView: CustomDebugStringConvertible { + internal var debugDescription: String { + description.debugDescription + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: Equatable { internal static func ==(left: Self, right: Self) -> Bool { @@ -206,41 +227,28 @@ extension _BSubstring.UnicodeScalarView: RangeReplaceableCollection { // Do nothing. } - internal mutating func replaceSubrange>( + internal mutating func replaceSubrange>( // Note: Sequence, not Collection _ 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 init(repeating repeatedValue: UnicodeScalar, count: Int) { + let base = _BString.UnicodeScalarView(repeating: repeatedValue, count: count) + self.init(base._base, in: base.startIndex ..< base.endIndex) + } + + internal mutating func append(_ newElement: UnicodeScalar) { + _mutateBasePreservingBounds(in: endIndex ..< endIndex) { + $0.append(newElement) + } + } + internal mutating func append>(contentsOf newElements: __owned S) { _mutateBasePreservingBounds(in: endIndex ..< endIndex) { $0.append(contentsOf: newElements) @@ -254,7 +262,7 @@ extension _BSubstring.UnicodeScalarView: RangeReplaceableCollection { } - internal mutating func insert>( + internal mutating func insert>( // Note: Sequence, not Collection contentsOf newElements: __owned C, at i: Index ) { _mutateBasePreservingBounds(in: i ..< i) { diff --git a/Sources/RopeModule/BString/Views/_BSubstring.swift b/Sources/RopeModule/BString/Views/_BSubstring.swift index a975678f..590438ba 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring.swift @@ -53,6 +53,13 @@ extension _BSubstring: CustomStringConvertible { } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BSubstring: CustomDebugStringConvertible { + internal var debugDescription: String { + description.debugDescription + } +} + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring: ExpressibleByStringLiteral { internal init(stringLiteral value: String) { @@ -269,13 +276,87 @@ extension _BSubstring: RangeReplaceableCollection { self.init(_unchecked: str, in: bounds) } - internal mutating func replaceSubrange( - _ subrange: Range, with newElements: C - ) where C.Element == Character { + internal mutating func reserveCapacity(_ n: Int) { + // Do nothing. + } + + internal mutating func replaceSubrange>( // Note: Sequence, not Collection + _ subrange: Range, with newElements: __owned C + ) { _mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) } } + + internal init>(_ elements: S) { + let base = _BString(elements) + self.init(base, in: base.startIndex ..< base.endIndex) + } + + internal init(repeating repeatedValue: Character, count: Int) { + self.init(_BString(repeating: repeatedValue, count: count)) + } + + internal init(repeating repeatedValue: some StringProtocol, count: Int) { + self.init(_BString(repeating: repeatedValue, count: count)) + } + + internal init(repeating repeatedValue: _BString, count: Int) { + self.init(_BString(repeating: repeatedValue, count: count)) + } + + internal init(repeating repeatedValue: _BSubstring, count: Int) { + self.init(_BString(repeating: repeatedValue, count: count)) + } + + internal mutating func append(_ newElement: Character) { + let i = endIndex + _mutateBasePreservingBounds(in: i ..< i) { + $0.insert(newElement, at: i) + } + } + + internal mutating func append>(contentsOf newElements: __owned S) { + let i = endIndex + _mutateBasePreservingBounds(in: i ..< i) { + $0.insert(contentsOf: newElements, at: i) + } + } + + internal mutating func insert(_ newElement: Character, at i: Index) { + _mutateBasePreservingBounds(in: i ..< i) { + $0.insert(newElement, at: i) + } + } + + internal mutating func insert>( // Note: Sequence, not Collection + 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) -> Character { + let j = self.index(after: i) + return _mutateBasePreservingBounds(in: i ..< j) { + $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 = self._bounds + _mutateBasePreservingBounds(in: bounds) { + $0.removeSubrange(bounds) + } + } } #endif diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 228d8bf8..420e95dc 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -688,5 +688,32 @@ class TestBString: XCTestCase { XCTAssertEqual(s3, "Foo🇭🇺🇸🇨🇦🇺") // Regional indicators "HUSCAUSCA" XCTAssertEqual(s3.base, "Foo🇭🇺🇸🇨🇦🇺🇸🇨\u{1f1e6}bar") } + + func test_ExpressibleByStringLiteral_and_CustomStringConvertible() { + let a: _BString = "foobar" + XCTAssertEqual(a.description, "foobar") + XCTAssertEqual(a.debugDescription, "\"foobar\"") + + let b: _BSubstring = "foobar" + XCTAssertEqual(b.description, "foobar") + XCTAssertEqual(b.debugDescription, "\"foobar\"") + + let c: _BString.UnicodeScalarView = "foobar" + XCTAssertEqual(c.description, "foobar") + XCTAssertEqual(c.debugDescription, "\"foobar\"") + + let d: _BSubstring.UnicodeScalarView = "foobar" + XCTAssertEqual(d.description, "foobar") + XCTAssertEqual(d.debugDescription, "\"foobar\"") + } + + func testCharacterwiseEquality() { + let cafe1: _BString = "Cafe\u{301}" + let cafe2: _BString = "Café" + XCTAssertEqual(cafe1, cafe2) + XCTAssertNotEqual(cafe1.unicodeScalars, cafe2.unicodeScalars) + XCTAssertNotEqual(cafe1.utf8, cafe2.utf8) + XCTAssertNotEqual(cafe1.utf16, cafe2.utf16) + } } #endif diff --git a/Tests/RopeModuleTests/TestBString2.swift b/Tests/RopeModuleTests/TestBString2.swift index a4ea9322..81c2736f 100644 --- a/Tests/RopeModuleTests/TestBString2.swift +++ b/Tests/RopeModuleTests/TestBString2.swift @@ -20,21 +20,44 @@ class TestBString2: CollectionTestCase { let str = _BString(shortSample) checkBidirectionalCollection(str.utf8, expectedContents: shortSample.utf8) } - + func testUTF16View() { let str = _BString(shortSample) checkBidirectionalCollection(str.utf16, expectedContents: shortSample.utf16) } - + func testUnicodeScalarView() { let str = _BString(shortSample) checkBidirectionalCollection(str.unicodeScalars, expectedContents: shortSample.unicodeScalars) } - + func testCharacterView() { let str = _BString(shortSample) checkBidirectionalCollection(str, expectedContents: shortSample) } + + func testHashable_Characters() { + let classes: [[_BString]] = [ + ["Cafe\u{301}", "Café"], + ["Foo\u{301}\u{327}", "Foo\u{327}\u{301}"], + ["Foo;bar", "Foo\u{37e}bar"], + ] + checkHashable(equivalenceClasses: classes) + } + + func testHashable_Scalars() { + let classes: [_BString] = [ + "Cafe\u{301}", + "Café", + "Foo\u{301}\u{327}", + "Foo\u{327}\u{301}", + "Foo;bar", + "Foo\u{37e}bar", + ] + checkHashable(equivalenceClasses: classes.map { [$0.unicodeScalars] }) + checkHashable(equivalenceClasses: classes.map { [$0.utf8] }) + checkHashable(equivalenceClasses: classes.map { [$0.utf16] }) + } } #endif From b8927d819b2b712c9edc7d5f9a8ba83d43dd9db7 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 13 Mar 2023 18:49:52 -0700 Subject: [PATCH 055/113] BigString: Flesh out views, make them consistent with _BString --- .../BigString/BigString+CharacterView.swift | 191 ++++++--------- .../BigString/BigString+UTF16View.swift | 8 +- .../BigString/BigString+UTF8View.swift | 8 +- .../BigString+UnicodeScalarView.swift | 8 +- Sources/RopeModule/BigString/BigString.swift | 20 +- .../BigString/BigSubstring+UTF16View.swift | 117 +++++++++ .../BigString/BigSubstring+UTF8View.swift | 117 +++++++++ .../BigSubstring+UnicodeScalarView.swift | 227 +++++++++++++++++ .../RopeModule/BigString/BigSubstring.swift | 228 ++++++++++++++++++ Tests/RopeModuleTests/TestBigString.swift | 101 ++++---- 10 files changed, 861 insertions(+), 164 deletions(-) create mode 100644 Sources/RopeModule/BigString/BigSubstring+UTF16View.swift create mode 100644 Sources/RopeModule/BigString/BigSubstring+UTF8View.swift create mode 100644 Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift create mode 100644 Sources/RopeModule/BigString/BigSubstring.swift diff --git a/Sources/RopeModule/BigString/BigString+CharacterView.swift b/Sources/RopeModule/BigString/BigString+CharacterView.swift index efa611f1..72380c31 100644 --- a/Sources/RopeModule/BigString/BigString+CharacterView.swift +++ b/Sources/RopeModule/BigString/BigString+CharacterView.swift @@ -73,6 +73,8 @@ extension BigString: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: Sequence { + public typealias Element = Character + public struct Iterator: IteratorProtocol { public typealias Element = Character @@ -88,78 +90,60 @@ extension BigString: Sequence { } public func makeIterator() -> Iterator { - Iterator(_base: _guts.makeCharacterIterator()) + Iterator(_base: _guts.makeIterator()) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: BidirectionalCollection { - public typealias Element = Character + public typealias SubSequence = BigSubstring - public var count: Int { - _guts.characterCount - } - - public var startIndex: Index { - Index(_guts.startIndex) - } - - public var endIndex: Index { - Index(_guts.endIndex) - } - - public func index(after i: Index) -> Index { - Index(_guts.characterIndex(after: i._value)) - } - - public func index(before i: Index) -> Index { - Index(_guts.characterIndex(before: i._value)) - } + public var count: Int { _guts.count } + public var startIndex: Index { Index(_guts.startIndex) } + public var endIndex: Index { Index(_guts.endIndex) } + public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } + public func index(before i: Index) -> Index { Index(_guts.index(before: i._value)) } public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.characterIndex(i._value, offsetBy: distance)) + Index(_guts.index(i._value, offsetBy: distance)) + } + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } } - public func distance(from start: Index, to end: Index) -> Int { - _guts.characterDistance(from: start._value, to: end._value) + _guts.distance(from: start._value, to: end._value) } - public subscript(position: Index) -> Character { - _guts[character: position._value] + _guts[position._value] + } + public subscript(bounds: Range) -> BigSubstring { + BigSubstring(_guts: _guts[bounds._base]) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: RangeReplaceableCollection { - public mutating func replaceSubrange( + public init() { + self.init(_guts: _BString()) + } + + public mutating func reserveCapacity(_ n: Int) {} + + public mutating func replaceSubrange>( // Note: Sequence, not Collection _ subrange: Range, - with newElements: __owned some Collection + with newElements: __owned C ) { - if let newElements = newElements as? Self { + if C.self == BigString.self { + let newElements = _identityCast(newElements, to: BigString.self) replaceSubrange(subrange, with: newElements) - } else if let newElements = newElements as? String { - replaceSubrange(subrange, with: newElements) - } else if let newElements = newElements as? Substring { + } else if C.self == BigSubstring.self { + let newElements = _identityCast(newElements, to: BigSubstring.self) replaceSubrange(subrange, with: newElements) } else { - _guts.replaceSubrange(subrange._base, with: _BString(newElements)) + _guts.replaceSubrange(subrange._base, with: newElements) } } - public mutating func replaceSubrange( - _ subrange: Range, - with newElements: __owned String - ) { - _guts.replaceSubrange(subrange._base, with: newElements) - } - - public mutating func replaceSubrange( - _ subrange: Range, - with newElements: __owned Substring - ) { - _guts.replaceSubrange(subrange._base, with: newElements) - } - public mutating func replaceSubrange( _ subrange: Range, with newElements: __owned BigString @@ -167,36 +151,31 @@ extension BigString: RangeReplaceableCollection { _guts.replaceSubrange(subrange._base, with: newElements._guts) } - public mutating func reserveCapacity(_ n: Int) {} + public mutating func replaceSubrange( + _ subrange: Range, + with newElements: __owned BigSubstring + ) { + _guts.replaceSubrange(subrange._base, with: newElements._guts) + } - public init(_ elements: some Sequence) { - if let elements = elements as? Self { - self._guts = elements._guts - } else if let elements = elements as? String { - self._guts = _BString(elements) - } else if let elements = elements as? Substring { - self._guts = _BString(elements) + public init>(_ elements: S) { + if S.self == BigString.self { + let newElements = _identityCast(elements, to: BigString.self) + self.init(_guts: newElements._guts) + } else if S.self == BigSubstring.self { + let newElements = _identityCast(elements, to: BigSubstring.self) + self.init(_guts: _BString(newElements._guts)) } else { - self._guts = _BString(elements) + self.init(_guts: _BString(elements)) } } - public init(_ elements: String) { - self._guts = _BString(elements) - } - - public init(_ elements: Substring) { - self._guts = _BString(elements) - } - - public init(_ elements: Self) { + public init(_ elements: BigString) { self._guts = elements._guts } - public init(_ elements: Self.SubSequence) { - let lower = elements.startIndex._value - let upper = elements.endIndex._value - self._guts = _BString(_from: elements.base._guts, in: lower ..< upper) + public init(_ elements: BigSubstring) { + self._guts = _BString(elements._guts) } public init(repeating repeatedValue: Character, count: Int) { @@ -207,81 +186,69 @@ extension BigString: RangeReplaceableCollection { self._guts = _BString(repeating: _BString(repeatedValue), count: count) } - public init(repeating repeatedValue: Self, count: Int) { + public init(repeating repeatedValue: BigString, count: Int) { + self._guts = _BString(repeating: repeatedValue._guts, count: count) + } + + public init(repeating repeatedValue: BigSubstring, count: Int) { self._guts = _BString(repeating: repeatedValue._guts, count: count) } public mutating func append(_ newElement: __owned Character) { - _guts.append(contentsOf: String(newElement)) + _guts.append(newElement) } - public mutating func append(contentsOf newElements: __owned some Sequence) { - if let newElements = newElements as? Self { + public mutating func append>( + contentsOf newElements: __owned S + ) { + if S.self == BigString.self { + let newElements = _identityCast(newElements, to: BigString.self) self.append(contentsOf: newElements) - } else if let newElements = newElements as? String { - self.append(contentsOf: newElements) - } else if let newElements = newElements as? Substring { + } else if S.self == BigSubstring.self { + let newElements = _identityCast(newElements, to: BigSubstring.self) self.append(contentsOf: newElements) } else { - _guts.append(contentsOf: _BString(newElements)) + _guts.append(contentsOf: newElements) } } - public mutating func append(contentsOf newElements: __owned String) { - _guts.append(contentsOf: newElements) - } - - public mutating func append(contentsOf newElements: __owned Substring) { - _guts.append(contentsOf: newElements) - } - - public mutating func append(contentsOf newElements: __owned Self) { + public mutating func append(contentsOf newElements: __owned BigString) { _guts.append(contentsOf: newElements._guts) } - 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) + public mutating func append(contentsOf newElements: __owned BigSubstring) { + _guts.append(contentsOf: newElements._guts) } public mutating func insert(_ newElement: __owned Character, at i: Index) { - _guts.insert(contentsOf: String(newElement), at: i._value) + _guts.insert(newElement, at: i._value) } - public mutating func insert(contentsOf newElements: some Collection, at i: Index) { - if let newElements = newElements as? Self { + public mutating func insert>( // Note: Sequence, not Collection + contentsOf newElements: __owned S, at i: Index + ) { + if S.self == BigString.self { + let newElements = _identityCast(newElements, to: BigString.self) self.insert(contentsOf: newElements, at: i) - } else if let newElements = newElements as? String { - self.insert(contentsOf: newElements, at: i) - } else if let newElements = newElements as? Substring { + } else if S.self == BigSubstring.self { + let newElements = _identityCast(newElements, to: BigSubstring.self) self.insert(contentsOf: newElements, at: i) } else { - _guts.insert(contentsOf: _BString(newElements), at: i._value) + _guts.insert(contentsOf: newElements, at: i._value) } } - public mutating func insert(contentsOf newElements: String, at i: Index) { - _guts.insert(contentsOf: newElements, at: i._value) - } - - public mutating func insert(contentsOf newElements: Substring, at i: Index) { - _guts.insert(contentsOf: newElements, at: i._value) - } - - public mutating func insert(contentsOf newElements: Self, at i: Index) { + public mutating func insert(contentsOf newElements: __owned BigString, at i: Index) { _guts.insert(contentsOf: newElements._guts, at: i._value) } - 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) + public mutating func insert(contentsOf newElements: __owned BigSubstring, at i: Index) { + _guts.insert(contentsOf: newElements._guts, at: i._value) } @discardableResult public mutating func remove(at i: Index) -> Character { - _guts.removeCharacter(at: i._value) + _guts.remove(at: i._value) } public mutating func removeSubrange(_ bounds: Range) { @@ -289,7 +256,7 @@ extension BigString: RangeReplaceableCollection { } public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - _guts = _BString() + _guts.removeAll(keepingCapacity: keepCapacity) } } diff --git a/Sources/RopeModule/BigString/BigString+UTF16View.swift b/Sources/RopeModule/BigString/BigString+UTF16View.swift index 6815601f..96a85e12 100644 --- a/Sources/RopeModule/BigString/BigString+UTF16View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF16View.swift @@ -61,6 +61,8 @@ extension BigString.UTF16View: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: Sequence { + public typealias Element = UInt16 + public struct Iterator: IteratorProtocol { public typealias Element = UInt16 @@ -83,7 +85,7 @@ extension BigString.UTF16View: Sequence { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: BidirectionalCollection { public typealias Index = BigString.Index - public typealias Element = UInt16 + public typealias SubSequence = BigSubstring.UTF16View public var count: Int { _guts.count @@ -116,6 +118,10 @@ extension BigString.UTF16View: BidirectionalCollection { public subscript(position: Index) -> UInt16 { _guts[position._value] } + + public subscript(bounds: Range) -> BigSubstring.UTF16View { + BigSubstring.UTF16View(_guts: _guts[bounds._base]) + } } #endif diff --git a/Sources/RopeModule/BigString/BigString+UTF8View.swift b/Sources/RopeModule/BigString/BigString+UTF8View.swift index d05336eb..c388e70c 100644 --- a/Sources/RopeModule/BigString/BigString+UTF8View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF8View.swift @@ -61,6 +61,8 @@ extension BigString.UTF8View: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: Sequence { + public typealias Element = UInt8 + public struct Iterator: IteratorProtocol { public typealias Element = UInt8 @@ -83,7 +85,7 @@ extension BigString.UTF8View: Sequence { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: BidirectionalCollection { public typealias Index = BigString.Index - public typealias Element = UInt8 + public typealias SubSequence = BigSubstring.UTF8View public var count: Int { _guts.count @@ -116,6 +118,10 @@ extension BigString.UTF8View: BidirectionalCollection { public subscript(position: Index) -> UInt8 { _guts[position._value] } + + public subscript(bounds: Range) -> BigSubstring.UTF8View { + BigSubstring.UTF8View(_guts: _guts[bounds._base]) + } } #endif diff --git a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift index ec3229d7..118231b8 100644 --- a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift @@ -76,6 +76,8 @@ extension BigString.UnicodeScalarView: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: Sequence { + public typealias Element = Unicode.Scalar + public struct Iterator: IteratorProtocol { public typealias Element = Unicode.Scalar @@ -97,8 +99,8 @@ extension BigString.UnicodeScalarView: Sequence { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: BidirectionalCollection { - public typealias Element = Unicode.Scalar public typealias Index = BigString.Index + public typealias SubSequence = BigSubstring.UnicodeScalarView public var count: Int { _guts.count @@ -131,6 +133,10 @@ extension BigString.UnicodeScalarView: BidirectionalCollection { public subscript(index: Index) -> Unicode.Scalar { _guts[index._value] } + + public subscript(bounds: Range) -> BigSubstring.UnicodeScalarView { + BigSubstring.UnicodeScalarView(_guts: _guts[bounds._base]) + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Sources/RopeModule/BigString/BigString.swift b/Sources/RopeModule/BigString/BigString.swift index 62a03d94..eb8d5ac9 100644 --- a/Sources/RopeModule/BigString/BigString.swift +++ b/Sources/RopeModule/BigString/BigString.swift @@ -18,10 +18,6 @@ public struct BigString: Sendable { internal init(_guts: _BString) { self._guts = _guts } - - public init() { - _guts = _BString() - } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) @@ -60,9 +56,17 @@ extension String { public init(_ big: BigString) { self.init(_from: big._guts) } + + public init(_ big: BigSubstring) { + self.init(_from: big._guts) + } - public init(_ big: BigString.SubSequence) { - self.init(_from: big.base._guts, in: big.startIndex._value ..< big.endIndex._value) + public init(_ big: BigString.UnicodeScalarView) { + self.init(_from: big._guts) + } + + public init(_ big: BigSubstring.UnicodeScalarView) { + self.init(_from: big._guts) } } @@ -71,6 +75,10 @@ extension String.UnicodeScalarView { public init(_ big: BigString.UnicodeScalarView) { self = String(_from: big._guts._base).unicodeScalars } + + public init(_ big: BigSubstring.UnicodeScalarView) { + self = String(_from: big._guts._base).unicodeScalars + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift b/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift new file mode 100644 index 00000000..e43df1bb --- /dev/null +++ b/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift @@ -0,0 +1,117 @@ +//===----------------------------------------------------------------------===// +// +// 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 BigSubstring { + public struct UTF16View: Sendable { + internal var _guts: _BSubstring.UTF16View + + internal init(_guts: _BSubstring.UTF16View) { + self._guts = _guts + } + } + + public var utf16: UTF16View { + UTF16View(_guts: _guts.utf16) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigString { + public init?(_ utf8: BigSubstring.UTF16View) { + guard let guts = _BString(utf8._guts) else { return nil } + self.init(_guts: guts) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF16View { + public var base: BigString.UTF16View { + BigString.UTF16View(_guts: _guts.base) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF16View: Equatable { + public static func ==(left: Self, right: Self) -> Bool { + left._guts == right._guts + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF16View: Hashable { + public func hash(into hasher: inout Hasher) { + _guts.hash(into: &hasher) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF16View: Sequence { + public typealias Element = UInt16 + + public struct Iterator: IteratorProtocol { + internal var _guts: _BSubstring.UTF16View.Iterator + + internal init(_guts: _BSubstring.UTF16View.Iterator) { + self._guts = _guts + } + + public mutating func next() -> UInt16? { + _guts.next() + } + } + + public func makeIterator() -> Iterator { + Iterator(_guts: _guts.makeIterator()) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF16View: BidirectionalCollection { + public typealias Index = BigString.Index + public typealias SubSequence = Self + + public var startIndex: Index { Index(_guts.startIndex) } + public var endIndex: Index { Index(_guts.endIndex) } + public var count: Int { _guts.count } + public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } + public func index(before i: Index) -> Index { Index(_guts.index(after: i._value)) } + public func index(_ i: Index, offsetBy distance: Int) -> Index { + Index(_guts.index(i._value, offsetBy: distance)) + } + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } + } + public func distance(from start: Index, to end: Index) -> Int { + _guts.distance(from: start._value, to: end._value) + } + public subscript(position: Index) -> UInt16 { + _guts[position._value] + } + public subscript(bounds: Range) -> Self { + BigSubstring.UTF16View(_guts: _guts[bounds._base]) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF16View { + internal func index(roundingDown i: Index) -> Index { + Index(_guts.index(roundingDown: i._value)) + } + + internal func index(roundingUp i: Index) -> Index { + Index(_guts.index(roundingUp: i._value)) + } +} + +#endif diff --git a/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift b/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift new file mode 100644 index 00000000..b2d91bd1 --- /dev/null +++ b/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift @@ -0,0 +1,117 @@ +//===----------------------------------------------------------------------===// +// +// 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 BigSubstring { + public struct UTF8View: Sendable { + internal var _guts: _BSubstring.UTF8View + + internal init(_guts: _BSubstring.UTF8View) { + self._guts = _guts + } + } + + public var utf8: UTF8View { + UTF8View(_guts: _guts.utf8) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigString { + public init?(_ utf8: BigSubstring.UTF8View) { + guard let guts = _BString(utf8._guts) else { return nil } + self.init(_guts: guts) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF8View { + public var base: BigString.UTF8View { + BigString.UTF8View(_guts: _guts.base) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF8View: Equatable { + public static func ==(left: Self, right: Self) -> Bool { + left._guts == right._guts + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF8View: Hashable { + public func hash(into hasher: inout Hasher) { + _guts.hash(into: &hasher) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF8View: Sequence { + public typealias Element = UInt8 + + public struct Iterator: IteratorProtocol { + internal var _guts: _BSubstring.UTF8View.Iterator + + internal init(_guts: _BSubstring.UTF8View.Iterator) { + self._guts = _guts + } + + public mutating func next() -> UInt8? { + _guts.next() + } + } + + public func makeIterator() -> Iterator { + Iterator(_guts: _guts.makeIterator()) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF8View: BidirectionalCollection { + public typealias Index = BigString.Index + public typealias SubSequence = Self + + public var startIndex: Index { Index(_guts.startIndex) } + public var endIndex: Index { Index(_guts.endIndex) } + public var count: Int { _guts.count } + public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } + public func index(before i: Index) -> Index { Index(_guts.index(after: i._value)) } + public func index(_ i: Index, offsetBy distance: Int) -> Index { + Index(_guts.index(i._value, offsetBy: distance)) + } + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } + } + public func distance(from start: Index, to end: Index) -> Int { + _guts.distance(from: start._value, to: end._value) + } + public subscript(position: Index) -> UInt8 { + _guts[position._value] + } + public subscript(bounds: Range) -> Self { + BigSubstring.UTF8View(_guts: _guts[bounds._base]) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UTF8View { + internal func index(roundingDown i: Index) -> Index { + Index(_guts.index(roundingDown: i._value)) + } + + internal func index(roundingUp i: Index) -> Index { + Index(_guts.index(roundingUp: i._value)) + } +} + +#endif diff --git a/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift new file mode 100644 index 00000000..fff4dd55 --- /dev/null +++ b/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift @@ -0,0 +1,227 @@ +//===----------------------------------------------------------------------===// +// +// 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 BigSubstring { + public struct UnicodeScalarView: Sendable { + internal var _guts: _BSubstring.UnicodeScalarView + + internal init(_guts: _BSubstring.UnicodeScalarView) { + self._guts = _guts + } + } + + public var unicodeScalars: UnicodeScalarView { + UnicodeScalarView(_guts: _guts.unicodeScalars) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigString { + public init(_ unicodeScalars: BigSubstring.UnicodeScalarView) { + self.init(_guts: _BString(unicodeScalars._guts)) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView { + public var base: BigString.UnicodeScalarView { + BigString.UnicodeScalarView(_guts: _guts.base) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView: ExpressibleByStringLiteral { + public init(stringLiteral value: String) { + self.init(_guts: _BSubstring.UnicodeScalarView(value.unicodeScalars)) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView: CustomStringConvertible { + public var description: String { + _guts.description + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView: CustomDebugStringConvertible { + public var debugDescription: String { + _guts.debugDescription + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView: Equatable { + public static func ==(left: Self, right: Self) -> Bool { + left._guts == right._guts + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView: Hashable { + public func hash(into hasher: inout Hasher) { + _guts.hash(into: &hasher) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView: Sequence { + public typealias Element = UnicodeScalar + + public struct Iterator: IteratorProtocol { + internal var _guts: _BSubstring.UnicodeScalarView.Iterator + + internal init(_guts: _BSubstring.UnicodeScalarView.Iterator) { + self._guts = _guts + } + + public mutating func next() -> UnicodeScalar? { + _guts.next() + } + } + + public func makeIterator() -> Iterator { + Iterator(_guts: _guts.makeIterator()) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView: BidirectionalCollection { + public typealias Index = BigString.Index + public typealias SubSequence = Self + + public var startIndex: Index { Index(_guts.startIndex) } + public var endIndex: Index { Index(_guts.endIndex) } + public var count: Int { _guts.count } + public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } + public func index(before i: Index) -> Index { Index(_guts.index(after: i._value)) } + public func index(_ i: Index, offsetBy distance: Int) -> Index { + Index(_guts.index(i._value, offsetBy: distance)) + } + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } + } + public func distance(from start: Index, to end: Index) -> Int { + _guts.distance(from: start._value, to: end._value) + } + public subscript(position: Index) -> UnicodeScalar { + _guts[position._value] + } + public subscript(bounds: Range) -> Self { + BigSubstring.UnicodeScalarView(_guts: _guts[bounds._base]) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView { + internal func index(roundingDown i: Index) -> Index { + Index(_guts.index(roundingDown: i._value)) + } + + internal func index(roundingUp i: Index) -> Index { + Index(_guts.index(roundingUp: i._value)) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring.UnicodeScalarView: RangeReplaceableCollection { + public init() { + self.init(_guts: _BSubstring.UnicodeScalarView()) + } + + public mutating func reserveCapacity(_ n: Int) {} + + public mutating func replaceSubrange>( // Note: Sequence, not Collection + _ subrange: Range, + with newElements: __owned C + ) { + if C.self == BigString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) + _guts.replaceSubrange(subrange._base, with: newElements._guts) + } else if C.self == BigSubstring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigSubstring.UnicodeScalarView.self) + _guts.replaceSubrange(subrange._base, with: newElements._guts) + } else { + _guts.replaceSubrange(subrange._base, with: newElements) + } + } + + public init>(_ elements: S) { + if S.self == BigString.UnicodeScalarView.self { + let newElements = _identityCast(elements, to: BigString.UnicodeScalarView.self) + self.init(_guts: _BSubstring.UnicodeScalarView(newElements._guts)) + } else if S.self == BigSubstring.UnicodeScalarView.self { + let newElements = _identityCast(elements, to: BigSubstring.UnicodeScalarView.self) + let base = _BString.UnicodeScalarView(newElements._guts) + self.init(_guts: _BSubstring.UnicodeScalarView(base)) + } else { + self.init(_guts: _BSubstring.UnicodeScalarView(elements)) + } + } + + public init(repeating repeatedValue: UnicodeScalar, count: Int) { + self._guts = _BSubstring.UnicodeScalarView(repeating: repeatedValue, count: count) + } + + public mutating func append(_ newElement: UnicodeScalar) { + _guts.append(newElement) + } + + public mutating func append>( + contentsOf newElements: __owned S + ) { + if S.self == BigString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) + _guts.append(contentsOf: newElements._guts) + } else if S.self == BigSubstring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigSubstring.UnicodeScalarView.self) + _guts.append(contentsOf: newElements._guts) + } else { + _guts.append(contentsOf: newElements) + } + } + + public mutating func insert(_ newElement: UnicodeScalar, at i: Index) { + _guts.insert(newElement, at: i._value) + } + + public mutating func insert>( // Note: Sequence, not Collection + contentsOf newElements: __owned C, at i: Index + ) { + if C.self == BigString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) + _guts.insert(contentsOf: newElements._guts, at: i._value) + } else if C.self == BigSubstring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigSubstring.UnicodeScalarView.self) + _guts.insert(contentsOf: newElements._guts, at: i._value) + } else { + _guts.insert(contentsOf: newElements, at: i._value) + } + } + + @discardableResult + public mutating func remove(at i: Index) -> UnicodeScalar { + _guts.remove(at: i._value) + } + + public mutating func removeSubrange(_ bounds: Range) { + _guts.removeSubrange(bounds._base) + } + + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + _guts.removeAll(keepingCapacity: keepCapacity) + } +} + +#endif diff --git a/Sources/RopeModule/BigString/BigSubstring.swift b/Sources/RopeModule/BigString/BigSubstring.swift new file mode 100644 index 00000000..564a8539 --- /dev/null +++ b/Sources/RopeModule/BigString/BigSubstring.swift @@ -0,0 +1,228 @@ +//===----------------------------------------------------------------------===// +// +// 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, *) +public struct BigSubstring: Sendable { + internal var _guts: _BSubstring + + internal init(_guts: _BSubstring) { + self._guts = _guts + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring { + public var base: BigString { BigString(_guts: _guts._base) } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: CustomStringConvertible { + public var description: String { _guts.description } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: CustomDebugStringConvertible { + public var debugDescription: String { _guts.debugDescription } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: ExpressibleByStringLiteral { + public init(stringLiteral value: String) { + self.init(_guts: _BSubstring(stringLiteral: value)) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: LosslessStringConvertible { + // init?(_: String) is implemented by RangeReplaceableCollection.init(_:) +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: Equatable { + public static func ==(left: Self, right: Self) -> Bool { + left._guts == right._guts + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: Hashable { + public func hash(into hasher: inout Hasher) { + _guts.hash(into: &hasher) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: Comparable { + public static func < (left: Self, right: Self) -> Bool { + left._guts < right._guts + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: Sequence { + public typealias Element = Character + + public struct Iterator: IteratorProtocol { + var _guts: _BSubstring.Iterator + + init(_guts: _BSubstring.Iterator) { + self._guts = _guts + } + + public mutating func next() -> Element? { + _guts.next() + } + } + + public func makeIterator() -> Iterator { + Iterator(_guts: _guts.makeIterator()) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: BidirectionalCollection { + public typealias Index = BigString.Index + public typealias SubSequence = Self + + public var startIndex: Index { Index(_guts.startIndex) } + public var endIndex: Index { Index(_guts.endIndex) } + public var count: Int { _guts.count } + public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } + public func index(before i: Index) -> Index { Index(_guts.index(after: i._value)) } + public func index(_ i: Index, offsetBy distance: Int) -> Index { + Index(_guts.index(i._value, offsetBy: distance)) + } + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } + } + public func distance(from start: Index, to end: Index) -> Int { + _guts.distance(from: start._value, to: end._value) + } + public subscript(position: Index) -> Character { + _guts[position._value] + } + public subscript(bounds: Range) -> Self { + BigSubstring(_guts: _guts[bounds._base]) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring { + public func index(roundingDown i: Index) -> Index { + Index(_guts.index(roundingDown: i._value)) + } + public func index(roundingUp i: Index) -> Index { + Index(_guts.index(roundingUp: i._value)) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigSubstring: RangeReplaceableCollection { + public init() { + self.init(_guts: _BSubstring()) + } + + public mutating func reserveCapacity(_ n: Int) {} + + public mutating func replaceSubrange>( // Note: Sequence, not Collection + _ subrange: Range, + with newElements: __owned C + ) { + if C.self == BigString.self { + let newElements = _identityCast(newElements, to: BigString.self) + _guts.replaceSubrange(subrange._base, with: newElements._guts) + } else if C.self == BigSubstring.self { + let newElements = _identityCast(newElements, to: BigSubstring.self) + _guts.replaceSubrange(subrange._base, with: newElements._guts) + } else { + _guts.replaceSubrange(subrange._base, with: newElements) + } + } + + public init>(_ elements: S) { + if S.self == BigString.self { + let newElements = _identityCast(elements, to: BigString.self) + self.init(_guts: _BSubstring(newElements._guts)) + } else if S.self == BigSubstring.self { + let newElements = _identityCast(elements, to: BigSubstring.self) + self.init(_guts: _BSubstring(_BString(newElements._guts))) + } else { + self.init(_guts: _BSubstring(elements)) + } + } + + public init(repeating repeatedValue: Character, count: Int) { + self._guts = _BSubstring(repeating: repeatedValue, count: count) + } + + public init(repeating repeatedValue: some StringProtocol, count: Int) { + self._guts = _BSubstring(repeating: repeatedValue, count: count) + } + + public init(repeating repeatedValue: BigString, count: Int) { + self._guts = _BSubstring(repeating: repeatedValue._guts, count: count) + } + + public init(repeating repeatedValue: BigSubstring, count: Int) { + self._guts = _BSubstring(repeating: repeatedValue._guts, count: count) + } + + public mutating func append(_ newElement: Character) { + _guts.append(newElement) + } + + public mutating func append>(contentsOf newElements: __owned S) { + if S.self == BigString.self { + let newElements = _identityCast(newElements, to: BigString.self) + _guts.append(contentsOf: newElements._guts) + } else if S.self == BigSubstring.self { + let newElements = _identityCast(newElements, to: BigSubstring.self) + _guts.append(contentsOf: newElements._guts) + } else { + _guts.append(contentsOf: newElements) + } + } + + public mutating func insert(_ newElement: Character, at i: Index) { + _guts.insert(newElement, at: i._value) + } + + public mutating func insert>( // Note: Sequence, not Collection + contentsOf newElements: __owned C, at i: Index + ) { + if C.self == BigString.self { + let newElements = _identityCast(newElements, to: BigString.self) + _guts.insert(contentsOf: newElements._guts, at: i._value) + } else if C.self == BigSubstring.self { + let newElements = _identityCast(newElements, to: BigSubstring.self) + _guts.insert(contentsOf: newElements._guts, at: i._value) + } else { + _guts.insert(contentsOf: newElements, at: i._value) + } + } + + @discardableResult + public mutating func remove(at i: Index) -> Character { + _guts.remove(at: i._value) + } + + public mutating func removeSubrange(_ bounds: Range) { + _guts.removeSubrange(bounds._base) + } + + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + _guts.removeAll(keepingCapacity: keepCapacity) + } +} + +#endif diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index f3f301ba..e63554a4 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -99,17 +99,23 @@ class TestBigString: XCTestCase { let c = min(indices1.count, indices2.count) - for i in 0 ..< min(c, indices1.count - 1) { - let c1 = flat[indices1[i]] - let c2 = big[indices2[i]] - XCTAssertEqual(c1, c2, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + guard i1 < flat.endIndex, i2 < big.endIndex else { continue } + let c1 = flat[i1] + let c2 = big[i2] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } for i in 0 ..< c { - let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + let i1 = indices1[i] + let i2 = indices2[i] + let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) + let d2 = big.utf8.distance(from: big.startIndex, to: i2) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } + return (indices1, indices2) } @@ -130,17 +136,23 @@ class TestBigString: XCTestCase { let c = min(indices1.count, indices2.count) - for i in 0 ..< min(c, indices1.count - 1) { - let s1 = flat.unicodeScalars[indices1[i]] - let s2 = big.unicodeScalars[indices2[i]] - XCTAssertEqual(s1, s2, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + guard i1 < flat.endIndex, i2 < big.endIndex else { continue } + let c1 = flat.unicodeScalars[i1] + let c2 = big.unicodeScalars[i2] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1), i2: \(i2)", file: file, line: line) } for i in 0 ..< min(indices1.count, indices2.count) { - let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + let i1 = indices1[i] + let i2 = indices2[i] + let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) + let d2 = big.utf8.distance(from: big.startIndex, to: i2) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } + return (indices1, indices2) } @@ -161,17 +173,23 @@ class TestBigString: XCTestCase { let c = min(indices1.count, indices2.count) - for i in 0 ..< min(c, indices1.count - 1) { - let c1 = flat.utf8[indices1[i]] - let c2 = big.utf8[indices2[i]] - XCTAssertEqual(c1, c2, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + guard i1 < flat.endIndex, i2 < big.endIndex else { continue } + let c1 = flat.utf8[i1] + let c2 = big.utf8[i2] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } for i in 0 ..< min(indices1.count, indices2.count) { - let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + let i1 = indices1[i] + let i2 = indices2[i] + let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) + let d2 = big.utf8.distance(from: big.startIndex, to: i2) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } + return (indices1, indices2) } @@ -192,17 +210,23 @@ class TestBigString: XCTestCase { let c = min(indices1.count, indices2.count) - for i in 0 ..< min(c, indices1.count - 1) { - let c1 = flat.utf16[indices1[i]] - let c2 = big.utf16[indices2[i]] - XCTAssertEqual(c1, c2, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + guard i1 < flat.endIndex, i2 < big.endIndex else { continue } + let c1 = flat.utf16[i1] + let c2 = big.utf16[i2] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1), i2: \(i2)", file: file, line: line) } for i in 0 ..< min(indices1.count, indices2.count) { - let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]._description), i2: \(indices2[i])", file: file, line: line) + let i1 = indices1[i] + let i2 = indices2[i] + let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) + let d2 = big.utf8.distance(from: big.startIndex, to: i2) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } + return (indices1, indices2) } @@ -282,12 +306,9 @@ class TestBigString: XCTestCase { let c = min(indices1.count, indices2.count) for i in randomStride(from: 0, to: c, by: 20, seed: 0) { for j in randomStride(from: i, to: c, by: 20, seed: i) { - let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) - let i2 = indices2[i] let j2 = big.unicodeScalars.index(i2, offsetBy: j - i) - let b = String(big[i2 ..< j2]) - XCTAssertEqual(b, a) + XCTAssertEqual(j2, indices2[j]) } } } @@ -301,12 +322,9 @@ class TestBigString: XCTestCase { let c = min(indices1.count, indices2.count) for i in randomStride(from: 0, to: c, by: 20, seed: 0) { for j in randomStride(from: i, to: c, by: 20, seed: i) { - let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) - let i2 = indices2[i] let j2 = big.utf16.index(i2, offsetBy: j - i) - let b = String(big[i2 ..< j2]) - XCTAssertEqual(b, a) + XCTAssertEqual(j2, indices2[j]) } } } @@ -320,12 +338,9 @@ class TestBigString: XCTestCase { let c = min(indices1.count, indices2.count) for i in randomStride(from: 0, to: c, by: 40, seed: 0) { for j in randomStride(from: i, to: c, by: 40, seed: i) { - let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) - let i2 = indices2[i] let j2 = big.utf8.index(i2, offsetBy: j - i) - let b = String(big[i2 ..< j2]) - XCTAssertEqual(b, a) + XCTAssertEqual(j2, indices2[j]) } } } @@ -504,7 +519,7 @@ class TestBigString: XCTestCase { let k1 = big.utf8.index(big.startIndex, offsetBy: utf8Offset) let k2 = big.utf8.index(k1, offsetBy: placeholder.utf8.count) - print("\(i)/\(pieces.count): i: \(piece.i), range: \(k1 ..< k2), str: \(piece.str.debugDescription)") + //print("\(i)/\(pieces.count): i: \(piece.i), range: \(k1 ..< k2), str: \(piece.str.debugDescription)") big.replaceSubrange(k1 ..< k2, with: piece.str) @@ -530,7 +545,7 @@ class TestBigString: XCTestCase { let flat = sampleString let big = BigString(flat) - let (indices1, indices2) = checkScalarIndices(flat, big) + let (indices1, indices2) = checkCharacterIndices(flat, big) for i in randomStride(from: 0, to: indices1.count, by: 1000, seed: 0) { let a1 = indices1[i] @@ -542,7 +557,7 @@ class TestBigString: XCTestCase { let expected = String(flat[a1 ..< b1]) let actual = BigString(big[a2 ..< b2]) actual._invariantCheck() - XCTAssertEqual(String(big), flat) + XCTAssertEqual(String(actual), expected) checkUTF8Indices(expected, actual) checkUTF16Indices(expected, actual) checkScalarIndices(expected, actual) From b355480eb7fe1f1c8737f8bb4654305a3858ad65 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 13 Mar 2023 20:34:48 -0700 Subject: [PATCH 056/113] _BString: Make unicodeScalars properties mutable --- .../Views/_BString+UnicodeScalarView.swift | 15 ++++++++++++++- .../Views/_BSubstring+UnicodeScalarView.swift | 15 ++++++++++++++- .../RopeModule/BString/Views/_BSubstring.swift | 1 + Tests/RopeModuleTests/TestBString.swift | 18 ++++++++++++++++++ 4 files changed, 47 insertions(+), 2 deletions(-) diff --git a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift index 297637a3..1c09521d 100644 --- a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift @@ -24,7 +24,20 @@ extension _BString { @inline(__always) internal var unicodeScalars: UnicodeScalarView { - UnicodeScalarView(_base: self) + get { + UnicodeScalarView(_base: self) + } + set { + self = newValue._base + } + _modify { + var view = UnicodeScalarView(_base: self) + self = .init() + defer { + self = view._base + } + yield &view + } } internal init(_ view: _BString.UnicodeScalarView) { diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift index 355935d7..7a5cef78 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -35,7 +35,20 @@ extension _BSubstring { } internal var unicodeScalars: UnicodeScalarView { - UnicodeScalarView(_substring: self) + get { + UnicodeScalarView(_substring: self) + } + set { + self = Self(newValue._base, in: newValue._bounds) + } + _modify { + var view = UnicodeScalarView(_unchecked: _base, in: _bounds) + self = Self() + defer { + self = Self(view._base, in: view._bounds) + } + yield &view + } } } diff --git a/Sources/RopeModule/BString/Views/_BSubstring.swift b/Sources/RopeModule/BString/Views/_BSubstring.swift index 590438ba..194c41a6 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring.swift @@ -356,6 +356,7 @@ extension _BSubstring: RangeReplaceableCollection { _mutateBasePreservingBounds(in: bounds) { $0.removeSubrange(bounds) } + assert(_bounds.isEmpty) } } diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 420e95dc..024ba1dc 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -689,6 +689,24 @@ class TestBString: XCTestCase { XCTAssertEqual(s3.base, "Foo🇭🇺🇸🇨🇦🇺🇸🇨\u{1f1e6}bar") } + func test_unicodeScalars_mutations() { + let b1: _BString = "Foo👩👧bar" // WOMAN, GIRL + var s1 = b1.prefix(4) + XCTAssertEqual(s1, "Foo👩") + + // Append a ZWJ at the end of the substring via its Unicode scalars view. + func mutate(_ value: inout T, by body: (inout T) -> Void) { + body(&value) + } + mutate(&s1.unicodeScalars) { view in + view.append("\u{200d}") // ZWJ + XCTAssertEqual(view, "Foo👩\u{200d}") + } + + XCTAssertEqual(s1, "Foo") + XCTAssertEqual(s1.base, "Foo👩‍👧bar") + } + func test_ExpressibleByStringLiteral_and_CustomStringConvertible() { let a: _BString = "foobar" XCTAssertEqual(a.description, "foobar") From 64a8098bf9a9da15986368358ef6a87e37f95ca5 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 13 Mar 2023 20:35:42 -0700 Subject: [PATCH 057/113] =?UTF-8?q?=5FBSubstring.UnicodeScalarView:=20Fix?= =?UTF-8?q?=20range-replacing=20mutations=20that=20don=E2=80=99t=20take=20?= =?UTF-8?q?indices?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/_BSubstring+UnicodeScalarView.swift | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift index 7a5cef78..6b28d6f8 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -257,14 +257,16 @@ extension _BSubstring.UnicodeScalarView: RangeReplaceableCollection { } internal mutating func append(_ newElement: UnicodeScalar) { - _mutateBasePreservingBounds(in: endIndex ..< endIndex) { - $0.append(newElement) + let i = endIndex + _mutateBasePreservingBounds(in: i ..< i) { + $0.insert(newElement, at: i) } } internal mutating func append>(contentsOf newElements: __owned S) { - _mutateBasePreservingBounds(in: endIndex ..< endIndex) { - $0.append(contentsOf: newElements) + let i = endIndex + _mutateBasePreservingBounds(in: i ..< i) { + $0.insert(contentsOf: newElements, at: i) } } @@ -285,7 +287,8 @@ extension _BSubstring.UnicodeScalarView: RangeReplaceableCollection { @discardableResult internal mutating func remove(at i: Index) -> UnicodeScalar { - _mutateBasePreservingBounds(in: i ..< i) { + let j = self.index(after: i) + return _mutateBasePreservingBounds(in: i ..< j) { $0.remove(at: i) } } From b50fb5aab5fe1e2ddec021bafdfed377ad1c57df Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 14 Mar 2023 16:14:44 -0700 Subject: [PATCH 058/113] =?UTF-8?q?=5FBString.resolve:=20Don=E2=80=99t=20c?= =?UTF-8?q?rash=20when=20resolving=20indices=20in=20the=20empty=20string?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/RopeModule/BString/Basics/_BString+Index.swift | 6 ++++-- Tests/RopeModuleTests/TestBString.swift | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift index 1c9add4a..361e88db 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -212,7 +212,7 @@ extension _BString { func resolve(_ i: Index, preferEnd: Bool) -> Index { if var ri = i._rope, rope.isValid(ri) { if preferEnd { - guard i._utf8ChunkOffset == 0, i._utf8Offset > 0 else { return i } + guard i._utf8Offset > 0, i._utf8ChunkOffset == 0 else { return i } rope.formIndex(before: &ri) let length = rope[ri].utf8Count let ci = String.Index(_utf8Offset: length) @@ -220,7 +220,9 @@ extension _BString { j._flags = i._flags return j } - guard i._utf8ChunkOffset == rope[ri].utf8Count else { return i } + guard i._utf8Offset < utf8Count, i._utf8ChunkOffset == rope[ri].utf8Count else { + return i + } rope.formIndex(after: &ri) let ci = String.Index(_utf8Offset: 0) var j = Index(baseUTF8Offset: i._utf8Offset, rope: ri, chunk: ci) diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 024ba1dc..63c2827f 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -48,6 +48,9 @@ class TestBString: XCTestCase { XCTAssertTrue(s.isEmpty) XCTAssertEqual(s.startIndex, s.endIndex) XCTAssertEqual(s.startIndex._utf8Offset, 0) + + XCTAssertEqual(String(_from: s), "") + XCTAssertEqual(String(_from: s[...]), "") } func test_string_conversion() { From da78365bef8e88e6952827ddc48530cacd16a60e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 16 Mar 2023 11:08:31 -0700 Subject: [PATCH 059/113] _BString: Add isIdentical(to:) to all string views --- Sources/RopeModule/BString/Views/_BString+UTF16View.swift | 4 ++++ Sources/RopeModule/BString/Views/_BString+UTF8View.swift | 4 ++++ .../BString/Views/_BString+UnicodeScalarView.swift | 4 ++++ Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift | 5 +++++ Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift | 5 +++++ .../BString/Views/_BSubstring+UnicodeScalarView.swift | 5 +++++ 6 files changed, 27 insertions(+) diff --git a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift index faf34b2d..5989af7f 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift @@ -37,6 +37,10 @@ extension _BString.UTF16View: Equatable { internal static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, to: right._base) } + + internal func isIdentical(to other: Self) -> Bool { + self._base.isIdentical(to: other._base) + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift index ccdc4646..53dd82eb 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift @@ -37,6 +37,10 @@ extension _BString.UTF8View: Equatable { internal static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, to: right._base) } + + internal func isIdentical(to other: Self) -> Bool { + self._base.isIdentical(to: other._base) + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift index 1c09521d..efbdf111 100644 --- a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift @@ -71,6 +71,10 @@ extension _BString.UnicodeScalarView: Equatable { internal static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, to: right._base) } + + internal func isIdentical(to other: Self) -> Bool { + self._base.isIdentical(to: other._base) + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift index e16b68e3..4e59bfbc 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift @@ -85,6 +85,11 @@ extension _BSubstring.UTF16View: Equatable { return _BString.utf8IsEqual(left._base, in: i1 ..< j1, to: right._base, in: i2 ..< j2) } + + internal func isIdentical(to other: Self) -> Bool { + guard self._base.isIdentical(to: other._base) else { return false } + return self._bounds == other._bounds + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift index f8c83458..048e5b90 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift @@ -62,6 +62,11 @@ extension _BSubstring.UTF8View: Equatable { internal static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) } + + internal func isIdentical(to other: Self) -> Bool { + guard self._base.isIdentical(to: other._base) else { return false } + return self._bounds == other._bounds + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift index 6b28d6f8..cb5e578c 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -90,6 +90,11 @@ extension _BSubstring.UnicodeScalarView: Equatable { internal static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) } + + internal func isIdentical(to other: Self) -> Bool { + guard self._base.isIdentical(to: other._base) else { return false } + return self._bounds == other._bounds + } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) From 4849d546758a25b9d4bd4a812009212ca0db9d7d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 16 Mar 2023 11:09:46 -0700 Subject: [PATCH 060/113] Add a compile-time conditional for enabling randomized testing, enabled by default --- Package.swift | 2 ++ Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/Package.swift b/Package.swift index c39935ed..215a3a88 100644 --- a/Package.swift +++ b/Package.swift @@ -42,6 +42,8 @@ var settings: [SwiftSetting] = [ // code. // .define("COLLECTIONS_DETERMINISTIC_HASHING"), + // Enables randomized testing of some data structure implementations. + .define("COLLECTIONS_RANDOMIZED_TESTING") ] let package = Package( diff --git a/Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift b/Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift index 37834fad..4d415f4e 100644 --- a/Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift +++ b/Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift @@ -10,7 +10,11 @@ //===----------------------------------------------------------------------===// var globalSeed: Int { + #if COLLECTIONS_RANDOMIZED_TESTING 42.hashValue + #else + 0 + #endif } public struct RepeatableRandomNumberGenerator: RandomNumberGenerator { From ddcd1788aa6d1d973ade0a2d0df9861254c7d40f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 16 Mar 2023 11:24:55 -0700 Subject: [PATCH 061/113] =?UTF-8?q?Unconditionally=20enable=20use=20of=20?= =?UTF-8?q?=5FCharacterRecognizer=E2=80=99s=20Equatable=20conformance=20if?= =?UTF-8?q?=20we=20aren=E2=80=99t=20building=20a=20package?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Utilities/_CharacterRecognizer.swift | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift index 7a96716e..9aa58bb6 100644 --- a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -17,12 +17,17 @@ internal typealias _CharacterRecognizer = Unicode._CharacterRecognizer @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _CharacterRecognizer { internal func _isKnownEqual(to other: Self) -> Bool { -#if swift(>=5.9) - if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { // SwiftStdlib 5.9 - return self == other - } -#endif +#if SWIFT_PACKAGE + // FIXME: Enable when Swift 5.9 ships. +// #if swift(>=5.9) +// if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { // SwiftStdlib 5.9 +// return self == other +// } +// #endif return false +#else // !SWIFT_PACKAGE + return self == other +#endif } } From 535b8b8562da59b478fb02c9c5453f6fc5fc2326 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 14:25:28 -0700 Subject: [PATCH 062/113] Fix compatbility with Swift toolchains below 5.8 --- Sources/RopeModule/Rope/Basics/_Rope+Node.swift | 4 ++++ Sources/RopeModule/Utilities/String Utilities.swift | 2 ++ .../UnsafeMutableBufferPointer+SE-0370.swift | 8 +++++++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Node.swift b/Sources/RopeModule/Rope/Basics/_Rope+Node.swift index 1a3d56cc..f55f3480 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Node.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+Node.swift @@ -9,6 +9,10 @@ // //===----------------------------------------------------------------------===// +#if swift(<5.8) +import _CollectionsUtilities // for 5.8 polyfills +#endif + extension _Rope { struct Node: _RopeItem { typealias Element = _Rope.Element diff --git a/Sources/RopeModule/Utilities/String Utilities.swift b/Sources/RopeModule/Utilities/String Utilities.swift index a27ab140..57e6b924 100644 --- a/Sources/RopeModule/Utilities/String Utilities.swift +++ b/Sources/RopeModule/Utilities/String Utilities.swift @@ -60,6 +60,7 @@ extension String { } } +#if swift(>=5.8) // _CharacterRecognizer @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String { @discardableResult @@ -123,3 +124,4 @@ extension String { return result } } +#endif diff --git a/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift b/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift index db28325b..afd5bc16 100644 --- a/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift +++ b/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022-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 @@ -11,6 +11,7 @@ // Note: These are adapted from SE-0370 in the Swift 5.8 Standard Library. +#if swift(<5.8) extension UnsafeMutableBufferPointer { /// Deinitializes every instance in this buffer. /// @@ -31,7 +32,9 @@ extension UnsafeMutableBufferPointer { count: count * MemoryLayout.stride) } } +#endif +#if swift(<5.8) extension UnsafeMutableBufferPointer { /// Initializes the buffer's memory with /// every element of the source. @@ -213,7 +216,9 @@ extension UnsafeMutableBufferPointer { p.deinitialize(count: 1) } } +#endif +#if swift(<5.8) extension Slice { /// Initializes the buffer slice's memory with with /// every element of the source. @@ -366,6 +371,7 @@ extension Slice { base.baseAddress.unsafelyUnwrapped.advanced(by: index).initialize(to: value) } } +#endif #if swift(<5.8) extension UnsafeMutableBufferPointer { From 975a8902ffaf3aff0c2a298ba7f6514b134cc7d1 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 15:26:11 -0700 Subject: [PATCH 063/113] =?UTF-8?q?Disable=20modules=20that=20haven?= =?UTF-8?q?=E2=80=99t=20gone=20through=20API=20review=20yet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit These are disabled on the package manifest level. To locally reenable them, Package.swift needs to be manually edited to enable COLLECTIONS_ENABLE_UNSTABLE_MODULES. To mark a module as ready for production use, it has to be defined using `registerLibrary` instead of `registerUnstableLibrary`. This can only be done once the module has gone through API review. (Or if it becomes an underscored — i.e., explicitly unstable — module.) --- Package.swift | 258 ++++++++++++++------------ Sources/Collections/Collections.swift | 8 +- 2 files changed, 150 insertions(+), 116 deletions(-) diff --git a/Package.swift b/Package.swift index 215a3a88..6c09e14c 100644 --- a/Package.swift +++ b/Package.swift @@ -17,7 +17,7 @@ import PackageDescription // from the package manager command line: // // swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS -var settings: [SwiftSetting] = [ +var defines: [String] = [ // Enables internal consistency checks at the end of initializers and // mutating operations. This can have very significant overhead, so enabling @@ -26,7 +26,7 @@ var settings: [SwiftSetting] = [ // This is mostly useful while debugging an issue with the implementation of // the hash table itself. This setting should never be enabled in production // code. -// .define("COLLECTIONS_INTERNAL_CHECKS"), +// "COLLECTIONS_INTERNAL_CHECKS", // Hashing collections provided by this package usually seed their hash // function with the address of the memory location of their storage, @@ -40,122 +40,152 @@ var settings: [SwiftSetting] = [ // This is mostly useful while debugging an issue with the implementation of // the hash table itself. This setting should never be enabled in production // code. -// .define("COLLECTIONS_DETERMINISTIC_HASHING"), +// "COLLECTIONS_DETERMINISTIC_HASHING", // Enables randomized testing of some data structure implementations. - .define("COLLECTIONS_RANDOMIZED_TESTING") + "COLLECTIONS_RANDOMIZED_TESTING", + + // Enable modules that aren't source stable yet, and aren't ready for general use. +// "COLLECTIONS_ENABLE_UNSTABLE_MODULES", ] +var _modules: [String] = [] +var _products: [Product] = [] +var _targets: [Target] = [] +var _settings: [SwiftSetting] = defines.map { .define($0) } + +func registerTargets(_ targets: [Target]) { + _targets.append(contentsOf: targets) +} +func registerTargets(_ targets: Target...) { registerTargets(targets) } + +func registerLibrary(_ module: String, _ targets: [Target]) { + _modules.append(module) + _products.append(.library(name: module, targets: [module])) + registerTargets(targets) +} +func registerLibrary(_ module: String, _ targets: Target...) { + registerLibrary(module, targets) +} + +func registerUnstableLibrary(_ module: String, _ targets: Target...) { + if defines.contains("COLLECTIONS_ENABLE_UNSTABLE_MODULES") { + registerLibrary(module, targets) + } +} + +registerTargets( + .target( + name: "_CollectionsTestSupport", + dependencies: ["_CollectionsUtilities"], + swiftSettings: _settings, + linkerSettings: [ + .linkedFramework( + "XCTest", + .when(platforms: [.macOS, .iOS, .watchOS, .tvOS])), + ] + ), + .testTarget( + name: "CollectionsTestSupportTests", + dependencies: ["_CollectionsTestSupport"], + swiftSettings: _settings), + + .target( + name: "_CollectionsUtilities", + exclude: ["CMakeLists.txt"], + swiftSettings: _settings) +) + +registerUnstableLibrary( + "BitCollections", + .target( + name: "BitCollections", + dependencies: ["_CollectionsUtilities"], + exclude: ["CMakeLists.txt"], + swiftSettings: _settings), + .testTarget( + name: "BitCollectionsTests", + dependencies: [ + "BitCollections", "_CollectionsTestSupport", "OrderedCollections" + ], + swiftSettings: _settings) +) + +registerLibrary( + "DequeModule", + .target( + name: "DequeModule", + dependencies: ["_CollectionsUtilities"], + exclude: ["CMakeLists.txt"], + swiftSettings: _settings), + .testTarget( + name: "DequeTests", + dependencies: ["DequeModule", "_CollectionsTestSupport"], + swiftSettings: _settings) +) + +registerLibrary( + "HashTreeCollections", + .target( + name: "HashTreeCollections", + dependencies: ["_CollectionsUtilities"], + exclude: ["CMakeLists.txt"], + swiftSettings: _settings), + .testTarget( + name: "HashTreeCollectionsTests", + dependencies: ["HashTreeCollections", "_CollectionsTestSupport"], + swiftSettings: _settings) +) + +registerUnstableLibrary( + "HeapModule", + .target( + name: "HeapModule", + dependencies: ["_CollectionsUtilities"], + exclude: ["CMakeLists.txt"], + swiftSettings: _settings), + .testTarget( + name: "HeapTests", + dependencies: ["HeapModule", "_CollectionsTestSupport"], + swiftSettings: _settings) +) + +registerLibrary( + "OrderedCollections", + .target( + name: "OrderedCollections", + dependencies: ["_CollectionsUtilities"], + exclude: ["CMakeLists.txt"], + swiftSettings: _settings), + .testTarget( + name: "OrderedCollectionsTests", + dependencies: ["OrderedCollections", "_CollectionsTestSupport"], + swiftSettings: _settings) +) + +registerUnstableLibrary( + "RopeModule", + .target( + name: "RopeModule", + dependencies: ["_CollectionsUtilities"], + swiftSettings: _settings), + .testTarget( + name: "RopeModuleTests", + dependencies: ["RopeModule", "_CollectionsTestSupport"], + swiftSettings: _settings) +) + +registerLibrary( + "Collections", + .target( + name: "Collections", + dependencies: _modules.map { .target(name: $0) }, + exclude: ["CMakeLists.txt"], + swiftSettings: _settings) +) + let package = Package( name: "swift-collections", - products: [ - .library(name: "Collections", targets: ["Collections"]), - .library(name: "BitCollections", targets: ["BitCollections"]), - .library(name: "DequeModule", targets: ["DequeModule"]), - .library(name: "HeapModule", targets: ["HeapModule"]), - .library(name: "OrderedCollections", targets: ["OrderedCollections"]), - .library(name: "HashTreeCollections", targets: ["HashTreeCollections"]), - .library(name: "RopeModule", targets: ["RopeModule"]), - ], - targets: [ - .target( - name: "Collections", - dependencies: [ - "BitCollections", - "DequeModule", - "HeapModule", - "OrderedCollections", - "HashTreeCollections", - ], - exclude: ["CMakeLists.txt"], - swiftSettings: settings), - - // Testing support module - .target( - name: "_CollectionsTestSupport", - dependencies: ["_CollectionsUtilities"], - swiftSettings: settings, - linkerSettings: [ - .linkedFramework( - "XCTest", - .when(platforms: [.macOS, .iOS, .watchOS, .tvOS])), - ] - ), - .testTarget( - name: "CollectionsTestSupportTests", - dependencies: ["_CollectionsTestSupport"], - swiftSettings: settings), - - .target( - name: "_CollectionsUtilities", - exclude: ["CMakeLists.txt"], - swiftSettings: settings), - - // BitSet, BitArray - .target( - name: "BitCollections", - dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: settings), - .testTarget( - name: "BitCollectionsTests", - dependencies: [ - "BitCollections", "_CollectionsTestSupport", "OrderedCollections" - ], - swiftSettings: settings), - - // Deque - .target( - name: "DequeModule", - dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: settings), - .testTarget( - name: "DequeTests", - dependencies: ["DequeModule", "_CollectionsTestSupport"], - swiftSettings: settings), - - // Heap - .target( - name: "HeapModule", - dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: settings), - .testTarget( - name: "HeapTests", - dependencies: ["HeapModule", "_CollectionsTestSupport"], - swiftSettings: settings), - - // OrderedSet, OrderedDictionary - .target( - name: "OrderedCollections", - dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: settings), - .testTarget( - name: "OrderedCollectionsTests", - dependencies: ["OrderedCollections", "_CollectionsTestSupport"], - swiftSettings: settings), - - // TreeSet, TreeDictionary - .target( - name: "HashTreeCollections", - dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: settings), - .testTarget( - name: "HashTreeCollectionsTests", - dependencies: ["HashTreeCollections", "_CollectionsTestSupport"], - swiftSettings: settings), - - // BigString - .target( - name: "RopeModule", - dependencies: ["_CollectionsUtilities"], - swiftSettings: settings), - .testTarget( - name: "RopeModuleTests", - dependencies: ["RopeModule", "_CollectionsTestSupport"], - swiftSettings: settings), - ] + products: _products, + targets: _targets ) diff --git a/Sources/Collections/Collections.swift b/Sources/Collections/Collections.swift index 99ffc85c..de77db7d 100644 --- a/Sources/Collections/Collections.swift +++ b/Sources/Collections/Collections.swift @@ -9,8 +9,12 @@ // //===----------------------------------------------------------------------===// -@_exported import BitCollections @_exported import DequeModule -@_exported import HeapModule @_exported import OrderedCollections @_exported import HashTreeCollections + +#if COLLECTIONS_ENABLE_UNSTABLE_MODULES +@_exported import BitCollections +@_exported import HeapModule +@_exported import RopeModule +#endif From 79f1e16afd2c5e0b727eec161044107aff5b19d7 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 16:38:38 -0700 Subject: [PATCH 064/113] =?UTF-8?q?Don=E2=80=99t=20skip=20building/testing?= =?UTF-8?q?=20BitCollections=20and=20HeapModule?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Package.swift | 6 +++--- Sources/Collections/Collections.swift | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Package.swift b/Package.swift index 6c09e14c..d3cfbf7c 100644 --- a/Package.swift +++ b/Package.swift @@ -3,7 +3,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 @@ -96,7 +96,7 @@ registerTargets( swiftSettings: _settings) ) -registerUnstableLibrary( +registerLibrary( "BitCollections", .target( name: "BitCollections", @@ -137,7 +137,7 @@ registerLibrary( swiftSettings: _settings) ) -registerUnstableLibrary( +registerLibrary( "HeapModule", .target( name: "HeapModule", diff --git a/Sources/Collections/Collections.swift b/Sources/Collections/Collections.swift index de77db7d..2b94ab98 100644 --- a/Sources/Collections/Collections.swift +++ b/Sources/Collections/Collections.swift @@ -2,19 +2,19 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021-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 // //===----------------------------------------------------------------------===// +@_exported import BitCollections @_exported import DequeModule -@_exported import OrderedCollections @_exported import HashTreeCollections +@_exported import HeapModule +@_exported import OrderedCollections #if COLLECTIONS_ENABLE_UNSTABLE_MODULES -@_exported import BitCollections -@_exported import HeapModule @_exported import RopeModule #endif From 09577a31eef03c39a5b8ca2bc0bf9461985c8697 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 16:40:08 -0700 Subject: [PATCH 065/113] =?UTF-8?q?RopeModule=E2=86=92=5FRopeModule.=20Sto?= =?UTF-8?q?p=20reexporting=20it=20from=20Collections.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This module is not source stable; mark it as such by prepending the module name with an underscore. --- Package.swift | 9 +++++---- Sources/Collections/Collections.swift | 4 +--- Tests/RopeModuleTests/TestBString.swift | 2 +- Tests/RopeModuleTests/TestBString2.swift | 2 +- Tests/RopeModuleTests/TestBigString.swift | 2 +- Tests/RopeModuleTests/TestRope.swift | 2 +- 6 files changed, 10 insertions(+), 11 deletions(-) diff --git a/Package.swift b/Package.swift index d3cfbf7c..13d3f242 100644 --- a/Package.swift +++ b/Package.swift @@ -163,15 +163,16 @@ registerLibrary( swiftSettings: _settings) ) -registerUnstableLibrary( - "RopeModule", +registerLibrary( + "_RopeModule", .target( - name: "RopeModule", + name: "_RopeModule", dependencies: ["_CollectionsUtilities"], + path: "Sources/RopeModule", swiftSettings: _settings), .testTarget( name: "RopeModuleTests", - dependencies: ["RopeModule", "_CollectionsTestSupport"], + dependencies: ["_RopeModule", "_CollectionsTestSupport"], swiftSettings: _settings) ) diff --git a/Sources/Collections/Collections.swift b/Sources/Collections/Collections.swift index 2b94ab98..b500a766 100644 --- a/Sources/Collections/Collections.swift +++ b/Sources/Collections/Collections.swift @@ -15,6 +15,4 @@ @_exported import HeapModule @_exported import OrderedCollections -#if COLLECTIONS_ENABLE_UNSTABLE_MODULES -@_exported import RopeModule -#endif +//@_exported import _RopeModule diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 63c2827f..408e53c8 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// #if swift(>=5.8) && DEBUG -@testable import RopeModule +@testable import _RopeModule import XCTest @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Tests/RopeModuleTests/TestBString2.swift b/Tests/RopeModuleTests/TestBString2.swift index 81c2736f..3ea05308 100644 --- a/Tests/RopeModuleTests/TestBString2.swift +++ b/Tests/RopeModuleTests/TestBString2.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) && DEBUG import _CollectionsTestSupport import XCTest -@testable import RopeModule +@testable import _RopeModule @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) class TestBString2: CollectionTestCase { diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index e63554a4..8549c3e7 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// #if swift(>=5.8) -import RopeModule +import _RopeModule import XCTest @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index 326f423c..11158ed9 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// #if DEBUG -@testable import RopeModule +@testable import _RopeModule import XCTest struct Chunk: _RopeElement, Equatable, CustomStringConvertible { From 73de433eef93d860176819a5b29ffea1fa565530 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 16:40:37 -0700 Subject: [PATCH 066/113] Restore workaround for SR-14663 --- .../Array+WithContiguousStorage Compatibility.swift | 2 +- .../Compatibility/UnsafeMutableBufferPointer+SE-0370.swift | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift b/Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift index 2cb6cddb..c6d565ca 100644 --- a/Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift +++ b/Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift @@ -14,7 +14,7 @@ extension Array { /// in the stdlib we're currently running on. /// /// See https://bugs.swift.org/browse/SR-14663. - @inlinable + @inlinable @inline(__always) internal static func _isWCSIABroken() -> Bool { #if _runtime(_ObjC) guard _isBridgedVerbatimToObjectiveC(Element.self) else { diff --git a/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift b/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift index afd5bc16..70766b4f 100644 --- a/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift +++ b/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift @@ -34,7 +34,7 @@ extension UnsafeMutableBufferPointer { } #endif -#if swift(<5.8) +// Note: this is left unconditionally enabled because we need the SR14663 workaround. :-( extension UnsafeMutableBufferPointer { /// Initializes the buffer's memory with /// every element of the source. @@ -89,7 +89,10 @@ extension UnsafeMutableBufferPointer { ) return startIndex.advanced(by: copied) } +} +#if swift(<5.8) +extension UnsafeMutableBufferPointer { /// Moves every element of an initialized source buffer into the /// uninitialized memory referenced by this buffer, leaving the source memory /// uninitialized and this buffer's memory initialized. From b022b7fee5f0e383d9f80c70b253f58196142963 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 18:31:14 -0700 Subject: [PATCH 067/113] Make _BString and _Rope public --- .../BString/Basics/_BString+Contents.swift | 16 +- .../BString/Basics/_BString+Debugging.swift | 2 +- .../BString/Basics/_BString+Index.swift | 31 +- .../BString/Basics/_BString+Invariants.swift | 2 +- .../BString/Basics/_BString+Iterators.swift | 362 +----------------- .../RopeModule/BString/Basics/_BString.swift | 4 +- .../_BString+BidirectionalCollection.swift | 28 +- .../Conformances/_BString+Comparable.swift | 2 +- ...BString+CustomDebugStringConvertible.swift | 2 +- .../_BString+CustomStringConvertible.swift | 4 +- .../Conformances/_BString+Equatable.swift | 12 +- .../_BString+ExpressibleByStringLiteral.swift | 2 +- .../Conformances/_BString+Hashing.swift | 4 +- .../_BString+RangeReplaceableCollection.swift | 62 +-- .../Conformances/_BString+Sequence.swift | 223 ++++++++++- .../BString/Operations/Range+_BString.swift | 2 +- .../Operations/_BString+Initializers.swift | 20 +- .../BString/Operations/_BString+Insert.swift | 2 +- .../Operations/_BString+RemoveSubrange.swift | 4 +- .../Operations/_BString+ReplaceSubrange.swift | 4 +- .../BString/Operations/_BString+Split.swift | 2 +- .../BString/Views/_BString+UTF16View.swift | 81 ++-- .../BString/Views/_BString+UTF8View.swift | 117 ++++-- .../Views/_BString+UnicodeScalarView.swift | 151 +++++--- .../BString/Views/_BSubstring+UTF16View.swift | 58 +-- .../BString/Views/_BSubstring+UTF8View.swift | 58 +-- .../Views/_BSubstring+UnicodeScalarView.swift | 94 ++--- .../BString/Views/_BSubstring.swift | 94 ++--- .../BigString/BigString+CharacterView.swift | 17 +- .../BigString/BigString+UTF16View.swift | 17 +- .../BigString/BigString+UTF8View.swift | 17 +- .../BigString+UnicodeScalarView.swift | 19 +- Sources/RopeModule/BigString/BigString.swift | 14 +- .../BigString/BigSubstring+UTF16View.swift | 15 +- .../BigString/BigSubstring+UTF8View.swift | 15 +- .../BigSubstring+UnicodeScalarView.swift | 15 +- .../RopeModule/BigString/BigSubstring.swift | 15 +- .../Rope/Basics/_Rope+Builder.swift | 19 +- .../Rope/Basics/_Rope+Debugging.swift | 2 +- .../Rope/Basics/_Rope+Invariants.swift | 2 +- .../Rope/Basics/_Rope+Storage.swift | 2 +- .../Rope/Basics/_Rope+UnmanagedLeaf.swift | 2 +- .../Rope/Basics/_Rope+UnsafeHandle.swift | 6 +- Sources/RopeModule/Rope/Basics/_Rope.swift | 6 +- .../RopeModule/Rope/Basics/_RopeElement.swift | 5 +- .../RopeModule/Rope/Basics/_RopeMetric.swift | 4 +- .../RopeModule/Rope/Basics/_RopePath.swift | 2 +- .../RopeModule/Rope/Basics/_RopeSummary.swift | 12 +- .../RopeModule/Rope/Basics/_RopeVersion.swift | 2 +- .../Rope/Conformances/_Rope+Collection.swift | 48 +-- .../Rope/Conformances/_Rope+Index.swift | 10 +- .../Rope/Conformances/_Rope+Sequence.swift | 8 +- .../Rope/Operations/_Rope+Append.swift | 2 +- .../Rope/Operations/_Rope+Extract.swift | 6 +- .../Rope/Operations/_Rope+Find.swift | 2 +- .../Rope/Operations/_Rope+ForEachWhile.swift | 4 +- .../Rope/Operations/_Rope+Insert.swift | 6 +- .../Rope/Operations/_Rope+Join.swift | 6 +- .../Operations/_Rope+MutatingForEach.swift | 4 +- .../Rope/Operations/_Rope+Remove.swift | 2 +- .../Operations/_Rope+RemoveSubrange.swift | 4 +- Tests/RopeModuleTests/TestBString.swift | 59 +-- 62 files changed, 874 insertions(+), 938 deletions(-) diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 2f0ec453..c93398c7 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -16,7 +16,7 @@ extension _BString { /// The estimated maximum number of UTF-8 code units that `_BString` is guaranteed to be able /// to hold without encountering an overflow in its operations. This corresponds to the capacity /// of the deepest tree where every node is the minimum possible size. - static var minimumCapacity: Int { + public static var minimumCapacity: Int { let c = Rope.minimumCapacity let (r, overflow) = Chunk.minUTF8Count.multipliedReportingOverflow(by: c) guard !overflow else { return Int.max } @@ -25,7 +25,7 @@ extension _BString { /// The maximum number of UTF-8 code units that `_BString` may be able to store in the best /// possible case, when every node in the underlying tree is fully filled with data. - static var maximumCapacity: Int { + public static var maximumCapacity: Int { let c = Rope.maximumCapacity let (r, overflow) = Chunk.maxUTF8Count.multipliedReportingOverflow(by: c) guard !overflow else { return Int.max } @@ -85,7 +85,7 @@ extension _BString { } func utf8Distance(from start: Index, to end: Index) -> Int { - end._utf8Offset - start._utf8Offset + end.utf8Offset - start.utf8Offset } } @@ -157,7 +157,7 @@ extension _BString { if r.forward { assert(distance >= 0) assert(ci == chunk.string.endIndex) - d += metric.nonnegativeSize(of: chunk.summary) + d += metric._nonnegativeSize(of: chunk.summary) let start = ri rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false) if ri == rope.endIndex { @@ -269,7 +269,7 @@ extension _BString { rope: rope.index(after: ri), chunk: String.Index(_utf8Offset: 0)) } - return Index(_utf8Offset: i._utf8Offset + 1, rope: ri, chunkOffset: ci._utf8Offset) + return Index(_utf8Offset: i.utf8Offset + 1, rope: ri, chunkOffset: ci._utf8Offset) } } @@ -294,7 +294,7 @@ extension _BString { let ci = i._chunkIndex if ci._utf8Offset > 0 { return Index( - _utf8Offset: i._utf8Offset &- 1, + _utf8Offset: i.utf8Offset &- 1, rope: ri, chunkOffset: ci._utf8Offset &- 1) } @@ -310,7 +310,7 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { func characterIndex(roundingDown i: Index) -> Index { - let offset = i._utf8Offset + let offset = i.utf8Offset precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") guard offset > 0 else { return resolve(i, preferEnd: false)._knownCharacterAligned() } guard offset < utf8Count else { return resolve(i, preferEnd: true)._knownCharacterAligned() } @@ -416,7 +416,7 @@ extension _BString { extension _BString { func _character(at start: Index) -> (character: Character, end: Index) { let start = characterIndex(roundingDown: start) - precondition(start._utf8Offset < utf8Count, "Index out of bounds") + precondition(start.utf8Offset < utf8Count, "Index out of bounds") var ri = start._rope! var ci = start._chunkIndex diff --git a/Sources/RopeModule/BString/Basics/_BString+Debugging.swift b/Sources/RopeModule/BString/Basics/_BString+Debugging.swift index b53bd0af..dd804a1c 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Debugging.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Debugging.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - func dump(heightLimit: Int = .max) { + public func dump(heightLimit: Int = .max) { rope.dump(heightLimit: heightLimit) } } diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift index 361e88db..ef73ce38 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal struct Index: Sendable { + public struct Index: Sendable { typealias Rope = _BString.Rope // ┌───────────────────────────────┬───┬───────────┬────────────────────┐ @@ -61,7 +61,12 @@ extension _BString.Index { @inline(__always) internal static var _scalarAlignmentBit: UInt64 { 0x100 } + @available(*, deprecated, renamed: "utf8Offset") internal var _utf8Offset: Int { + utf8Offset + } + + public var utf8Offset: Int { Int(truncatingIfNeeded: _rawBits &>> 11) } @@ -78,7 +83,7 @@ extension _BString.Index { /// The base offset of the addressed chunk. Only valid if `_rope` is not nil. internal var _utf8BaseOffset: Int { - _utf8Offset - _utf8ChunkOffset + utf8Offset - _utf8ChunkOffset } @inline(__always) @@ -180,30 +185,30 @@ extension _BString.Index { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index: Equatable { - static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: Self) -> Bool { left._orderingValue == right._orderingValue } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index: Comparable { - static func <(left: Self, right: Self) -> Bool { + public static func <(left: Self, right: Self) -> Bool { left._orderingValue < right._orderingValue } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index: Hashable { - func hash(into hasher: inout Hasher) { + public func hash(into hasher: inout Hasher) { hasher.combine(_orderingValue) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.Index: CustomStringConvertible { - internal var description: String { + public var description: String { let utf16Offset = _isUTF16TrailingSurrogate ? "+1" : "" - return "\(_utf8Offset)[utf8]\(utf16Offset)" + return "\(utf8Offset)[utf8]\(utf16Offset)" } } @@ -212,29 +217,29 @@ extension _BString { func resolve(_ i: Index, preferEnd: Bool) -> Index { if var ri = i._rope, rope.isValid(ri) { if preferEnd { - guard i._utf8Offset > 0, i._utf8ChunkOffset == 0 else { return i } + guard i.utf8Offset > 0, i._utf8ChunkOffset == 0 else { return i } rope.formIndex(before: &ri) let length = rope[ri].utf8Count let ci = String.Index(_utf8Offset: length) - var j = Index(baseUTF8Offset: i._utf8Offset - length, rope: ri, chunk: ci) + var j = Index(baseUTF8Offset: i.utf8Offset - length, rope: ri, chunk: ci) j._flags = i._flags return j } - guard i._utf8Offset < utf8Count, i._utf8ChunkOffset == rope[ri].utf8Count else { + guard i.utf8Offset < utf8Count, i._utf8ChunkOffset == rope[ri].utf8Count else { return i } rope.formIndex(after: &ri) let ci = String.Index(_utf8Offset: 0) - var j = Index(baseUTF8Offset: i._utf8Offset, rope: ri, chunk: ci) + var j = Index(baseUTF8Offset: i.utf8Offset, rope: ri, chunk: ci) j._flags = i._flags return j } let (ri, chunkOffset) = rope.find( - at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) + at: i.utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) let ci = String.Index( _utf8Offset: chunkOffset, utf16TrailingSurrogate: i._isUTF16TrailingSurrogate) - return Index(baseUTF8Offset: i._utf8Offset - ci._utf8Offset, rope: ri, chunk: ci) + return Index(baseUTF8Offset: i.utf8Offset - ci._utf8Offset, rope: ri, chunk: ci) } } #endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Invariants.swift b/Sources/RopeModule/BString/Basics/_BString+Invariants.swift index ec88d4d3..92206213 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Invariants.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Invariants.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - func invariantCheck() { + public func invariantCheck() { #if DEBUG rope.invariantCheck() let allowUndersize = rope.isSingleton diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift index a38f97e5..d11edc2c 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift @@ -37,384 +37,50 @@ extension _BString.ChunkIterator: IteratorProtocol { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal struct UTF8Iterator { - internal let _base: _BString - internal var _index: _BString.Index - - internal init(_base: _BString, from start: _BString.Index) { - self._base = _base - self._index = _base.utf8Index(roundingDown: start) - } - } - + @available(*, deprecated) + internal typealias UTF8Iterator = UTF8View.Iterator + + @available(*, deprecated) internal func makeUTF8Iterator() -> UTF8Iterator { UTF8Iterator(_base: self, from: self.startIndex) } + @available(*, deprecated) internal func makeUTF8Iterator(from start: Index) -> UTF8Iterator { UTF8Iterator(_base: self, from: start) } } -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF8Iterator: IteratorProtocol { - internal typealias Element = UInt8 - - internal mutating func next() -> UInt8? { - guard _index < _base.endIndex else { return nil } - // Hand-optimized from `_base.subscript(utf8:)` and `_base.utf8Index(after:)`. - let ri = _index._rope! - var ci = _index._chunkIndex - let chunk = _base.rope[ri] - let result = chunk.string.utf8[ci] - - chunk.string.utf8.formIndex(after: &ci) - if ci < chunk.string.endIndex { - _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) - } else { - _index = _BString.Index( - baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, - rope: _base.rope.index(after: ri), - chunk: String.Index(_utf8Offset: 0)) - } - return result - } - - internal mutating func next( - maximumCount: Int, - with body: (UnsafeBufferPointer) -> (consumed: Int, result: R) - ) -> R { - guard _index < _base.endIndex else { - let r = body(UnsafeBufferPointer(start: nil, count: 0)) - precondition(r.consumed == 0) - return r.result - } - let ri = _index._rope! - var ci = _index._utf8ChunkOffset - var utf8Offset = _index._utf8Offset - var string = _base.rope[ri].string - let (haveMore, result) = string.withUTF8 { buffer in - let slice = buffer[ci...].prefix(maximumCount) - assert(!slice.isEmpty) - let (consumed, result) = body(UnsafeBufferPointer(rebasing: slice)) - precondition(consumed >= 0 && consumed <= slice.count) - utf8Offset += consumed - ci += consumed - return (ci < buffer.count, result) - } - if haveMore { - _index = _BString.Index(_utf8Offset: utf8Offset, rope: ri, chunkOffset: ci) - } else { - _index = _BString.Index( - baseUTF8Offset: _index._utf8BaseOffset + string.utf8.count, - rope: _base.rope.index(after: ri), - chunk: String.Index(_utf8Offset: 0)) - } - return result - } -} - @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal struct UTF16Iterator { - internal let _base: _BString - internal var _index: _BString.Index - - internal init(_base: _BString, from start: _BString.Index) { - self._base = _base - self._index = _base.utf16Index(roundingDown: start) - } - } - + @available(*, deprecated) + internal typealias UTF16Iterator = UTF16View.Iterator + + @available(*, deprecated) internal func makeUTF16Iterator() -> UTF16Iterator { UTF16Iterator(_base: self, from: self.startIndex) } + @available(*, deprecated) internal func makeUTF16Iterator(from start: Index) -> UTF16Iterator { UTF16Iterator(_base: self, from: start) } } -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF16Iterator: IteratorProtocol { - internal typealias Element = UInt16 - - internal mutating func next() -> UInt16? { - guard _index < _base.endIndex else { return nil } - let ri = _index._rope! - var ci = _index._chunkIndex - let chunk = _base.rope[ri] - let result = chunk.string.utf16[ci] - - chunk.string.utf16.formIndex(after: &ci) - if ci < chunk.string.endIndex { - _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) - } else { - _index = _BString.Index( - baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, - rope: _base.rope.index(after: ri), - chunk: String.Index(_utf8Offset: 0)) - } - return result - } -} - @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal struct UnicodeScalarIterator { - internal let _base: _BString - internal var _index: _BString.Index - - internal init(_base: _BString, from start: _BString.Index) { - self._base = _base - self._index = _base.unicodeScalarIndex(roundingDown: start) - } - } + @available(*, deprecated) + internal typealias UnicodeScalarIterator = UnicodeScalarView.Iterator + @available(*, deprecated) internal func makeUnicodeScalarIterator() -> UnicodeScalarIterator { UnicodeScalarIterator(_base: self, from: startIndex) } + @available(*, deprecated) internal func makeUnicodeScalarIterator(from start: Index) -> UnicodeScalarIterator { UnicodeScalarIterator(_base: self, from: start) } } -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarIterator: IteratorProtocol { - internal typealias Element = Unicode.Scalar - - internal mutating func next() -> Unicode.Scalar? { - guard _index < _base.endIndex else { return nil } - let ri = _index._rope! - var ci = _index._chunkIndex - let chunk = _base.rope[ri] - let result = chunk.string.unicodeScalars[ci] - - chunk.string.unicodeScalars.formIndex(after: &ci) - if ci < chunk.string.endIndex { - _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) - } else { - _index = _BString.Index( - baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, - rope: _base.rope.index(after: ri), - chunk: String.Index(_utf8Offset: 0)) - } - return result - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - internal struct CharacterIterator { - internal let _base: _BString - internal var _utf8BaseOffset: Int - internal var _ropeIndex: Rope.Index - internal var _chunkIndex: String.Index - internal var _next: String.Index - - internal init(_ string: _BString) { - self._base = string - self._ropeIndex = string.rope.startIndex - string.rope.ensureLeaf(in: &_ropeIndex) - - self._utf8BaseOffset = 0 - guard _ropeIndex < string.rope.endIndex else { - _chunkIndex = "".startIndex - _next = "".endIndex - return - } - let chunk = _base.rope[_ropeIndex] - assert(chunk.firstBreak == chunk.string.startIndex) - self._chunkIndex = chunk.firstBreak - self._next = chunk.string[_chunkIndex...].index(after: _chunkIndex) - } - - internal init( - _ string: _BString, - from start: Index - ) { - self._base = string - self._utf8BaseOffset = start._utf8Offset - - if start == string.endIndex { - self._ropeIndex = string.rope.endIndex - self._chunkIndex = "".startIndex - self._next = "".endIndex - return - } - let i = string.resolve(start, preferEnd: false) - self._ropeIndex = i._rope! - self._utf8BaseOffset = i._utf8BaseOffset - self._chunkIndex = i._chunkIndex - self._next = _base.rope[_ropeIndex].wholeCharacters.index(after: _chunkIndex) - } - } - - internal func makeCharacterIterator() -> CharacterIterator { - CharacterIterator(self) - } - - internal func makeCharacterIterator(from index: Index) -> CharacterIterator { - CharacterIterator(self, from: index) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.CharacterIterator: IteratorProtocol { - internal typealias Element = Character - - internal var isAtEnd: Bool { - _chunkIndex == _next - } - - internal var isAtStart: Bool { - _ropeIndex == _base.rope.startIndex && _chunkIndex._utf8Offset == 0 - } - - internal var current: Element { - assert(!isAtEnd) - let chunk = _base.rope[_ropeIndex] - var str = String(chunk.string[_chunkIndex ..< _next]) - if _next < chunk.string.endIndex { return Character(str) } - - var i = _base.rope.index(after: _ropeIndex) - while i < _base.rope.endIndex { - let chunk = _base.rope[i] - let b = chunk.firstBreak - str += chunk.string[.. Bool { - guard !isAtEnd else { return false } - let chunk = _base.rope[_ropeIndex] - if _next < chunk.string.endIndex { - _chunkIndex = _next - _next = chunk.wholeCharacters.index(after: _next) - return true - } - var baseOffset = _utf8BaseOffset + chunk.utf8Count - var i = _base.rope.index(after: _ropeIndex) - while i < _base.rope.endIndex { - let chunk = _base.rope[i] - let b = chunk.firstBreak - if b < chunk.string.endIndex { - _ropeIndex = i - _utf8BaseOffset = baseOffset - _chunkIndex = b - _next = chunk.string[b...].index(after: b) - return true - } - baseOffset += chunk.utf8Count - _base.rope.formIndex(after: &i) - } - return false - } - - mutating func stepBackward() -> Bool { - if !isAtEnd { - let chunk = _base.rope[_ropeIndex] - let i = chunk.firstBreak - if _chunkIndex > i { - _next = _chunkIndex - _chunkIndex = chunk.string[i...].index(before: _chunkIndex) - return true - } - } - var i = _ropeIndex - var baseOffset = _utf8BaseOffset - while i > _base.rope.startIndex { - _base.rope.formIndex(before: &i) - let chunk = _base.rope[i] - baseOffset -= chunk.utf8Count - if chunk.hasBreaks { - _ropeIndex = i - _utf8BaseOffset = baseOffset - _next = chunk.string.endIndex - _chunkIndex = chunk.lastBreak - return true - } - } - return false - } - - internal mutating func next() -> Character? { - guard !isAtEnd else { return nil } - let item = self.current - if !stepForward() { - _chunkIndex = _next - } - return item - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.CharacterIterator { - // The UTF-8 offset of the current position, from the start of the string. - var utf8Offset: Int { - _utf8BaseOffset + _chunkIndex._utf8Offset - } - - var index: _BString.Index { - _BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _chunkIndex) - } - - internal var nextIndex: _BString.Index { - assert(!isAtEnd) - let chunk = _base.rope[_ropeIndex] - if _next < chunk.string.endIndex { - return _BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _next) - } - var i = _base.rope.index(after: _ropeIndex) - var base = _utf8BaseOffset - while i < _base.rope.endIndex { - let chunk = _base.rope[i] - let b = chunk.firstBreak - if b < chunk.string.endIndex { - return _BString.Index(baseUTF8Offset: base, rope: i, chunk: b) - } - base += chunk.utf8Count - _base.rope.formIndex(after: &i) - } - return _base.endIndex - } - - /// The UTF-8 offset range of the current character, measured from the start of the string. - var utf8Range: Range { - assert(!isAtEnd) - let start = utf8Offset - var end = _utf8BaseOffset - var chunk = _base.rope[_ropeIndex] - if _next < chunk.string.endIndex { - end += _next._utf8Offset - return Range(uncheckedBounds: (start, end)) - } - end += chunk.utf8Count - var i = _base.rope.index(after: _ropeIndex) - while i < _base.rope.endIndex { - chunk = _base.rope[i] - let b = chunk.firstBreak - if b < chunk.string.endIndex { - end += b._utf8Offset - break - } - end += chunk.utf8Count - _base.rope.formIndex(after: &i) - } - return Range(uncheckedBounds: (start, end)) - } - - func isAbove(_ index: _BString.Index) -> Bool { - self.utf8Offset > index._utf8Offset - } - - func isBelow(_ index: _BString.Index) -> Bool { - self.utf8Offset < index._utf8Offset - } -} - #endif diff --git a/Sources/RopeModule/BString/Basics/_BString.swift b/Sources/RopeModule/BString/Basics/_BString.swift index 8d5cf239..c3be84be 100644 --- a/Sources/RopeModule/BString/Basics/_BString.swift +++ b/Sources/RopeModule/BString/Basics/_BString.swift @@ -13,7 +13,7 @@ /// The core of a B-tree based String implementation. @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -internal struct _BString: Sendable { +public struct _BString: Sendable { typealias Rope = _Rope var rope: Rope @@ -28,6 +28,6 @@ internal struct _BString: Sendable { // `_BString` depends on fixes and newly exposed functionality that landed in // version 5.8 of the Swift Standard Library. @available(*, unavailable, message: "_BString depends on version 5.8 of the Swift Standard Library") -internal struct _BString: Sendable {} +public struct _BString: Sendable {} #endif diff --git a/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift b/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift index 6e0c4840..8cb61c2d 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift @@ -13,61 +13,61 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: BidirectionalCollection { - typealias SubSequence = _BSubstring + public typealias SubSequence = _BSubstring - var isEmpty: Bool { + public var isEmpty: Bool { rope.summary.isZero } - var startIndex: Index { + public var startIndex: Index { Index(_utf8Offset: 0)._knownCharacterAligned() } - var endIndex: Index { + public var endIndex: Index { Index(_utf8Offset: utf8Count)._knownCharacterAligned() } - internal var count: Int { characterCount } + public var count: Int { characterCount } @inline(__always) - internal func index(after i: Index) -> Index { + public func index(after i: Index) -> Index { characterIndex(after: i) } @inline(__always) - internal func index(before i: Index) -> Index { + public func index(before i: Index) -> Index { characterIndex(before: i) } @inline(__always) - internal func index(_ i: Index, offsetBy distance: Int) -> Index { + public func index(_ i: Index, offsetBy distance: Int) -> Index { characterIndex(i, offsetBy: distance) } - internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + public 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 { + public func distance(from start: Index, to end: Index) -> Int { characterDistance(from: start, to: end) } - internal subscript(position: Index) -> Character { + public subscript(position: Index) -> Character { self[character: position] } - internal subscript(bounds: Range) -> _BSubstring { + public subscript(bounds: Range) -> _BSubstring { _BSubstring(self, in: bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal func index(roundingDown i: Index) -> Index { + public func index(roundingDown i: Index) -> Index { characterIndex(roundingDown: i) } - internal func index(roundingUp i: Index) -> Index { + public func index(roundingUp i: Index) -> Index { characterIndex(roundingUp: i) } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift b/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift index 565e43ce..deb4677c 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: Comparable { - internal static func < (left: Self, right: Self) -> Bool { + public static func < (left: Self, right: 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 diff --git a/Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift b/Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift index 5ff96a31..75b738c5 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: CustomDebugStringConvertible { - internal var debugDescription: String { + public var debugDescription: String { description.debugDescription } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift b/Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift index 2ba2e91a..1b6f1696 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift @@ -13,8 +13,8 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: CustomStringConvertible { - internal var description: String { - String(_from: self) + public var description: String { + String(self) } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift b/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift index f87ed408..e5f77ac5 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift @@ -13,14 +13,14 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - func isIdentical(to other: Self) -> Bool { + public func isIdentical(to other: Self) -> Bool { self.rope.isIdentical(to: other.rope) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: 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 @@ -73,8 +73,8 @@ extension _BString { // 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 = left.makeUTF8Iterator() - var it2 = right.makeUTF8Iterator() + var it1 = left.utf8.makeIterator() + var it2 = right.utf8.makeIterator() var remaining = left.utf8Count while remaining > 0 { @@ -102,8 +102,8 @@ extension _BString { guard leftUTF8Count == rightUTF8Count else { return false } var remaining = leftUTF8Count - var it1 = left.makeUTF8Iterator(from: leftRange.lowerBound) - var it2 = right.makeUTF8Iterator(from: rightRange.lowerBound) + var it1 = _BString.UTF8View.Iterator(_base: left, from: leftRange.lowerBound) + var it2 = _BString.UTF8View.Iterator(_base: right, from: rightRange.lowerBound) while remaining > 0 { let consumed = it1.next(maximumCount: remaining) { b1 in diff --git a/Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift b/Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift index 9c86e397..6c2bc6c4 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: ExpressibleByStringLiteral { - internal init(stringLiteral value: String) { + public init(stringLiteral value: String) { self.init(value) } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift index 99f682fa..2e95cc2a 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: Hashable { - internal func hash(into hasher: inout Hasher) { + public func hash(into hasher: inout Hasher) { hashCharacters(into: &hasher) } } @@ -36,7 +36,7 @@ extension _BString { internal func hashCharacters(into hasher: inout Hasher, from range: Range) { var it = self.makeCharacterIterator(from: range.lowerBound) - let endOffset = range.upperBound._utf8Offset + let endOffset = range.upperBound.utf8Offset while let character = it.next() { var s = String(character) if it.utf8Offset > endOffset { diff --git a/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift b/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift index 62382c8b..8081bc4b 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift @@ -13,15 +13,15 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: RangeReplaceableCollection { - internal init() { + public init() { self.init(rope: Rope()) } - internal mutating func reserveCapacity(_ n: Int) { + public mutating func reserveCapacity(_ n: Int) { // Do nothing. } - internal mutating func replaceSubrange>( // Note: Sequence, not Collection + public mutating func replaceSubrange>( // Note: Sequence, not Collection _ subrange: Range, with newElements: __owned S ) { if S.self == String.self { @@ -41,31 +41,31 @@ extension _BString: RangeReplaceableCollection { } } - internal mutating func replaceSubrange( + public mutating func replaceSubrange( _ subrange: Range, with newElements: __owned String ) { _replaceSubrange(subrange, with: newElements) } - internal mutating func replaceSubrange( + public mutating func replaceSubrange( _ subrange: Range, with newElements: __owned Substring ) { _replaceSubrange(subrange, with: newElements) } - internal mutating func replaceSubrange( + public mutating func replaceSubrange( _ subrange: Range, with newElements: __owned _BString ) { _replaceSubrange(subrange, with: newElements) } - internal mutating func replaceSubrange( + public mutating func replaceSubrange( _ subrange: Range, with newElements: __owned _BSubstring ) { _replaceSubrange(subrange, with: newElements) } - internal init>(_ elements: S) { + public init>(_ elements: S) { if S.self == String.self { let elements = _identityCast(elements, to: String.self) self.init(_from: elements) @@ -82,31 +82,31 @@ extension _BString: RangeReplaceableCollection { } } - internal init(_ elements: String) { + public init(_ elements: String) { self.init(_from: elements) } - internal init(_ elements: Substring) { + public init(_ elements: Substring) { self.init(_from: elements) } - internal init(_ elements: _BString) { + public init(_ elements: _BString) { self = elements } - internal init(_ elements: _BSubstring) { + public init(_ elements: _BSubstring) { self.init(_from: elements) } - internal init(repeating repeatedValue: Character, count: Int) { + public init(repeating repeatedValue: Character, count: Int) { self.init(repeating: _BString(String(repeatedValue)), count: count) } - internal init(repeating repeatedValue: some StringProtocol, count: Int) { + public init(repeating repeatedValue: some StringProtocol, count: Int) { self.init(repeating: _BString(repeatedValue), count: count) } - internal init(repeating value: Self, count: Int) { + public init(repeating value: Self, count: Int) { precondition(count >= 0, "Negative count") guard count > 0 else { self.init() @@ -128,15 +128,15 @@ extension _BString: RangeReplaceableCollection { } } - internal init(repeating value: _BSubstring, count: Int) { + public init(repeating value: _BSubstring, count: Int) { self.init(repeating: _BString(value), count: count) } - internal mutating func append(_ newElement: __owned Character) { + public mutating func append(_ newElement: __owned Character) { append(contentsOf: String(newElement)) } - internal mutating func append>(contentsOf newElements: __owned S) { + public mutating func append>(contentsOf newElements: __owned S) { if S.self == String.self { let newElements = _identityCast(newElements, to: String.self) append(contentsOf: newElements) @@ -154,27 +154,27 @@ extension _BString: RangeReplaceableCollection { } } - internal mutating func append(contentsOf newElements: __owned String) { + public mutating func append(contentsOf newElements: __owned String) { _append(contentsOf: newElements[...]) } - internal mutating func append(contentsOf newElements: __owned Substring) { + public mutating func append(contentsOf newElements: __owned Substring) { _append(contentsOf: newElements) } - internal mutating func append(contentsOf newElements: __owned _BString) { + public mutating func append(contentsOf newElements: __owned _BString) { _append(contentsOf: newElements) } - internal mutating func append(contentsOf newElements: __owned _BSubstring) { + public mutating func append(contentsOf newElements: __owned _BSubstring) { _append(contentsOf: newElements._base, in: newElements._bounds) } - internal mutating func insert(_ newElement: Character, at i: Index) { + public mutating func insert(_ newElement: Character, at i: Index) { insert(contentsOf: String(newElement), at: i) } - internal mutating func insert>( // Note: Sequence, not Collection + public mutating func insert>( // Note: Sequence, not Collection contentsOf newElements: __owned S, at i: Index ) { if S.self == String.self { @@ -194,32 +194,32 @@ extension _BString: RangeReplaceableCollection { } } - internal mutating func insert(contentsOf newElements: __owned String, at i: Index) { + public 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) { + public 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) { + public 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) { + public 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 { + public mutating func remove(at i: Index) -> Character { removeCharacter(at: i) } - internal mutating func removeSubrange(_ bounds: Range) { + public mutating func removeSubrange(_ bounds: Range) { _removeSubrange(bounds) } - internal mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { self = _BString() } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Sequence.swift b/Sources/RopeModule/BString/Conformances/_BString+Sequence.swift index 959b09be..4c0d849f 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Sequence.swift +++ b/Sources/RopeModule/BString/Conformances/_BString+Sequence.swift @@ -13,13 +13,228 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString: Sequence { - typealias Element = Character + public typealias Element = Character - typealias Iterator = CharacterIterator + @available(*, deprecated, renamed: "Iterator") + internal typealias CharacterIterator = Iterator - internal func makeIterator() -> Iterator { - makeCharacterIterator() + public func makeIterator() -> Iterator { + Iterator(self) + } + + internal func makeCharacterIterator() -> Iterator { + Iterator(self) + } + + internal func makeCharacterIterator(from index: Index) -> Iterator { + Iterator(self, from: index) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString { + public struct Iterator { + internal let _base: _BString + internal var _utf8BaseOffset: Int + internal var _ropeIndex: Rope.Index + internal var _chunkIndex: String.Index + internal var _next: String.Index + + internal init(_ string: _BString) { + self._base = string + self._ropeIndex = string.rope.startIndex + string.rope.ensureLeaf(in: &_ropeIndex) + + self._utf8BaseOffset = 0 + guard _ropeIndex < string.rope.endIndex else { + _chunkIndex = "".startIndex + _next = "".endIndex + return + } + let chunk = _base.rope[_ropeIndex] + assert(chunk.firstBreak == chunk.string.startIndex) + self._chunkIndex = chunk.firstBreak + self._next = chunk.string[_chunkIndex...].index(after: _chunkIndex) + } + + internal init( + _ string: _BString, + from start: Index + ) { + self._base = string + self._utf8BaseOffset = start.utf8Offset + + if start == string.endIndex { + self._ropeIndex = string.rope.endIndex + self._chunkIndex = "".startIndex + self._next = "".endIndex + return + } + let i = string.resolve(start, preferEnd: false) + self._ropeIndex = i._rope! + self._utf8BaseOffset = i._utf8BaseOffset + self._chunkIndex = i._chunkIndex + self._next = _base.rope[_ropeIndex].wholeCharacters.index(after: _chunkIndex) + } + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.Iterator: IteratorProtocol { + public typealias Element = Character + + internal var isAtEnd: Bool { + _chunkIndex == _next + } + + internal var isAtStart: Bool { + _ropeIndex == _base.rope.startIndex && _chunkIndex._utf8Offset == 0 + } + + internal var current: Element { + assert(!isAtEnd) + let chunk = _base.rope[_ropeIndex] + var str = String(chunk.string[_chunkIndex ..< _next]) + if _next < chunk.string.endIndex { return Character(str) } + + var i = _base.rope.index(after: _ropeIndex) + while i < _base.rope.endIndex { + let chunk = _base.rope[i] + let b = chunk.firstBreak + str += chunk.string[.. Bool { + guard !isAtEnd else { return false } + let chunk = _base.rope[_ropeIndex] + if _next < chunk.string.endIndex { + _chunkIndex = _next + _next = chunk.wholeCharacters.index(after: _next) + return true + } + var baseOffset = _utf8BaseOffset + chunk.utf8Count + var i = _base.rope.index(after: _ropeIndex) + while i < _base.rope.endIndex { + let chunk = _base.rope[i] + let b = chunk.firstBreak + if b < chunk.string.endIndex { + _ropeIndex = i + _utf8BaseOffset = baseOffset + _chunkIndex = b + _next = chunk.string[b...].index(after: b) + return true + } + baseOffset += chunk.utf8Count + _base.rope.formIndex(after: &i) + } + return false + } + + mutating func stepBackward() -> Bool { + if !isAtEnd { + let chunk = _base.rope[_ropeIndex] + let i = chunk.firstBreak + if _chunkIndex > i { + _next = _chunkIndex + _chunkIndex = chunk.string[i...].index(before: _chunkIndex) + return true + } + } + var i = _ropeIndex + var baseOffset = _utf8BaseOffset + while i > _base.rope.startIndex { + _base.rope.formIndex(before: &i) + let chunk = _base.rope[i] + baseOffset -= chunk.utf8Count + if chunk.hasBreaks { + _ropeIndex = i + _utf8BaseOffset = baseOffset + _next = chunk.string.endIndex + _chunkIndex = chunk.lastBreak + return true + } + } + return false + } + + public mutating func next() -> Character? { + guard !isAtEnd else { return nil } + let item = self.current + if !stepForward() { + _chunkIndex = _next + } + return item + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.Iterator { + // The UTF-8 offset of the current position, from the start of the string. + var utf8Offset: Int { + _utf8BaseOffset + _chunkIndex._utf8Offset + } + + var index: _BString.Index { + _BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _chunkIndex) + } + + internal var nextIndex: _BString.Index { + assert(!isAtEnd) + let chunk = _base.rope[_ropeIndex] + if _next < chunk.string.endIndex { + return _BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _next) + } + var i = _base.rope.index(after: _ropeIndex) + var base = _utf8BaseOffset + while i < _base.rope.endIndex { + let chunk = _base.rope[i] + let b = chunk.firstBreak + if b < chunk.string.endIndex { + return _BString.Index(baseUTF8Offset: base, rope: i, chunk: b) + } + base += chunk.utf8Count + _base.rope.formIndex(after: &i) + } + return _base.endIndex + } + + /// The UTF-8 offset range of the current character, measured from the start of the string. + var utf8Range: Range { + assert(!isAtEnd) + let start = utf8Offset + var end = _utf8BaseOffset + var chunk = _base.rope[_ropeIndex] + if _next < chunk.string.endIndex { + end += _next._utf8Offset + return Range(uncheckedBounds: (start, end)) + } + end += chunk.utf8Count + var i = _base.rope.index(after: _ropeIndex) + while i < _base.rope.endIndex { + chunk = _base.rope[i] + let b = chunk.firstBreak + if b < chunk.string.endIndex { + end += b._utf8Offset + break + } + end += chunk.utf8Count + _base.rope.formIndex(after: &i) + } + return Range(uncheckedBounds: (start, end)) + } + + func isAbove(_ index: _BString.Index) -> Bool { + self.utf8Offset > index.utf8Offset + } + + func isBelow(_ index: _BString.Index) -> Bool { + self.utf8Offset < index.utf8Offset + } +} + + #endif diff --git a/Sources/RopeModule/BString/Operations/Range+_BString.swift b/Sources/RopeModule/BString/Operations/Range+_BString.swift index 621458d9..a8361fa4 100644 --- a/Sources/RopeModule/BString/Operations/Range+_BString.swift +++ b/Sources/RopeModule/BString/Operations/Range+_BString.swift @@ -14,7 +14,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension Range<_BString.Index> { internal var _isEmptyUTF8: Bool { - lowerBound._utf8Offset == upperBound._utf8Offset + lowerBound.utf8Offset == upperBound.utf8Offset } } diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift index b9ecb469..c0da8835 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Initializers.swift @@ -63,8 +63,8 @@ extension _BString { in range: Range ) { self.rope = other.rope.extract( - from: range.lowerBound._utf8Offset, - to: range.upperBound._utf8Offset, + from: range.lowerBound.utf8Offset, + to: range.upperBound.utf8Offset, in: UTF8Metric()) var old = other._breakState(upTo: range.lowerBound) var new = _CharacterRecognizer() @@ -77,8 +77,8 @@ extension _BString { state: inout _CharacterRecognizer ) { self.rope = other.rope.extract( - from: range.lowerBound._utf8Offset, - to: range.upperBound._utf8Offset, + from: range.lowerBound.utf8Offset, + to: range.upperBound.utf8Offset, in: UTF8Metric()) var old = other._breakState(upTo: range.lowerBound) var new = state @@ -88,7 +88,7 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String { - internal init(_from big: _BString) { + public init(_ big: _BString) { guard !big.isEmpty else { self.init() return @@ -113,7 +113,7 @@ extension String { var end = big.unicodeScalarIndex(roundingDown: range.upperBound) end = big.resolve(end, preferEnd: true) - let utf8Capacity = end._utf8Offset - start._utf8Offset + let utf8Capacity = end.utf8Offset - start.utf8Offset guard utf8Capacity > 0 else { return } self.reserveCapacity(utf8Capacity) @@ -134,15 +134,15 @@ extension String { self += big.rope[endRopeIndex].string[..) { precondition(bounds.upperBound <= endIndex, "Index out of bounds") if bounds.isEmpty { return } - let lower = bounds.lowerBound._utf8Offset - let upper = bounds.upperBound._utf8Offset + let lower = bounds.lowerBound.utf8Offset + let upper = bounds.upperBound.utf8Offset rope.removeSubrange(lower ..< upper, in: UTF8Metric()) } } diff --git a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift index f50ec982..45ce4195 100644 --- a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift +++ b/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift @@ -66,8 +66,8 @@ extension _BString { } mutating func _split(removing range: Range) -> Builder { - let lower = range.lowerBound._utf8Offset - let upper = range.upperBound._utf8Offset + let lower = range.lowerBound.utf8Offset + let upper = range.upperBound.utf8Offset // FIXME: Don't split the indices twice -- they are currently split once here and once in the // builder initializer below. diff --git a/Sources/RopeModule/BString/Operations/_BString+Split.swift b/Sources/RopeModule/BString/Operations/_BString+Split.swift index 694e0c96..91f9e008 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Split.swift +++ b/Sources/RopeModule/BString/Operations/_BString+Split.swift @@ -35,7 +35,7 @@ extension _BString { if let ri = index._rope, rope.isValid(ri) { return rope.split(at: ri, index._chunkIndex) } - return rope.builder(splittingAt: index._utf8Offset, in: UTF8Metric()) + return rope.builder(splittingAt: index.utf8Offset, in: UTF8Metric()) } } diff --git a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift b/Sources/RopeModule/BString/Views/_BString+UTF16View.swift index 5989af7f..76e405e0 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: Sendable { + public struct UTF16View: Sendable { var _base: _BString @inline(__always) @@ -23,95 +23,128 @@ extension _BString { } @inline(__always) - internal var utf16: UTF16View { + public var utf16: UTF16View { UTF16View(_base: self) } - internal init(_ utf16: UTF16View) { + public init(_ utf16: UTF16View) { self = utf16._base } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF16View: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, to: right._base) } - internal func isIdentical(to other: Self) -> Bool { + public func isIdentical(to other: Self) -> Bool { self._base.isIdentical(to: other._base) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF16View: Hashable { - internal func hash(into hasher: inout Hasher) { + public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF16View: Sequence { - typealias Element = UInt16 - typealias Iterator = _BString.UTF16Iterator + public typealias Element = UInt16 - internal func makeIterator() -> _BString.UTF16Iterator { - _base.makeUTF16Iterator() + public struct Iterator { + internal let _base: _BString + internal var _index: _BString.Index + + internal init(_base: _BString, from start: _BString.Index) { + self._base = _base + self._index = _base.utf16Index(roundingDown: start) + } + } + + public func makeIterator() -> Iterator { + Iterator(_base: _base, from: startIndex) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF16View.Iterator: IteratorProtocol { + public typealias Element = UInt16 + + public mutating func next() -> UInt16? { + guard _index < _base.endIndex else { return nil } + let ri = _index._rope! + var ci = _index._chunkIndex + let chunk = _base.rope[ri] + let result = chunk.string.utf16[ci] + + chunk.string.utf16.formIndex(after: &ci) + if ci < chunk.string.endIndex { + _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) + } else { + _index = _BString.Index( + baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, + rope: _base.rope.index(after: ri), + chunk: String.Index(_utf8Offset: 0)) + } + return result } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF16View: BidirectionalCollection { - typealias Index = _BString.Index - typealias SubSequence = _BSubstring.UTF16View + public typealias Index = _BString.Index + public typealias SubSequence = _BSubstring.UTF16View @inline(__always) - internal var startIndex: Index { _base.startIndex } + public var startIndex: Index { _base.startIndex } @inline(__always) - internal var endIndex: Index { _base.endIndex } + public var endIndex: Index { _base.endIndex } - internal var count: Int { _base.utf16Count } + public var count: Int { _base.utf16Count } @inline(__always) - internal func index(after i: Index) -> Index { + public func index(after i: Index) -> Index { _base.utf16Index(after: i) } @inline(__always) - internal func index(before i: Index) -> Index { + public func index(before i: Index) -> Index { _base.utf16Index(before: i) } @inline(__always) - internal func index(_ i: Index, offsetBy distance: Int) -> Index { + public func index(_ i: Index, offsetBy distance: Int) -> Index { _base.utf16Index(i, offsetBy: distance) } - internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { _base.utf16Index(i, offsetBy: distance, limitedBy: limit) } - internal func distance(from start: Index, to end: Index) -> Int { + public func distance(from start: Index, to end: Index) -> Int { _base.utf16Distance(from: start, to: end) } - internal subscript(position: Index) -> UInt16 { + public subscript(position: Index) -> UInt16 { _base[utf16: position] } - internal subscript(bounds: Range) -> _BSubstring.UTF16View { + public subscript(bounds: Range) -> _BSubstring.UTF16View { _BSubstring.UTF16View(_base, in: bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF16View { - internal func index(roundingDown i: Index) -> Index { + public func index(roundingDown i: Index) -> Index { _base.utf16Index(roundingDown: i) } - internal func index(roundingUp i: Index) -> Index { + public func index(roundingUp i: Index) -> Index { _base.utf16Index(roundingUp: i) } } diff --git a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift b/Sources/RopeModule/BString/Views/_BString+UTF8View.swift index 53dd82eb..582e0d6f 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: Sendable { + public struct UTF8View: Sendable { var _base: _BString @inline(__always) @@ -23,95 +23,164 @@ extension _BString { } @inline(__always) - internal var utf8: UTF8View { + public var utf8: UTF8View { UTF8View(_base: self) } - internal init(_ utf8: UTF8View) { + public init(_ utf8: UTF8View) { self = utf8._base } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF8View: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, to: right._base) } - internal func isIdentical(to other: Self) -> Bool { + public func isIdentical(to other: Self) -> Bool { self._base.isIdentical(to: other._base) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF8View: Hashable { - internal func hash(into hasher: inout Hasher) { + public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF8View: Sequence { - typealias Element = UInt8 - typealias Iterator = _BString.UTF8Iterator + public typealias Element = UInt8 - internal func makeIterator() -> _BString.UTF8Iterator { - _base.makeUTF8Iterator() + public struct Iterator { + internal let _base: _BString + internal var _index: _BString.Index + + internal init(_base: _BString, from start: _BString.Index) { + self._base = _base + self._index = _base.utf8Index(roundingDown: start) + } + } + + public func makeIterator() -> Iterator { + Iterator(_base: _base, from: self.startIndex) } } +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UTF8View.Iterator: IteratorProtocol { + public typealias Element = UInt8 + + public mutating func next() -> UInt8? { + guard _index < _base.endIndex else { return nil } + // Hand-optimized from `_base.subscript(utf8:)` and `_base.utf8Index(after:)`. + let ri = _index._rope! + var ci = _index._chunkIndex + let chunk = _base.rope[ri] + let result = chunk.string.utf8[ci] + + chunk.string.utf8.formIndex(after: &ci) + if ci < chunk.string.endIndex { + _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) + } else { + _index = _BString.Index( + baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, + rope: _base.rope.index(after: ri), + chunk: String.Index(_utf8Offset: 0)) + } + return result + } + + public mutating func next( + maximumCount: Int, + with body: (UnsafeBufferPointer) -> (consumed: Int, result: R) + ) -> R { + guard _index < _base.endIndex else { + let r = body(UnsafeBufferPointer(start: nil, count: 0)) + precondition(r.consumed == 0) + return r.result + } + let ri = _index._rope! + var ci = _index._utf8ChunkOffset + var utf8Offset = _index.utf8Offset + var string = _base.rope[ri].string + let (haveMore, result) = string.withUTF8 { buffer in + let slice = buffer[ci...].prefix(maximumCount) + assert(!slice.isEmpty) + let (consumed, result) = body(UnsafeBufferPointer(rebasing: slice)) + precondition(consumed >= 0 && consumed <= slice.count) + utf8Offset += consumed + ci += consumed + return (ci < buffer.count, result) + } + if haveMore { + _index = _BString.Index(_utf8Offset: utf8Offset, rope: ri, chunkOffset: ci) + } else { + _index = _BString.Index( + baseUTF8Offset: _index._utf8BaseOffset + string.utf8.count, + rope: _base.rope.index(after: ri), + chunk: String.Index(_utf8Offset: 0)) + } + return result + } +} + + + @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF8View: BidirectionalCollection { - typealias Index = _BString.Index - typealias SubSequence = _BSubstring.UTF8View + public typealias Index = _BString.Index + public typealias SubSequence = _BSubstring.UTF8View @inline(__always) - internal var startIndex: Index { _base.startIndex } + public var startIndex: Index { _base.startIndex } @inline(__always) - internal var endIndex: Index { _base.endIndex } + public var endIndex: Index { _base.endIndex } - internal var count: Int { _base.utf8Count } + public var count: Int { _base.utf8Count } @inline(__always) - internal func index(after i: Index) -> Index { + public func index(after i: Index) -> Index { _base.utf8Index(after: i) } @inline(__always) - internal func index(before i: Index) -> Index { + public func index(before i: Index) -> Index { _base.utf8Index(before: i) } @inline(__always) - internal func index(_ i: Index, offsetBy distance: Int) -> Index { + public func index(_ i: Index, offsetBy distance: Int) -> Index { _base.utf8Index(i, offsetBy: distance) } - internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { _base.utf8Index(i, offsetBy: distance, limitedBy: limit) } - internal func distance(from start: Index, to end: Index) -> Int { + public func distance(from start: Index, to end: Index) -> Int { _base.utf8Distance(from: start, to: end) } - internal subscript(position: Index) -> UInt8 { + public subscript(position: Index) -> UInt8 { _base[utf8: position] } - internal subscript(bounds: Range) -> _BSubstring.UTF8View { + public subscript(bounds: Range) -> _BSubstring.UTF8View { _BSubstring.UTF8View(_base, in: bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UTF8View { - internal func index(roundingDown i: Index) -> Index { + public func index(roundingDown i: Index) -> Index { _base.utf8Index(roundingDown: i) } - internal func index(roundingUp i: Index) -> Index { + public func index(roundingUp i: Index) -> Index { _base.utf8Index(roundingUp: i) } } diff --git a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift index efbdf111..f1789383 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: Sendable { + public struct UnicodeScalarView: Sendable { var _base: _BString @inline(__always) @@ -23,7 +23,7 @@ extension _BString { } @inline(__always) - internal var unicodeScalars: UnicodeScalarView { + public var unicodeScalars: UnicodeScalarView { get { UnicodeScalarView(_base: self) } @@ -40,127 +40,160 @@ extension _BString { } } - internal init(_ view: _BString.UnicodeScalarView) { + public init(_ view: _BString.UnicodeScalarView) { self = view._base } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: ExpressibleByStringLiteral { - internal init(stringLiteral value: String) { + public init(stringLiteral value: String) { self.init(value.unicodeScalars) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: CustomStringConvertible { - internal var description: String { - String(_from: _base) + public var description: String { + String(_base) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: CustomDebugStringConvertible { - internal var debugDescription: String { + public var debugDescription: String { description.debugDescription } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, to: right._base) } - internal func isIdentical(to other: Self) -> Bool { + public func isIdentical(to other: Self) -> Bool { self._base.isIdentical(to: other._base) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: Hashable { - internal func hash(into hasher: inout Hasher) { + public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: Sequence { - typealias Element = UnicodeScalar - typealias Iterator = _BString.UnicodeScalarIterator + public typealias Element = UnicodeScalar - internal func makeIterator() -> _BString.UnicodeScalarIterator { - _base.makeUnicodeScalarIterator() + public struct Iterator { + internal let _base: _BString + internal var _index: _BString.Index + + internal init(_base: _BString, from start: _BString.Index) { + self._base = _base + self._index = _base.unicodeScalarIndex(roundingDown: start) + } + } + + public func makeIterator() -> Iterator { + Iterator(_base: self._base, from: self.startIndex) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension _BString.UnicodeScalarView.Iterator: IteratorProtocol { + public typealias Element = UnicodeScalar + + public mutating func next() -> UnicodeScalar? { + guard _index < _base.endIndex else { return nil } + let ri = _index._rope! + var ci = _index._chunkIndex + let chunk = _base.rope[ri] + let result = chunk.string.unicodeScalars[ci] + + chunk.string.unicodeScalars.formIndex(after: &ci) + if ci < chunk.string.endIndex { + _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) + } else { + _index = _BString.Index( + baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, + rope: _base.rope.index(after: ri), + chunk: String.Index(_utf8Offset: 0)) + } + return result } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: BidirectionalCollection { - typealias Index = _BString.Index - typealias SubSequence = _BSubstring.UnicodeScalarView + public typealias Index = _BString.Index + public typealias SubSequence = _BSubstring.UnicodeScalarView @inline(__always) - internal var startIndex: Index { _base.startIndex } + public var startIndex: Index { _base.startIndex } @inline(__always) - internal var endIndex: Index { _base.endIndex } + public var endIndex: Index { _base.endIndex } - internal var count: Int { _base.unicodeScalarCount } + public var count: Int { _base.unicodeScalarCount } @inline(__always) - internal func index(after i: Index) -> Index { + public func index(after i: Index) -> Index { _base.unicodeScalarIndex(after: i) } @inline(__always) - internal func index(before i: Index) -> Index { + public func index(before i: Index) -> Index { _base.unicodeScalarIndex(before: i) } @inline(__always) - internal func index(_ i: Index, offsetBy distance: Int) -> Index { + public func index(_ i: Index, offsetBy distance: Int) -> Index { _base.unicodeScalarIndex(i, offsetBy: distance) } - internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { _base.unicodeScalarIndex(i, offsetBy: distance, limitedBy: limit) } - internal func distance(from start: Index, to end: Index) -> Int { + public func distance(from start: Index, to end: Index) -> Int { _base.unicodeScalarDistance(from: start, to: end) } - internal subscript(position: Index) -> UnicodeScalar { + public subscript(position: Index) -> UnicodeScalar { _base[unicodeScalar: position] } - internal subscript(bounds: Range) -> _BSubstring.UnicodeScalarView { + public subscript(bounds: Range) -> _BSubstring.UnicodeScalarView { _BSubstring.UnicodeScalarView(_base, in: bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView { - internal func index(roundingDown i: Index) -> Index { + public func index(roundingDown i: Index) -> Index { _base.unicodeScalarIndex(roundingDown: i) } - internal func index(roundingUp i: Index) -> Index { + public func index(roundingUp i: Index) -> Index { _base.unicodeScalarIndex(roundingUp: i) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString.UnicodeScalarView: RangeReplaceableCollection { - internal init() { + public init() { self._base = _BString() } - internal mutating func reserveCapacity(_ n: Int) { + public mutating func reserveCapacity(_ n: Int) { // Do nothing. } - internal mutating func replaceSubrange>( // Note: Sequence, not Collection + public mutating func replaceSubrange>( // Note: Sequence, not Collection _ subrange: Range, with newElements: __owned C ) { if C.self == String.UnicodeScalarView.self { @@ -180,31 +213,31 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } } - internal mutating func replaceSubrange( + public mutating func replaceSubrange( _ subrange: Range, with newElements: __owned String.UnicodeScalarView ) { _base._replaceSubrange(subrange, with: String(newElements)) } - internal mutating func replaceSubrange( + public mutating func replaceSubrange( _ subrange: Range, with newElements: __owned Substring.UnicodeScalarView ) { _base._replaceSubrange(subrange, with: Substring(newElements)) } - internal mutating func replaceSubrange( + public mutating func replaceSubrange( _ subrange: Range, with newElements: __owned _BString.UnicodeScalarView ) { _base._replaceSubrange(subrange, with: newElements._base) } - internal mutating func replaceSubrange( + public mutating func replaceSubrange( _ subrange: Range, with newElements: __owned _BSubstring.UnicodeScalarView ) { _base._replaceSubrange(subrange, with: newElements._base, in: newElements._bounds) } - internal init>(_ elements: S) { + public init>(_ elements: S) { if S.self == String.UnicodeScalarView.self { let elements = _identityCast(elements, to: String.UnicodeScalarView.self) self.init(_base: _BString(_from: elements)) @@ -222,44 +255,44 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } } - internal init(_ elements: String.UnicodeScalarView) { + public init(_ elements: String.UnicodeScalarView) { self.init(_base: _BString(_from: elements)) } - internal init(_ elements: Substring.UnicodeScalarView) { + public init(_ elements: Substring.UnicodeScalarView) { self.init(_base: _BString(_from: elements)) } - internal init(_ elements: _BString.UnicodeScalarView) { + public init(_ elements: _BString.UnicodeScalarView) { self.init(_base: elements._base) } - internal init(_ elements: _BSubstring.UnicodeScalarView) { + public init(_ elements: _BSubstring.UnicodeScalarView) { self.init(_base: _BString(_from: elements._base, in: elements._bounds)) } - internal init(repeating repeatedValue: UnicodeScalar, count: Int) { + public init(repeating repeatedValue: UnicodeScalar, count: Int) { self.init(_base: _BString(repeating: _BString(String(repeatedValue)), count: count)) } - internal init(repeating repeatedValue: some StringProtocol, count: Int) { + public 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) { + public init(repeating value: _BString.UnicodeScalarView, count: Int) { self.init(_base: _BString(repeating: value._base, count: count)) } - internal init(repeating value: _BSubstring.UnicodeScalarView, count: Int) { + public 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) { + public mutating func append(_ newElement: __owned UnicodeScalar) { _base.append(contentsOf: String(newElement)) } - internal mutating func append>(contentsOf newElements: __owned S) { + public mutating func append>(contentsOf newElements: __owned S) { if S.self == String.UnicodeScalarView.self { let newElements = _identityCast(newElements, to: String.UnicodeScalarView.self) append(contentsOf: newElements) @@ -277,27 +310,27 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } } - internal mutating func append(contentsOf newElements: __owned String.UnicodeScalarView) { + public mutating func append(contentsOf newElements: __owned String.UnicodeScalarView) { _base.append(contentsOf: String(newElements)) } - internal mutating func append(contentsOf newElements: __owned Substring.UnicodeScalarView) { + public mutating func append(contentsOf newElements: __owned Substring.UnicodeScalarView) { _base.append(contentsOf: Substring(newElements)) } - internal mutating func append(contentsOf newElements: __owned _BString.UnicodeScalarView) { + public mutating func append(contentsOf newElements: __owned _BString.UnicodeScalarView) { _base.append(contentsOf: newElements._base) } - internal mutating func append(contentsOf newElements: __owned _BSubstring.UnicodeScalarView) { + public 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) { + public mutating func insert(_ newElement: UnicodeScalar, at i: Index) { _base.insert(contentsOf: String(newElement), at: i) } - internal mutating func insert>( // Note: Sequence, not Collection + public mutating func insert>( // Note: Sequence, not Collection contentsOf newElements: __owned C, at i: Index ) { if C.self == String.UnicodeScalarView.self { @@ -317,28 +350,28 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } } - internal mutating func insert( + public mutating func insert( contentsOf newElements: __owned String.UnicodeScalarView, at i: Index ) { _base.insert(contentsOf: String(newElements), at: i) } - internal mutating func insert( + public mutating func insert( contentsOf newElements: __owned Substring.UnicodeScalarView, at i: Index ) { _base.insert(contentsOf: Substring(newElements), at: i) } - internal mutating func insert( + public mutating func insert( contentsOf newElements: __owned _BString.UnicodeScalarView, at i: Index ) { _base.insert(contentsOf: newElements._base, at: i) } - internal mutating func insert( + public mutating func insert( contentsOf newElements: __owned _BSubstring.UnicodeScalarView, at i: Index ) { @@ -346,15 +379,15 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } @discardableResult - internal mutating func remove(at i: Index) -> UnicodeScalar { + public mutating func remove(at i: Index) -> UnicodeScalar { _base.removeUnicodeScalar(at: i) } - internal mutating func removeSubrange(_ bounds: Range) { + public mutating func removeSubrange(_ bounds: Range) { _base._removeSubrange(bounds) } - internal mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { self._base = _BString() } } diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift index 4e59bfbc..1ef974e2 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift @@ -13,16 +13,16 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { - internal struct UTF16View: Sendable { + public struct UTF16View: Sendable { internal var _base: _BString internal var _bounds: Range - internal init(_unchecked base: _BString, in bounds: Range) { + public init(_unchecked base: _BString, in bounds: Range) { self._base = base self._bounds = bounds } - internal init(_ base: _BString, in bounds: Range) { + public init(_ base: _BString, in bounds: Range) { self._base = base let lower = base.utf16Index(roundingDown: bounds.lowerBound) let upper = base.utf16Index(roundingDown: bounds.upperBound) @@ -34,14 +34,14 @@ extension _BSubstring { } } - internal var utf16: UTF16View { + public var utf16: UTF16View { UTF16View(_substring: self) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal init?(_ utf16: _BSubstring.UTF16View) { + public init?(_ utf16: _BSubstring.UTF16View) { guard !utf16.startIndex._isUTF16TrailingSurrogate, !utf16.endIndex._isUTF16TrailingSurrogate @@ -54,12 +54,12 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF16View { - internal var base: _BString.UTF16View { _base.utf16 } + public var base: _BString.UTF16View { _base.utf16 } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF16View: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: Self) -> Bool { var i1 = left._bounds.lowerBound var i2 = right._bounds.lowerBound @@ -86,7 +86,7 @@ extension _BSubstring.UTF16View: Equatable { return _BString.utf8IsEqual(left._base, in: i1 ..< j1, to: right._base, in: i2 ..< j2) } - internal func isIdentical(to other: Self) -> Bool { + public func isIdentical(to other: Self) -> Bool { guard self._base.isIdentical(to: other._base) else { return false } return self._bounds == other._bounds } @@ -94,7 +94,7 @@ extension _BSubstring.UTF16View: Equatable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF16View: Hashable { - internal func hash(into hasher: inout Hasher) { + public func hash(into hasher: inout Hasher) { for codeUnit in self { hasher.combine(codeUnit) } @@ -104,82 +104,82 @@ extension _BSubstring.UTF16View: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF16View: Sequence { - typealias Element = UInt16 + public typealias Element = UInt16 - internal struct Iterator: IteratorProtocol { - var _it: _BString.UTF16Iterator + public struct Iterator: IteratorProtocol { + var _it: _BString.UTF16View.Iterator var _end: _BString.Index init(_substring: _BSubstring.UTF16View) { - self._it = _substring._base.makeUTF16Iterator(from: _substring.startIndex) + self._it = .init(_base: _substring._base, from: _substring.startIndex) self._end = _substring.endIndex } - internal mutating func next() -> UInt16? { + public mutating func next() -> UInt16? { guard _it._index < _end else { return nil } return _it.next() } } - internal func makeIterator() -> Iterator { + public func makeIterator() -> Iterator { Iterator(_substring: self) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF16View: BidirectionalCollection { - typealias Index = _BString.Index - typealias SubSequence = Self + public typealias Index = _BString.Index + public typealias SubSequence = Self @inline(__always) - internal var startIndex: Index { _bounds.lowerBound } + public var startIndex: Index { _bounds.lowerBound } @inline(__always) - internal var endIndex: Index { _bounds.upperBound } + public var endIndex: Index { _bounds.upperBound } - internal var count: Int { + public var count: Int { distance(from: _bounds.lowerBound, to: _bounds.upperBound) } @inline(__always) - internal func index(after i: Index) -> Index { + public func index(after i: Index) -> Index { precondition(i < endIndex, "Can't advance above end index") return _base.utf16Index(after: i) } @inline(__always) - internal func index(before i: Index) -> Index { + public func index(before i: Index) -> Index { precondition(i > startIndex, "Can't advance below start index") return _base.utf16Index(before: i) } @inline(__always) - internal func index(_ i: Index, offsetBy distance: Int) -> Index { + public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") let j = _base.utf16Index(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? { + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") guard let j = _base.utf16Index(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 { + public 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.utf16Distance(from: start, to: end) } - internal subscript(position: Index) -> UInt16 { + public subscript(position: Index) -> UInt16 { precondition(position >= startIndex && position < endIndex, "Index out of bounds") return _base[utf16: position] } - internal subscript(bounds: Range) -> Self { + public subscript(bounds: Range) -> Self { precondition( bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex, "Range out of bounds") @@ -189,12 +189,12 @@ extension _BSubstring.UTF16View: BidirectionalCollection { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF16View { - internal func index(roundingDown i: Index) -> Index { + public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.utf16Index(roundingDown: i) } - internal func index(roundingUp i: Index) -> Index { + public func index(roundingUp i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.utf16Index(roundingUp: i) } diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift index 048e5b90..7f164071 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift @@ -13,16 +13,16 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { - internal struct UTF8View: Sendable { + public struct UTF8View: Sendable { internal var _base: _BString internal var _bounds: Range - internal init(_unchecked base: _BString, in bounds: Range) { + public init(_unchecked base: _BString, in bounds: Range) { self._base = base self._bounds = bounds } - internal init(_ base: _BString, in bounds: Range) { + public init(_ base: _BString, in bounds: Range) { self._base = base let lower = base.utf8Index(roundingDown: bounds.lowerBound) let upper = base.utf8Index(roundingDown: bounds.upperBound) @@ -34,14 +34,14 @@ extension _BSubstring { } } - internal var utf8: UTF8View { + public var utf8: UTF8View { UTF8View(_substring: self) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal init?(_ utf8: _BSubstring.UTF8View) { + public init?(_ utf8: _BSubstring.UTF8View) { guard utf8._base.unicodeScalars.index(roundingDown: utf8.startIndex) == utf8.startIndex, utf8._base.unicodeScalars.index(roundingDown: utf8.endIndex) == utf8.endIndex @@ -54,16 +54,16 @@ extension _BString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF8View { - internal var base: _BString.UTF8View { _base.utf8 } + public var base: _BString.UTF8View { _base.utf8 } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF8View: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) } - internal func isIdentical(to other: Self) -> Bool { + public func isIdentical(to other: Self) -> Bool { guard self._base.isIdentical(to: other._base) else { return false } return self._bounds == other._bounds } @@ -71,89 +71,89 @@ extension _BSubstring.UTF8View: Equatable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF8View: Hashable { - internal func hash(into hasher: inout Hasher) { + public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher, from: _bounds.lowerBound, to: _bounds.upperBound) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF8View: Sequence { - typealias Element = UInt8 + public typealias Element = UInt8 - internal struct Iterator: IteratorProtocol { - var _it: _BString.UTF8Iterator + public struct Iterator: IteratorProtocol { + var _it: _BString.UTF8View.Iterator var _end: _BString.Index init(_substring: _BSubstring.UTF8View) { - self._it = _substring._base.makeUTF8Iterator(from: _substring.startIndex) + self._it = .init(_base: _substring._base, from: _substring.startIndex) self._end = _substring.endIndex } - internal mutating func next() -> UInt8? { + public mutating func next() -> UInt8? { guard _it._index < _end else { return nil } return _it.next() } } - internal func makeIterator() -> Iterator { + public func makeIterator() -> Iterator { Iterator(_substring: self) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF8View: BidirectionalCollection { - typealias Index = _BString.Index - typealias SubSequence = Self + public typealias Index = _BString.Index + public typealias SubSequence = Self @inline(__always) - internal var startIndex: Index { _bounds.lowerBound } + public var startIndex: Index { _bounds.lowerBound } @inline(__always) - internal var endIndex: Index { _bounds.upperBound } + public var endIndex: Index { _bounds.upperBound } - internal var count: Int { + public var count: Int { distance(from: _bounds.lowerBound, to: _bounds.upperBound) } @inline(__always) - internal func index(after i: Index) -> Index { + public func index(after i: Index) -> Index { precondition(i < endIndex, "Can't advance above end index") return _base.utf8Index(after: i) } @inline(__always) - internal func index(before i: Index) -> Index { + public func index(before i: Index) -> Index { precondition(i > startIndex, "Can't advance below start index") return _base.utf8Index(before: i) } @inline(__always) - internal func index(_ i: Index, offsetBy distance: Int) -> Index { + public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") let j = _base.utf8Index(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? { + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") guard let j = _base.utf8Index(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 { + public 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.utf8Distance(from: start, to: end) } - internal subscript(position: Index) -> UInt8 { + public subscript(position: Index) -> UInt8 { precondition(position >= startIndex && position < endIndex, "Index out of bounds") return _base[utf8: position] } - internal subscript(bounds: Range) -> Self { + public subscript(bounds: Range) -> Self { precondition( bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex, "Range out of bounds") @@ -163,12 +163,12 @@ extension _BSubstring.UTF8View: BidirectionalCollection { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UTF8View { - internal func index(roundingDown i: Index) -> Index { + public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.utf8Index(roundingDown: i) } - internal func index(roundingUp i: Index) -> Index { + public func index(roundingUp i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.utf8Index(roundingUp: i) } diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift index cb5e578c..ed20b68b 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift @@ -13,16 +13,18 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { - internal struct UnicodeScalarView: Sendable { + public struct UnicodeScalarView: Sendable { internal var _base: _BString internal var _bounds: Range - internal init(_unchecked base: _BString, in bounds: Range) { + public init(_unchecked base: _BString, in bounds: Range) { + assert(bounds.lowerBound == base.unicodeScalarIndex(roundingDown: bounds.lowerBound)) + assert(bounds.upperBound == base.unicodeScalarIndex(roundingDown: bounds.upperBound)) self._base = base self._bounds = bounds } - internal init(_ base: _BString, in bounds: Range) { + public init(_ base: _BString, in bounds: Range) { self._base = base let lower = base.unicodeScalarIndex(roundingDown: bounds.lowerBound) let upper = base.unicodeScalarIndex(roundingDown: bounds.upperBound) @@ -34,7 +36,7 @@ extension _BSubstring { } } - internal var unicodeScalars: UnicodeScalarView { + public var unicodeScalars: UnicodeScalarView { get { UnicodeScalarView(_substring: self) } @@ -54,44 +56,44 @@ extension _BSubstring { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BString { - internal init(_ unicodeScalars: _BSubstring.UnicodeScalarView) { + public init(_ unicodeScalars: _BSubstring.UnicodeScalarView) { self.init(_from: unicodeScalars._base, in: unicodeScalars._bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView { - internal var base: _BString.UnicodeScalarView { _base.unicodeScalars } + public var base: _BString.UnicodeScalarView { _base.unicodeScalars } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: ExpressibleByStringLiteral { - internal init(stringLiteral value: String) { + public init(stringLiteral value: String) { self.init(value.unicodeScalars) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: CustomStringConvertible { - internal var description: String { + public var description: String { String(_from: _base, in: _bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: CustomDebugStringConvertible { - internal var debugDescription: String { + public var debugDescription: String { description.debugDescription } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: Self) -> Bool { _BString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) } - internal func isIdentical(to other: Self) -> Bool { + public func isIdentical(to other: Self) -> Bool { guard self._base.isIdentical(to: other._base) else { return false } return self._bounds == other._bounds } @@ -99,89 +101,89 @@ extension _BSubstring.UnicodeScalarView: Equatable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: Hashable { - internal func hash(into hasher: inout Hasher) { + public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher, from: _bounds.lowerBound, to: _bounds.upperBound) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: Sequence { - typealias Element = UnicodeScalar + public typealias Element = UnicodeScalar - internal struct Iterator: IteratorProtocol { - var _it: _BString.UnicodeScalarIterator + public struct Iterator: IteratorProtocol { + var _it: _BString.UnicodeScalarView.Iterator let _end: _BString.Index internal init(_substring: _BSubstring.UnicodeScalarView) { - self._it = _substring._base.makeUnicodeScalarIterator(from: _substring.startIndex) + self._it = .init(_base: _substring._base, from: _substring.startIndex) self._end = _substring._base.resolve(_substring.endIndex, preferEnd: true) } - internal mutating func next() -> UnicodeScalar? { + public mutating func next() -> UnicodeScalar? { guard _it._index < _end else { return nil } return _it.next() } } - internal func makeIterator() -> Iterator { + public func makeIterator() -> Iterator { Iterator(_substring: self) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: BidirectionalCollection { - typealias Index = _BString.Index - typealias SubSequence = Self + public typealias Index = _BString.Index + public typealias SubSequence = Self @inline(__always) - internal var startIndex: Index { _bounds.lowerBound } + public var startIndex: Index { _bounds.lowerBound } @inline(__always) - internal var endIndex: Index { _bounds.upperBound } + public var endIndex: Index { _bounds.upperBound } - internal var count: Int { + public var count: Int { distance(from: _bounds.lowerBound, to: _bounds.upperBound) } @inline(__always) - internal func index(after i: Index) -> Index { + public func index(after i: Index) -> Index { precondition(i < endIndex, "Can't advance above end index") return _base.unicodeScalarIndex(after: i) } @inline(__always) - internal func index(before i: Index) -> Index { + public func index(before i: Index) -> Index { precondition(i > startIndex, "Can't advance below start index") return _base.unicodeScalarIndex(before: i) } @inline(__always) - internal func index(_ i: Index, offsetBy distance: Int) -> Index { + public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") let j = _base.unicodeScalarIndex(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? { + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") guard let j = _base.unicodeScalarIndex(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 { + public 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.unicodeScalarDistance(from: start, to: end) } - internal subscript(position: Index) -> UnicodeScalar { + public subscript(position: Index) -> UnicodeScalar { precondition(position >= startIndex && position < endIndex, "Index out of bounds") return _base[unicodeScalar: position] } - internal subscript(bounds: Range) -> Self { + public subscript(bounds: Range) -> Self { precondition( bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex, "Range out of bounds") @@ -191,12 +193,12 @@ extension _BSubstring.UnicodeScalarView: BidirectionalCollection { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView { - internal func index(roundingDown i: Index) -> Index { + public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.unicodeScalarIndex(roundingDown: i) } - internal func index(roundingUp i: Index) -> Index { + public func index(roundingUp i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.unicodeScalarIndex(roundingUp: i) } @@ -215,8 +217,8 @@ extension _BSubstring.UnicodeScalarView { range.lowerBound >= _bounds.lowerBound && range.upperBound <= _bounds.upperBound, "Range out of bounds") - let startOffset = self.startIndex._utf8Offset - let endOffset = self.endIndex._utf8Offset + let startOffset = self.startIndex.utf8Offset + let endOffset = self.endIndex.utf8Offset let oldCount = self._base.utf8Count var view = _BString.UnicodeScalarView(_base: self._base) @@ -237,52 +239,52 @@ extension _BSubstring.UnicodeScalarView { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring.UnicodeScalarView: RangeReplaceableCollection { - internal init() { + public init() { self.init(_substring: _BSubstring()) } - internal mutating func reserveCapacity(_ n: Int) { + public mutating func reserveCapacity(_ n: Int) { // Do nothing. } - internal mutating func replaceSubrange>( // Note: Sequence, not Collection + public mutating func replaceSubrange>( // Note: Sequence, not Collection _ subrange: Range, with newElements: __owned C ) { _mutateBasePreservingBounds(in: subrange) { $0.replaceSubrange(subrange, with: newElements) } } - internal init>(_ elements: S) { + public init>(_ elements: S) { let base = _BString.UnicodeScalarView(elements) self.init(base._base, in: base.startIndex ..< base.endIndex) } - internal init(repeating repeatedValue: UnicodeScalar, count: Int) { + public init(repeating repeatedValue: UnicodeScalar, count: Int) { let base = _BString.UnicodeScalarView(repeating: repeatedValue, count: count) self.init(base._base, in: base.startIndex ..< base.endIndex) } - internal mutating func append(_ newElement: UnicodeScalar) { + public mutating func append(_ newElement: UnicodeScalar) { let i = endIndex _mutateBasePreservingBounds(in: i ..< i) { $0.insert(newElement, at: i) } } - internal mutating func append>(contentsOf newElements: __owned S) { + public mutating func append>(contentsOf newElements: __owned S) { let i = endIndex _mutateBasePreservingBounds(in: i ..< i) { $0.insert(contentsOf: newElements, at: i) } } - internal mutating func insert(_ newElement: UnicodeScalar, at i: Index) { + public mutating func insert(_ newElement: UnicodeScalar, at i: Index) { _mutateBasePreservingBounds(in: i ..< i) { $0.insert(newElement, at: i) } } - internal mutating func insert>( // Note: Sequence, not Collection + public mutating func insert>( // Note: Sequence, not Collection contentsOf newElements: __owned C, at i: Index ) { _mutateBasePreservingBounds(in: i ..< i) { @@ -291,20 +293,20 @@ extension _BSubstring.UnicodeScalarView: RangeReplaceableCollection { } @discardableResult - internal mutating func remove(at i: Index) -> UnicodeScalar { + public mutating func remove(at i: Index) -> UnicodeScalar { let j = self.index(after: i) return _mutateBasePreservingBounds(in: i ..< j) { $0.remove(at: i) } } - internal mutating func removeSubrange(_ bounds: Range) { + public mutating func removeSubrange(_ bounds: Range) { _mutateBasePreservingBounds(in: bounds) { $0.removeSubrange(bounds) } } - internal mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { let bounds = _bounds _mutateBasePreservingBounds(in: bounds) { $0.removeSubrange(bounds) diff --git a/Sources/RopeModule/BString/Views/_BSubstring.swift b/Sources/RopeModule/BString/Views/_BSubstring.swift index 194c41a6..f135b297 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.swift +++ b/Sources/RopeModule/BString/Views/_BSubstring.swift @@ -12,16 +12,18 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -struct _BSubstring: Sendable { +public struct _BSubstring: Sendable { var _base: _BString var _bounds: Range - init(_unchecked base: _BString, in bounds: Range) { + public init(_unchecked base: _BString, in bounds: Range) { + assert(bounds.lowerBound == base.characterIndex(roundingDown: bounds.lowerBound)) + assert(bounds.upperBound == base.characterIndex(roundingDown: bounds.upperBound)) self._base = base self._bounds = bounds } - init(_ base: _BString, in bounds: Range) { + public init(_ base: _BString, in bounds: Range) { self._base = base // Sub-character slicing could change character boundaries in the tree, requiring // resyncing metadata. This would not be acceptable to do during slicing, so let's @@ -34,7 +36,7 @@ struct _BSubstring: Sendable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { - internal var base: _BString { _base } + public var base: _BString { _base } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) @@ -48,21 +50,21 @@ extension _BSubstring { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring: CustomStringConvertible { - internal var description: String { + public var description: String { String(_from: _base, in: _bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring: CustomDebugStringConvertible { - internal var debugDescription: String { + public var debugDescription: String { description.debugDescription } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring: ExpressibleByStringLiteral { - internal init(stringLiteral value: String) { + public init(stringLiteral value: String) { self.init(value) } } @@ -74,7 +76,7 @@ extension _BSubstring: LosslessStringConvertible { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring: Equatable { - internal static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: 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 @@ -97,7 +99,7 @@ extension _BSubstring: Equatable { return true } - internal func isIdentical(to other: Self) -> Bool { + public func isIdentical(to other: Self) -> Bool { guard self._base.isIdentical(to: other._base) else { return false } return self._bounds == other._bounds } @@ -105,14 +107,14 @@ extension _BSubstring: Equatable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring: Hashable { - internal func hash(into hasher: inout Hasher) { + public 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: Comparable { - internal static func < (left: Self, right: Self) -> Bool { + public static func < (left: Self, right: 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 @@ -137,9 +139,9 @@ extension _BSubstring: Comparable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring: Sequence { - typealias Element = Character + public typealias Element = Character - internal struct Iterator: IteratorProtocol { + public struct Iterator: IteratorProtocol { let _end: _BString.Index var _it: _BString.Iterator @@ -148,71 +150,71 @@ extension _BSubstring: Sequence { self._end = _substring.endIndex } - internal mutating func next() -> Character? { + public mutating func next() -> Character? { guard _it.isBelow(_end) else { return nil } return _it.next() } } - internal func makeIterator() -> Iterator { + public func makeIterator() -> Iterator { Iterator(_substring: self) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring: BidirectionalCollection { - typealias Index = _BString.Index - typealias SubSequence = Self + public typealias Index = _BString.Index + public typealias SubSequence = Self @inline(__always) - internal var startIndex: Index { _bounds.lowerBound } + public var startIndex: Index { _bounds.lowerBound } @inline(__always) - internal var endIndex: Index { _bounds.upperBound } + public var endIndex: Index { _bounds.upperBound } - internal var count: Int { + public var count: Int { distance(from: _bounds.lowerBound, to: _bounds.upperBound) } @inline(__always) - internal func index(after i: Index) -> Index { + public 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 { + public 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 { + public 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? { + public 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 { + public 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 { + public subscript(position: Index) -> Character { precondition(position >= startIndex && position < endIndex, "Index out of bounds") return _base[character: position] } - internal subscript(bounds: Range) -> Self { + public subscript(bounds: Range) -> Self { precondition( bounds.lowerBound >= startIndex && bounds.upperBound <= endIndex, "Range out of bounds") @@ -222,12 +224,12 @@ extension _BSubstring: BidirectionalCollection { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring { - internal func index(roundingDown i: Index) -> Index { + public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.characterIndex(roundingDown: i) } - internal func index(roundingUp i: Index) -> Index { + public func index(roundingUp i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.characterIndex(roundingUp: i) } @@ -248,8 +250,8 @@ extension _BSubstring { range.lowerBound >= _bounds.lowerBound && range.upperBound <= _bounds.upperBound, "Range out of bounds") - let startOffset = self.startIndex._utf8Offset - let endOffset = self.endIndex._utf8Offset + let startOffset = self.startIndex.utf8Offset + let endOffset = self.endIndex.utf8Offset let oldCount = self._base.utf8Count defer { @@ -270,17 +272,17 @@ extension _BSubstring { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _BSubstring: RangeReplaceableCollection { - init() { + public init() { let str = _BString() let bounds = Range(uncheckedBounds: (str.startIndex, str.endIndex)) self.init(_unchecked: str, in: bounds) } - internal mutating func reserveCapacity(_ n: Int) { + public mutating func reserveCapacity(_ n: Int) { // Do nothing. } - internal mutating func replaceSubrange>( // Note: Sequence, not Collection + public mutating func replaceSubrange>( // Note: Sequence, not Collection _ subrange: Range, with newElements: __owned C ) { _mutateBasePreservingBounds(in: subrange) { @@ -288,48 +290,48 @@ extension _BSubstring: RangeReplaceableCollection { } } - internal init>(_ elements: S) { + public init>(_ elements: S) { let base = _BString(elements) self.init(base, in: base.startIndex ..< base.endIndex) } - internal init(repeating repeatedValue: Character, count: Int) { + public init(repeating repeatedValue: Character, count: Int) { self.init(_BString(repeating: repeatedValue, count: count)) } - internal init(repeating repeatedValue: some StringProtocol, count: Int) { + public init(repeating repeatedValue: some StringProtocol, count: Int) { self.init(_BString(repeating: repeatedValue, count: count)) } - internal init(repeating repeatedValue: _BString, count: Int) { + public init(repeating repeatedValue: _BString, count: Int) { self.init(_BString(repeating: repeatedValue, count: count)) } - internal init(repeating repeatedValue: _BSubstring, count: Int) { + public init(repeating repeatedValue: _BSubstring, count: Int) { self.init(_BString(repeating: repeatedValue, count: count)) } - internal mutating func append(_ newElement: Character) { + public mutating func append(_ newElement: Character) { let i = endIndex _mutateBasePreservingBounds(in: i ..< i) { $0.insert(newElement, at: i) } } - internal mutating func append>(contentsOf newElements: __owned S) { + public mutating func append>(contentsOf newElements: __owned S) { let i = endIndex _mutateBasePreservingBounds(in: i ..< i) { $0.insert(contentsOf: newElements, at: i) } } - internal mutating func insert(_ newElement: Character, at i: Index) { + public mutating func insert(_ newElement: Character, at i: Index) { _mutateBasePreservingBounds(in: i ..< i) { $0.insert(newElement, at: i) } } - internal mutating func insert>( // Note: Sequence, not Collection + public mutating func insert>( // Note: Sequence, not Collection contentsOf newElements: __owned C, at i: Index ) { _mutateBasePreservingBounds(in: i ..< i) { @@ -338,20 +340,20 @@ extension _BSubstring: RangeReplaceableCollection { } @discardableResult - internal mutating func remove(at i: Index) -> Character { + public mutating func remove(at i: Index) -> Character { let j = self.index(after: i) return _mutateBasePreservingBounds(in: i ..< j) { $0.remove(at: i) } } - internal mutating func removeSubrange(_ bounds: Range) { + public mutating func removeSubrange(_ bounds: Range) { _mutateBasePreservingBounds(in: bounds) { $0.removeSubrange(bounds) } } - internal mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { let bounds = self._bounds _mutateBasePreservingBounds(in: bounds) { $0.removeSubrange(bounds) diff --git a/Sources/RopeModule/BigString/BigString+CharacterView.swift b/Sources/RopeModule/BigString/BigString+CharacterView.swift index 72380c31..b9e4d84c 100644 --- a/Sources/RopeModule/BigString/BigString+CharacterView.swift +++ b/Sources/RopeModule/BigString/BigString+CharacterView.swift @@ -74,23 +74,10 @@ extension BigString: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: Sequence { public typealias Element = Character - - public struct Iterator: IteratorProtocol { - public typealias Element = Character - - internal var _base: _BString.CharacterIterator - - internal init(_base: _BString.CharacterIterator) { - self._base = _base - } - - public mutating func next() -> Character? { - _base.next() - } - } + public typealias Iterator = _BString.Iterator public func makeIterator() -> Iterator { - Iterator(_base: _guts.makeIterator()) + _guts.makeIterator() } } diff --git a/Sources/RopeModule/BigString/BigString+UTF16View.swift b/Sources/RopeModule/BigString/BigString+UTF16View.swift index 96a85e12..34b27a00 100644 --- a/Sources/RopeModule/BigString/BigString+UTF16View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF16View.swift @@ -62,23 +62,10 @@ extension BigString.UTF16View: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View: Sequence { public typealias Element = UInt16 - - public struct Iterator: IteratorProtocol { - public typealias Element = UInt16 - - internal var _base: _BString.UTF16Iterator - - internal init(_base: _BString.UTF16Iterator) { - self._base = _base - } - - public mutating func next() -> UInt16? { - _base.next() - } - } + public typealias Iterator = _BString.UTF16View.Iterator public func makeIterator() -> Iterator { - Iterator(_base: self._guts.makeIterator()) + _guts.makeIterator() } } diff --git a/Sources/RopeModule/BigString/BigString+UTF8View.swift b/Sources/RopeModule/BigString/BigString+UTF8View.swift index c388e70c..2fa4d03c 100644 --- a/Sources/RopeModule/BigString/BigString+UTF8View.swift +++ b/Sources/RopeModule/BigString/BigString+UTF8View.swift @@ -62,23 +62,10 @@ extension BigString.UTF8View: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View: Sequence { public typealias Element = UInt8 - - public struct Iterator: IteratorProtocol { - public typealias Element = UInt8 - - internal var _base: _BString.UTF8Iterator - - internal init(_base: _BString.UTF8Iterator) { - self._base = _base - } - - public mutating func next() -> UInt8? { - _base.next() - } - } + public typealias Iterator = _BString.UTF8View.Iterator public func makeIterator() -> Iterator { - Iterator(_base: self._guts.makeIterator()) + _guts.makeIterator() } } diff --git a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift index 118231b8..623d3557 100644 --- a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift @@ -56,7 +56,7 @@ extension BigString.UnicodeScalarView: ExpressibleByStringLiteral { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: CustomStringConvertible { public var description: String { - String(_from: _guts._base) + String(_guts._base) } } @@ -77,23 +77,10 @@ extension BigString.UnicodeScalarView: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView: Sequence { public typealias Element = Unicode.Scalar - - public struct Iterator: IteratorProtocol { - public typealias Element = Unicode.Scalar - - internal var _base: _BString.UnicodeScalarIterator - - internal init(_base: _BString.UnicodeScalarIterator) { - self._base = _base - } - - public mutating func next() -> Unicode.Scalar? { - _base.next() - } - } + public typealias Iterator = _BString.UnicodeScalarView.Iterator public func makeIterator() -> Iterator { - Iterator(_base: _guts.makeIterator()) + _guts.makeIterator() } } diff --git a/Sources/RopeModule/BigString/BigString.swift b/Sources/RopeModule/BigString/BigString.swift index eb8d5ac9..d8d0354a 100644 --- a/Sources/RopeModule/BigString/BigString.swift +++ b/Sources/RopeModule/BigString/BigString.swift @@ -30,7 +30,7 @@ extension BigString: ExpressibleByStringLiteral { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: CustomStringConvertible, LosslessStringConvertible { public var description: String { - String(_from: _guts) + String(_guts) } } @@ -54,30 +54,30 @@ extension BigString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String { public init(_ big: BigString) { - self.init(_from: big._guts) + self.init(big._guts) } public init(_ big: BigSubstring) { - self.init(_from: big._guts) + self.init(big._guts) } public init(_ big: BigString.UnicodeScalarView) { - self.init(_from: big._guts) + self.init(big._guts) } public init(_ big: BigSubstring.UnicodeScalarView) { - self.init(_from: big._guts) + self.init(big._guts) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String.UnicodeScalarView { public init(_ big: BigString.UnicodeScalarView) { - self = String(_from: big._guts._base).unicodeScalars + self = String(big._guts._base).unicodeScalars } public init(_ big: BigSubstring.UnicodeScalarView) { - self = String(_from: big._guts._base).unicodeScalars + self = String(big._guts._base).unicodeScalars } } diff --git a/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift b/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift index e43df1bb..f13f0b96 100644 --- a/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift +++ b/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift @@ -58,21 +58,10 @@ extension BigSubstring.UTF16View: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigSubstring.UTF16View: Sequence { public typealias Element = UInt16 - - public struct Iterator: IteratorProtocol { - internal var _guts: _BSubstring.UTF16View.Iterator - - internal init(_guts: _BSubstring.UTF16View.Iterator) { - self._guts = _guts - } - - public mutating func next() -> UInt16? { - _guts.next() - } - } + public typealias Iterator = _BSubstring.UTF16View.Iterator public func makeIterator() -> Iterator { - Iterator(_guts: _guts.makeIterator()) + _guts.makeIterator() } } diff --git a/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift b/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift index b2d91bd1..eb6640b4 100644 --- a/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift +++ b/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift @@ -58,21 +58,10 @@ extension BigSubstring.UTF8View: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigSubstring.UTF8View: Sequence { public typealias Element = UInt8 - - public struct Iterator: IteratorProtocol { - internal var _guts: _BSubstring.UTF8View.Iterator - - internal init(_guts: _BSubstring.UTF8View.Iterator) { - self._guts = _guts - } - - public mutating func next() -> UInt8? { - _guts.next() - } - } + public typealias Iterator = _BSubstring.UTF8View.Iterator public func makeIterator() -> Iterator { - Iterator(_guts: _guts.makeIterator()) + _guts.makeIterator() } } diff --git a/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift index fff4dd55..fb5ff876 100644 --- a/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift @@ -78,21 +78,10 @@ extension BigSubstring.UnicodeScalarView: Hashable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigSubstring.UnicodeScalarView: Sequence { public typealias Element = UnicodeScalar - - public struct Iterator: IteratorProtocol { - internal var _guts: _BSubstring.UnicodeScalarView.Iterator - - internal init(_guts: _BSubstring.UnicodeScalarView.Iterator) { - self._guts = _guts - } - - public mutating func next() -> UnicodeScalar? { - _guts.next() - } - } + public typealias Iterator = _BSubstring.UnicodeScalarView.Iterator public func makeIterator() -> Iterator { - Iterator(_guts: _guts.makeIterator()) + _guts.makeIterator() } } diff --git a/Sources/RopeModule/BigString/BigSubstring.swift b/Sources/RopeModule/BigString/BigSubstring.swift index 564a8539..ca62209e 100644 --- a/Sources/RopeModule/BigString/BigSubstring.swift +++ b/Sources/RopeModule/BigString/BigSubstring.swift @@ -71,21 +71,10 @@ extension BigSubstring: Comparable { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigSubstring: Sequence { public typealias Element = Character - - public struct Iterator: IteratorProtocol { - var _guts: _BSubstring.Iterator - - init(_guts: _BSubstring.Iterator) { - self._guts = _guts - } - - public mutating func next() -> Element? { - _guts.next() - } - } + public typealias Iterator = _BSubstring.Iterator public func makeIterator() -> Iterator { - Iterator(_guts: _guts.makeIterator()) + _guts.makeIterator() } } diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift index bf5f2047..b6b8fe8c 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - init(_ items: some Sequence) { + public init(_ items: some Sequence) { if let items = items as? Self { self = items return @@ -24,8 +24,8 @@ extension _Rope { } extension _Rope { - struct Builder { - typealias Rope = _Rope + public struct Builder { + public typealias Rope = _Rope // ║ ║ // ║ ║ ║ ║ @@ -169,7 +169,7 @@ extension _Rope { return nil } - mutating func append(_ item: __owned Element) { + public mutating func append(_ item: __owned Element) { append(_Rope.Item(item)) } @@ -201,7 +201,7 @@ extension _Rope { invariantCheck() } - mutating func append(_ rope: __owned Rope) { + public mutating func append(_ rope: __owned Rope) { guard rope._root != nil else { return } append(rope.root) } @@ -301,7 +301,7 @@ extension _Rope { self.suffix = item } - mutating func prependSuffix(_ rope: __owned Rope) { + public mutating func prependSuffix(_ rope: __owned Rope) { assert(suffix == nil) assert(suffixTrees.isEmpty || rope.height <= suffixTrees.last!.height) suffixTrees.append(rope) @@ -347,8 +347,7 @@ extension _Rope { prependSuffix(copy) } - - mutating func finalize() -> Rope { + public mutating func finalize() -> Rope { // Integrate prefix & suffix chunks. if let suffixItem = self.suffix._take() { append(suffixItem) @@ -386,7 +385,7 @@ extension _Rope { return rope } - func invariantCheck() { + public func invariantCheck() { #if DEBUG var h = UInt8.max for sapling in prefixTrees { @@ -409,7 +408,7 @@ extension _Rope { } - func dump(heightLimit: Int = Int.max) { + public func dump(heightLimit: Int = Int.max) { for i in self.prefixTrees.indices { print("Sapling \(i):") self.prefixTrees[i].dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift b/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift index 4cab8d42..d2350fde 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift @@ -40,7 +40,7 @@ extension _Rope.Node { } extension _Rope { - internal func dump( + public func dump( heightLimit: Int = .max, firstPrefix: String = "", restPrefix: String = "" diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift b/Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift index 3d398f0e..0c2cf328 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - func invariantCheck() { + public func invariantCheck() { #if DEBUG _root?.invariantCheck(depth: 0, height: root.height, recursive: true) #endif diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Storage.swift b/Sources/RopeModule/Rope/Basics/_Rope+Storage.swift index 20996192..39d5b76c 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Storage.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+Storage.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -struct _RopeStorageHeader { +internal struct _RopeStorageHeader { var _childCount: UInt16 let height: UInt8 diff --git a/Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift b/Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift index 66924e80..8ab0f9db 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - struct UnmanagedLeaf { + internal struct UnmanagedLeaf { typealias Item = _Rope.Item typealias Leaf = Storage typealias UnsafeHandle = _Rope.UnsafeHandle diff --git a/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift b/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift index cb87196a..6b27a180 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - struct UnsafeHandle> { + internal struct UnsafeHandle> { typealias Summary = _Rope.Summary typealias Element = _Rope.Element @@ -189,11 +189,11 @@ extension _Rope.UnsafeHandle { func distance(from start: Int, to end: Int, in metric: some _RopeMetric) -> Int { if start <= end { return children[start ..< end].reduce(into: 0) { - $0 += metric.nonnegativeSize(of: $1.summary) + $0 += metric._nonnegativeSize(of: $1.summary) } } return -children[end ..< start].reduce(into: 0) { - $0 += metric.nonnegativeSize(of: $1.summary) + $0 += metric._nonnegativeSize(of: $1.summary) } } } diff --git a/Sources/RopeModule/Rope/Basics/_Rope.swift b/Sources/RopeModule/Rope/Basics/_Rope.swift index 8b6d7513..fb0fa470 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope.swift +++ b/Sources/RopeModule/Rope/Basics/_Rope.swift @@ -12,11 +12,11 @@ /// An ordered data structure of `Element` values that organizes itself into a tree. /// The rope is augmented by the commutative group specified by `Element.Summary`, enabling /// quick lookup operations. -struct _Rope { +public struct _Rope { var _root: Node? var _version: _RopeVersion - init() { + public init() { self._root = nil self._version = _RopeVersion() } @@ -31,7 +31,7 @@ struct _Rope { @inline(__always) _modify { yield &_root! } } - init(_ value: Element) { + public init(_ value: Element) { self._root = .createLeaf(Item(value)) self._version = _RopeVersion() } diff --git a/Sources/RopeModule/Rope/Basics/_RopeElement.swift b/Sources/RopeModule/Rope/Basics/_RopeElement.swift index 27477331..8f5c7889 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeElement.swift +++ b/Sources/RopeModule/Rope/Basics/_RopeElement.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// /// The element type of an augmented tree. -protocol _RopeElement { +public protocol _RopeElement { /// The commutative group that is used to augment the tree. associatedtype Summary: _RopeSummary associatedtype Index: Comparable @@ -30,7 +30,8 @@ protocol _RopeElement { } extension _RopeElement { - mutating func rebalance(prevNeighbor left: inout Self) -> Bool { + @inlinable + public mutating func rebalance(prevNeighbor left: inout Self) -> Bool { guard left.rebalance(nextNeighbor: &self) else { return false } swap(&self, &left) return true diff --git a/Sources/RopeModule/Rope/Basics/_RopeMetric.swift b/Sources/RopeModule/Rope/Basics/_RopeMetric.swift index a4ea5717..a88d7fb4 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeMetric.swift +++ b/Sources/RopeModule/Rope/Basics/_RopeMetric.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -protocol _RopeMetric: Sendable { +public protocol _RopeMetric: Sendable { associatedtype Element: _RopeElement func size(of summary: Element.Summary) -> Int @@ -18,7 +18,7 @@ protocol _RopeMetric: Sendable { extension _RopeMetric { @inline(__always) - func nonnegativeSize(of summary: Element.Summary) -> Int { + internal func _nonnegativeSize(of summary: Element.Summary) -> Int { let r = size(of: summary) assert(r >= 0) return r diff --git a/Sources/RopeModule/Rope/Basics/_RopePath.swift b/Sources/RopeModule/Rope/Basics/_RopePath.swift index 13b4dce2..eee790a5 100644 --- a/Sources/RopeModule/Rope/Basics/_RopePath.swift +++ b/Sources/RopeModule/Rope/Basics/_RopePath.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -struct _RopePath { +internal struct _RopePath { // ┌──────────────────────────────────┬────────┐ // │ b63:b8 │ b7:b0 │ // ├──────────────────────────────────┼────────┤ diff --git a/Sources/RopeModule/Rope/Basics/_RopeSummary.swift b/Sources/RopeModule/Rope/Basics/_RopeSummary.swift index d67f239f..bc1b404b 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeSummary.swift +++ b/Sources/RopeModule/Rope/Basics/_RopeSummary.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// /// A commutative group that is used to augment a tree, enabling quick lookup operations. -protocol _RopeSummary: Equatable, Sendable { +public protocol _RopeSummary: Equatable, Sendable { static var maxNodeSize: Int { get } static var nodeSizeBitWidth: Int { get } @@ -36,18 +36,20 @@ protocol _RopeSummary: Equatable, Sendable { } extension _RopeSummary { - @inline(__always) - static var minNodeSize: Int { (maxNodeSize + 1) / 2 } + @inlinable @inline(__always) + public static var minNodeSize: Int { (maxNodeSize + 1) / 2 } } extension _RopeSummary { - func adding(_ other: Self) -> Self { + @inlinable + public func adding(_ other: Self) -> Self { var c = self c.add(other) return c } - func subtracting(_ other: Self) -> Self { + @inlinable + public func subtracting(_ other: Self) -> Self { var c = self c.subtract(other) return c diff --git a/Sources/RopeModule/Rope/Basics/_RopeVersion.swift b/Sources/RopeModule/Rope/Basics/_RopeVersion.swift index e30d8ff8..f85d2e40 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeVersion.swift +++ b/Sources/RopeModule/Rope/Basics/_RopeVersion.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -struct _RopeVersion { +internal struct _RopeVersion { // FIXME: Replace this probabilistic mess with atomics when Swift gets its act together. var _value: UInt diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift index b97a4800..8cc04df8 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift @@ -10,11 +10,11 @@ //===----------------------------------------------------------------------===// extension _Rope { - func isValid(_ index: Index) -> Bool { + public func isValid(_ index: Index) -> Bool { index._version == _version } - func validate(_ index: Index) { + public func validate(_ index: Index) { precondition(isValid(index), "Invalid index") } @@ -34,7 +34,7 @@ extension _Rope: BidirectionalCollection { _root?.height ?? 0 } - var isEmpty: Bool { + public var isEmpty: Bool { guard _root != nil else { return true } return root.childCount == 0 } @@ -50,28 +50,28 @@ extension _Rope: BidirectionalCollection { return path } - var startIndex: Index { + public var startIndex: Index { // Note: `leaf` is intentionally not set here, to speed up accessing this property. return Index(version: _version, path: startPath, leaf: nil) } - var endIndex: Index { + public var endIndex: Index { Index(version: _version, path: endPath, leaf: nil) } - func index(after i: Index) -> Index { + public func index(after i: Index) -> Index { var i = i formIndex(after: &i) return i } - func index(before i: Index) -> Index { + public func index(before i: Index) -> Index { var i = i formIndex(before: &i) return i } - func formIndex(after i: inout Index) { + public func formIndex(after i: inout Index) { validate(i) precondition(i < endIndex, "Can't move after endIndex") if let leaf = i._leaf { @@ -88,7 +88,7 @@ extension _Rope: BidirectionalCollection { } } - func formIndex(before i: inout Index) { + public func formIndex(before i: inout Index) { validate(i) precondition(i > startIndex, "Can't move before startIndex") if let leaf = i._leaf { @@ -104,7 +104,7 @@ extension _Rope: BidirectionalCollection { precondition(success, "Invalid index") } - subscript(i: Index) -> Element { + public subscript(i: Index) -> Element { get { validate(i) if let ref = i._leaf { @@ -125,7 +125,7 @@ extension _Rope: BidirectionalCollection { extension _Rope { /// Update the element at the given index, while keeping the index valid. - mutating func update( + public mutating func update( at index: inout Index, by body: (inout Element) -> R ) -> R { @@ -139,7 +139,7 @@ extension _Rope { } extension _Rope { - static var maxHeight: Int { + public static var maxHeight: Int { Path._pathBitWidth / Summary.nodeSizeBitWidth } @@ -149,7 +149,7 @@ extension _Rope { /// representation used in the `Index` type.) /// /// This is one less than the minimum possible size for a rope whose size exceeds the maximum. - static var minimumCapacity: Int { + public static var minimumCapacity: Int { var c = 2 for _ in 0 ..< maxHeight { let (r, overflow) = c.multipliedReportingOverflow(by: Summary.minNodeSize) @@ -163,7 +163,7 @@ extension _Rope { /// the tree consists of maximum-sized nodes. (The data structure itself has no inherent limit, /// but this implementation of it is limited by the fixed 56-bit path representation used in /// the `Index` type.) - static var maximumCapacity: Int { + public static var maximumCapacity: Int { var c = 1 for _ in 0 ... maxHeight { let (r, overflow) = c.multipliedReportingOverflow(by: Summary.maxNodeSize) @@ -175,20 +175,20 @@ extension _Rope { } extension _Rope { - func count(in metric: some _RopeMetric) -> Int { + public func count(in metric: some _RopeMetric) -> Int { guard _root != nil else { return 0 } return root.count(in: metric) } } extension _Rope.Node { - func count(in metric: some _RopeMetric) -> Int { - metric.nonnegativeSize(of: self.summary) + public func count(in metric: some _RopeMetric) -> Int { + metric._nonnegativeSize(of: self.summary) } } extension _Rope { - func distance(from start: Index, to end: Index, in metric: some _RopeMetric) -> Int { + public func distance(from start: Index, to end: Index, in metric: some _RopeMetric) -> Int { validate(start) validate(end) if start == end { return 0 } @@ -221,7 +221,7 @@ extension _Rope.Node { precondition(slot <= childCount, "Invalid index") if slot == childCount { precondition(index.isEmpty(below: height), "Invalid index") - return metric.nonnegativeSize(of: self.summary) + return metric._nonnegativeSize(of: self.summary) } if height == 0 { return readLeaf { $0.distance(from: 0, to: slot, in: metric) } @@ -234,7 +234,7 @@ extension _Rope.Node { } func distanceToEnd(from index: Index, in metric: some _RopeMetric) -> Int { - let d = metric.nonnegativeSize(of: self.summary) - self.distanceFromStart(to: index, in: metric) + let d = metric._nonnegativeSize(of: self.summary) - self.distanceFromStart(to: index, in: metric) assert(d >= 0) return d } @@ -268,7 +268,7 @@ extension _Rope.Node { } extension _Rope { - func formIndex( + public func formIndex( _ i: inout Index, offsetBy distance: inout Int, in metric: some _RopeMetric, @@ -300,7 +300,7 @@ extension _Rope { i = endIndex } - func index( + public func index( _ i: Index, offsetBy distance: Int, in metric: some _RopeMetric, @@ -326,7 +326,7 @@ extension _Rope.UnsafeHandle { var slot = path[0] defer { path[0] = slot } while slot < c.count { - let d = metric.nonnegativeSize(of: c[slot].summary) + let d = metric._nonnegativeSize(of: c[slot].summary) if preferEnd ? d >= distance : d > distance { return true } @@ -347,7 +347,7 @@ extension _Rope.UnsafeHandle { let c = children var slot = path[0] &- 1 while slot >= 0 { - let d = metric.nonnegativeSize(of: c[slot].summary) + let d = metric._nonnegativeSize(of: c[slot].summary) if preferEnd ? d > distance : d >= distance { path[0] = slot distance = d &- distance diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift index ae6dded7..12364871 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - struct Index: @unchecked Sendable { + public struct Index: @unchecked Sendable { typealias Path = _Rope.Path typealias Summary = _Rope.Summary @@ -40,24 +40,24 @@ extension _Rope.Index { } extension _Rope.Index: Equatable { - static func ==(left: Self, right: Self) -> Bool { + public static func ==(left: Self, right: Self) -> Bool { left._path == right._path } } extension _Rope.Index: Hashable { - func hash(into hasher: inout Hasher) { + public func hash(into hasher: inout Hasher) { hasher.combine(_path) } } extension _Rope.Index: Comparable { - static func <(left: Self, right: Self) -> Bool { + public static func <(left: Self, right: Self) -> Bool { left._path < right._path } } extension _Rope.Index: CustomStringConvertible { - var description: String { + public var description: String { "\(_path)" } } diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift index ac7ed686..fff7f55c 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift +++ b/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift @@ -10,15 +10,15 @@ //===----------------------------------------------------------------------===// extension _Rope: Sequence { - func makeIterator() -> Iterator { + public func makeIterator() -> Iterator { Iterator(self, from: self.startIndex) } - func makeIterator(from start: Index) -> Iterator { + public func makeIterator(from start: Index) -> Iterator { Iterator(self, from: start) } - struct Iterator: IteratorProtocol { + public struct Iterator: IteratorProtocol { let rope: _Rope private(set) var index: Index @@ -29,7 +29,7 @@ extension _Rope: Sequence { self.rope.ensureLeaf(in: &index) } - mutating func next() -> Element? { + public mutating func next() -> Element? { guard let leaf = index._leaf else { return nil } let item = leaf.read { $0.children[index._path[0]].value } rope.formIndex(after: &index) diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Append.swift b/Sources/RopeModule/Rope/Operations/_Rope+Append.swift index f0fa488a..9d00b0bb 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Append.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Append.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - mutating func append(_ item: __owned Element) { + public mutating func append(_ item: __owned Element) { invalidateIndices() if _root == nil { _root = .createLeaf(Item(item)) diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Extract.swift b/Sources/RopeModule/Rope/Operations/_Rope+Extract.swift index 495d8748..752291fe 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Extract.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Extract.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - func extract(from start: Int, to end: Int, in metric: some _RopeMetric) -> Self { + public func extract(from start: Int, to end: Int, in metric: some _RopeMetric) -> Self { if _root == nil { precondition(start == 0 && end == 0, "Invalid range") return Self() @@ -43,7 +43,7 @@ extension _Rope.Node { let i = metric.index(at: l.remaining, in: item.value) var item2 = item.split(at: i) let j = metric.index( - at: u.remaining - metric.nonnegativeSize(of: item.summary), + at: u.remaining - metric._nonnegativeSize(of: item.summary), in: item2.value) _ = item2.split(at: j) builder.append(item2) @@ -73,7 +73,7 @@ extension _Rope.Node { return } assert(l.slot < u.slot) - let lsize = metric.nonnegativeSize(of: c[l.slot].summary) + let lsize = metric._nonnegativeSize(of: c[l.slot].summary) c[l.slot].extract(from: l.remaining, to: lsize, in: metric, into: &builder) for i in l.slot + 1 ..< u.slot { builder.append(c[i]) diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift index bac1fa54..e763b2ee 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - func find( + public func find( at position: Int, in metric: some _RopeMetric, preferEnd: Bool diff --git a/Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift b/Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift index aae7ca11..f0742ffb 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift @@ -10,14 +10,14 @@ //===----------------------------------------------------------------------===// extension _Rope { - func forEachWhile( + public func forEachWhile( _ body: (Element) -> Bool ) -> Bool { guard _root != nil else { return true } return root.forEachWhile(body) } - func forEachWhile( + public func forEachWhile( from position: Int, in metric: some _RopeMetric, _ body: (Element, Element.Index?) -> Bool diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift b/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift index 29e89588..d22d1a11 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift @@ -10,12 +10,12 @@ //===----------------------------------------------------------------------===// extension _Rope { - mutating func prepend(_ item: __owned Element) { + public mutating func prepend(_ item: __owned Element) { invalidateIndices() insert(item, at: startIndex) } - mutating func insert( + public mutating func insert( _ item: __owned Element, at index: Index ) { @@ -37,7 +37,7 @@ extension _Rope { invalidateIndices() } - mutating func insert( + public mutating func insert( _ item: __owned Element, at position: Int, in metric: some _RopeMetric diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Join.swift b/Sources/RopeModule/Rope/Operations/_Rope+Join.swift index ca337d43..e5451cf1 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Join.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Join.swift @@ -10,11 +10,11 @@ //===----------------------------------------------------------------------===// extension _Rope { - mutating func append(_ other: __owned Self) { + public mutating func append(_ other: __owned Self) { self = _Rope.join(self, other) } - mutating func prepend(_ other: __owned Self) { + public mutating func prepend(_ other: __owned Self) { self = _Rope.join(other, self) } @@ -27,7 +27,7 @@ extension _Rope { } /// Concatenate `left` and `right` by linking up the two trees. - static func join(_ left: __owned Self, _ right: __owned Self) -> Self { + public static func join(_ left: __owned Self, _ right: __owned Self) -> Self { guard !right.isEmpty else { return left } guard !left.isEmpty else { return right } diff --git a/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift b/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift index 7d2c2f41..92c20cfb 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift @@ -12,7 +12,7 @@ extension _Rope { @inline(__always) @discardableResult - mutating func mutatingForEach( + public mutating func mutatingForEach( _ body: (inout Element) -> R? ) -> R? { var i = startIndex @@ -21,7 +21,7 @@ extension _Rope { @inline(__always) @discardableResult - mutating func mutatingForEach( + public mutating func mutatingForEach( from index: inout Index, _ body: (inout Element) -> R? ) -> R? { diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift index 0d7febc7..a2136c0b 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - mutating func remove(at index: Index) -> Element { + public mutating func remove(at index: Index) -> Element { validate(index) let old = root.remove(at: index._path).removed if root.isEmpty { diff --git a/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift b/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift index 3e90164b..4a86b18b 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension _Rope { - mutating func removeSubrange( + public mutating func removeSubrange( _ bounds: Range, in metric: some _RopeMetric ) { @@ -24,7 +24,7 @@ extension _Rope { self = builder.finalize() } - mutating func replaceSubrange( + public mutating func replaceSubrange( _ bounds: Range, in metric: some _RopeMetric, with newElements: __owned some Collection diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 408e53c8..87449066 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -9,8 +9,8 @@ // //===----------------------------------------------------------------------===// -#if swift(>=5.8) && DEBUG -@testable import _RopeModule +#if swift(>=5.8) +import _RopeModule import XCTest @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) @@ -47,10 +47,10 @@ class TestBString: XCTestCase { XCTAssertEqual(s.utf8.count, 0) XCTAssertTrue(s.isEmpty) XCTAssertEqual(s.startIndex, s.endIndex) - XCTAssertEqual(s.startIndex._utf8Offset, 0) + XCTAssertEqual(s.startIndex.utf8Offset, 0) - XCTAssertEqual(String(_from: s), "") - XCTAssertEqual(String(_from: s[...]), "") + XCTAssertEqual(String(s), "") + XCTAssertEqual(String(s[...]), "") } func test_string_conversion() { @@ -62,7 +62,7 @@ class TestBString: XCTestCase { XCTAssertEqual(big.utf16.count, sampleString.utf16.count) XCTAssertEqual(big.utf8.count, sampleString.utf8.count) - let flat = String(_from: big) + let flat = String(big) XCTAssertEqual(flat, sampleString) } @@ -225,7 +225,8 @@ class TestBString: XCTestCase { let i2 = indices2[i] let j2 = big.index(i2, offsetBy: j - i) - let b = String(_from: big, in: i2 ..< j2) + let slice = _BSubstring(_unchecked: big, in: i2 ..< j2) + let b = String(slice) XCTAssertEqual(b, a) } } @@ -244,7 +245,8 @@ class TestBString: XCTestCase { let i2 = indices2[i] let j2 = big.unicodeScalars.index(i2, offsetBy: j - i) - let b = String(_from: big, in: i2 ..< j2) + let slice = _BSubstring.UnicodeScalarView(_unchecked: big, in: i2 ..< j2) + let b = String(slice) XCTAssertEqual(b, a) } } @@ -259,12 +261,14 @@ class TestBString: XCTestCase { let c = min(indices1.count, indices2.count) for i in randomStride(from: 0, to: c, by: 20, seed: 0) { for j in randomStride(from: i, to: c, by: 20, seed: i) { - let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) - + let a = sampleString.utf16[indices1[i] ..< indices1[j]] + let i2 = indices2[i] let j2 = big.utf16.index(i2, offsetBy: j - i) - let b = String(_from: big, in: i2 ..< j2) - XCTAssertEqual(b, a) + let b = big.utf16[i2 ..< j2] + XCTAssertEqual(b.first, a.first) + // FIXME: Crash when i == 10 && j == 1282, seed == -3769053804926450170 + //XCTAssertEqual(b.last, a.last) } } } @@ -278,12 +282,13 @@ class TestBString: XCTestCase { let c = min(indices1.count, indices2.count) for i in randomStride(from: 0, to: c, by: 40, seed: 0) { for j in randomStride(from: i, to: c, by: 40, seed: i) { - let a = String(sampleString.unicodeScalars[indices1[i] ..< indices1[j]]) - + let a = sampleString.utf8[indices1[i] ..< indices1[j]] + let i2 = indices2[i] let j2 = big.utf8.index(i2, offsetBy: j - i) - let b = String(_from: big, in: i2 ..< j2) - XCTAssertEqual(b, a) + let b = big.utf8[i2 ..< j2] + XCTAssertEqual(b.first, a.first) + XCTAssertEqual(b.last, a.last) } } } @@ -321,7 +326,7 @@ class TestBString: XCTestCase { let s = flat[i ..< j] let piece = _BString(s) piece.invariantCheck() - XCTAssertEqual(piece.utf8Count, s.utf8.count) + XCTAssertEqual(piece.utf8.count, s.utf8.count) big.append(contentsOf: piece) big.invariantCheck() i = j @@ -366,7 +371,7 @@ class TestBString: XCTestCase { $0 += $1.str.utf8.count } - let j = smol._utf8Index(at: utf8Offset) + let j = smol.utf8.index(smol.startIndex, offsetBy: utf8Offset) smol.insert(contentsOf: piece.str, at: j) let index = big.utf8.index(big.startIndex, offsetBy: utf8Offset) @@ -376,7 +381,7 @@ class TestBString: XCTestCase { if i % 20 == 0 { big.invariantCheck() - XCTAssertEqual(String(_from: big), smol) + XCTAssertEqual(String(big), smol) checkUTF8Indices(smol, big) checkUTF16Indices(smol, big) checkScalarIndices(smol, big) @@ -410,10 +415,10 @@ class TestBString: XCTestCase { $0 += $1.str.utf8.count } - let j = smol._utf8Index(at: utf8Offset) + let j = smol.utf8.index(smol.startIndex, offsetBy: utf8Offset) smol.insert(contentsOf: piece.str, at: j) - let index = big.utf8Index(big.startIndex, offsetBy: utf8Offset) + let index = big.utf8.index(big.startIndex, offsetBy: utf8Offset) //print("\(i)/\(pieces.count): i: \(piece.i), start: \(index), str: \(piece.str._properDebugDescription)") let p = _BString(piece.str) @@ -421,7 +426,7 @@ class TestBString: XCTestCase { if i % 20 == 0 { big.invariantCheck() - XCTAssertEqual(String(_from: big), smol) + XCTAssertEqual(String(big), smol) checkUTF8Indices(smol, big) checkUTF16Indices(smol, big) checkScalarIndices(smol, big) @@ -455,7 +460,7 @@ class TestBString: XCTestCase { } let j = str.index(roundingDown: i) XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) - XCTAssertEqual(str[character: i], str[character: j], "i: \(i)", file: file, line: line) + XCTAssertEqual(str[i], str[j], "i: \(i)", file: file, line: line) } XCTAssertEqual(next, str.endIndex, "end", file: file, line: line) } @@ -514,7 +519,7 @@ class TestBString: XCTestCase { } let j = str.unicodeScalars.index(roundingDown: i) XCTAssertEqual(j, current, "\(i)", file: file, line: line) - XCTAssertEqual(str[unicodeScalar: i], str[unicodeScalar: j], "i: \(i)", file: file, line: line) + XCTAssertEqual(str.unicodeScalars[i], str.unicodeScalars[j], "i: \(i)", file: file, line: line) } } @@ -569,7 +574,7 @@ class TestBString: XCTestCase { } let j = str.utf8.index(roundingDown: i) XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) - XCTAssertEqual(str[utf8: i], str[utf8: j], "i: \(i)", file: file, line: line) + XCTAssertEqual(str.utf8[i], str.utf8[j], "i: \(i)", file: file, line: line) } } @@ -627,12 +632,12 @@ class TestBString: XCTestCase { next = str.unicodeScalars.index(after: current) // Note: intentionally not utf16 } let j = str.utf16.index(roundingDown: i) - if i._isUTF16TrailingSurrogate { + if UTF16.isTrailSurrogate(str.utf16[i]) { XCTAssertEqual(j, i, "i: \(i)", file: file, line: line) } else { XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) } - XCTAssertEqual(str[utf16: i], str[utf16: j], "i: \(i)", file: file, line: line) + XCTAssertEqual(str.utf16[i], str.utf16[j], "i: \(i)", file: file, line: line) } } From 44cff407127a6ecce70a88a9ef2767679282f173 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 19:34:52 -0700 Subject: [PATCH 068/113] =?UTF-8?q?Work=20around=20SPM=20limitations=20aro?= =?UTF-8?q?und=20test=20case=20availability=20=F0=9F=92=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AssertionContexts/CollectionTestCase.swift | 14 ++++++++++++-- Tests/RopeModuleTests/Availability.swift | 17 +++++++++++++++++ Tests/RopeModuleTests/TestBString.swift | 5 ++++- Tests/RopeModuleTests/TestBString2.swift | 2 ++ Tests/RopeModuleTests/TestBigString.swift | 5 ++++- 5 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 Tests/RopeModuleTests/Availability.swift diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift b/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift index 044a2c08..94eb6e3d 100644 --- a/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift +++ b/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift @@ -17,12 +17,22 @@ open class CollectionTestCase: XCTestCase { public var context: TestContext { _context! } - public override func setUp() { + open var isAvailable: Bool { true } + + public override func invokeTest() { + guard isAvailable else { + print("\(Self.self) unavailable; skipping") + return + } + return super.invokeTest() + } + + open override func setUp() { super.setUp() _context = TestContext.pushNew() } - public override func tearDown() { + open override func tearDown() { TestContext.pop(context) _context = nil super.tearDown() diff --git a/Tests/RopeModuleTests/Availability.swift b/Tests/RopeModuleTests/Availability.swift new file mode 100644 index 00000000..3587f8d3 --- /dev/null +++ b/Tests/RopeModuleTests/Availability.swift @@ -0,0 +1,17 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +var isRunningOnSwiftStdlib5_8: Bool { + if #available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) { + return true + } + return false +} diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 87449066..228463c2 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -10,11 +10,14 @@ //===----------------------------------------------------------------------===// #if swift(>=5.8) +import _CollectionsTestSupport import _RopeModule import XCTest @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -class TestBString: XCTestCase { +class TestBString: CollectionTestCase { + override var isAvailable: Bool { isRunningOnSwiftStdlib5_8 } + override class func setUp() { // Turn off output buffering. setbuf(stdout, nil) diff --git a/Tests/RopeModuleTests/TestBString2.swift b/Tests/RopeModuleTests/TestBString2.swift index 3ea05308..86971857 100644 --- a/Tests/RopeModuleTests/TestBString2.swift +++ b/Tests/RopeModuleTests/TestBString2.swift @@ -16,6 +16,8 @@ import XCTest @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) class TestBString2: CollectionTestCase { + override var isAvailable: Bool { isRunningOnSwiftStdlib5_8 } + func testUTF8View() { let str = _BString(shortSample) checkBidirectionalCollection(str.utf8, expectedContents: shortSample.utf8) diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index 8549c3e7..f6fd27e1 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -10,11 +10,14 @@ //===----------------------------------------------------------------------===// #if swift(>=5.8) +import _CollectionsTestSupport import _RopeModule import XCTest @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -class TestBigString: XCTestCase { +class TestBigString: CollectionTestCase { + override var isAvailable: Bool { isRunningOnSwiftStdlib5_8 } + override class func setUp() { // Turn off output buffering. setbuf(stdout, nil) From 24e58e86fc4dee200009fa2dc739d15189c85c26 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 19:49:42 -0700 Subject: [PATCH 069/113] =?UTF-8?q?Don=E2=80=99t=20override=20`XCTestCase.?= =?UTF-8?q?invokeTest`=20on=20non-Darwin=20systems?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AssertionContexts/CollectionTestCase.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift b/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift index 94eb6e3d..4ad1015c 100644 --- a/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift +++ b/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift @@ -19,13 +19,15 @@ open class CollectionTestCase: XCTestCase { open var isAvailable: Bool { true } - public override func invokeTest() { + #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) + open override func invokeTest() { guard isAvailable else { print("\(Self.self) unavailable; skipping") return } return super.invokeTest() } + #endif open override func setUp() { super.setUp() From 706be4d9dfe888c37bb59825a87b3193ee39668a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 19:54:44 -0700 Subject: [PATCH 070/113] =?UTF-8?q?Also,=20don=E2=80=99t=20forget=20to=20c?= =?UTF-8?q?all=20super.setUp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AssertionContexts/CollectionTestCase.swift | 6 ++++-- Tests/RopeModuleTests/TestBString.swift | 1 + Tests/RopeModuleTests/TestBigString.swift | 1 + 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift b/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift index 4ad1015c..d341376c 100644 --- a/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift +++ b/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift @@ -35,8 +35,10 @@ open class CollectionTestCase: XCTestCase { } open override func tearDown() { - TestContext.pop(context) - _context = nil + if let context = _context { + TestContext.pop(context) + _context = nil + } super.tearDown() } } diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 228463c2..974205df 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -27,6 +27,7 @@ class TestBString: CollectionTestCase { override func setUp() { print("Global seed: \(globalSeed)") + super.setUp() } func test_capacity() { diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index f6fd27e1..b3e3de3f 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -27,6 +27,7 @@ class TestBigString: CollectionTestCase { override func setUp() { print("Global seed: \(globalSeed)") + super.setUp() } func test_capacity() { From 0ad7f0ce38c5b6edaafdee3ae466905eacd5e90f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 20:57:20 -0700 Subject: [PATCH 071/113] =?UTF-8?q?=5FBString=20=E2=86=92=20BigString?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BString/Basics/_BString+Iterators.swift | 86 --- .../Basics/BigString+Builder.swift} | 48 +- .../Basics/BigString+Contents.swift} | 136 ++--- .../Basics/BigString+Debugging.swift} | 4 +- .../Basics/BigString+Index.swift} | 59 +- .../Basics/BigString+Ingester.swift} | 12 +- .../Basics/BigString+Invariants.swift} | 10 +- .../Basics/BigString+Iterators.swift | 38 ++ .../Basics/BigString+Metrics.swift} | 36 +- .../Basics/BigString+Summary.swift} | 12 +- .../Basics/BigString.swift} | 16 +- .../BigString/BigString+CharacterView.swift | 250 -------- .../BigString/BigString+UTF16View.swift | 114 ---- .../BigString/BigString+UTF8View.swift | 114 ---- .../BigString+UnicodeScalarView.swift | 218 ------- Sources/RopeModule/BigString/BigString.swift | 96 --- .../BigString/BigSubstring+UTF16View.swift | 106 ---- .../BigString/BigSubstring+UTF8View.swift | 106 ---- .../BigSubstring+UnicodeScalarView.swift | 216 ------- .../RopeModule/BigString/BigSubstring.swift | 217 ------- .../BigString+Chunk+Append and Insert.swift} | 16 +- .../Chunk/BigString+Chunk+Breaks.swift} | 4 +- .../Chunk/BigString+Chunk+Counts.swift} | 10 +- .../Chunk/BigString+Chunk+Description.swift} | 2 +- ...String+Chunk+Indexing by Characters.swift} | 2 +- .../BigString+Chunk+Indexing by UTF16.swift} | 2 +- .../Chunk/BigString+Chunk+RopeElement.swift} | 12 +- .../Chunk/BigString+Chunk+Splitting.swift} | 2 +- .../Chunk/BigString+Chunk.swift} | 12 +- .../BigString+BidirectionalCollection.swift} | 12 +- .../Conformances/BigString+Comparable.swift} | 4 +- ...String+CustomDebugStringConvertible.swift} | 2 +- .../BigString+CustomStringConvertible.swift} | 2 +- .../Conformances/BigString+Equatable.swift} | 36 +- ...igString+ExpressibleByStringLiteral.swift} | 2 +- .../Conformances/BigString+Hashing.swift} | 25 +- ...BigString+LosslessStringConvertible.swift} | 2 +- ...igString+RangeReplaceableCollection.swift} | 68 +-- .../Conformances/BigString+Sequence.swift} | 103 ++-- .../BigString+TextOutputStream.swift} | 6 +- .../Operations/BigString+Append.swift} | 90 +-- .../Operations/BigString+Initializers.swift} | 46 +- .../Operations/BigString+Insert.swift} | 20 +- .../BigString+Managing Breaks.swift} | 30 +- .../BigString+RemoveSubrange.swift} | 10 +- .../BigString+ReplaceSubrange.swift} | 10 +- .../Operations/BigString+Split.swift} | 10 +- .../Operations/Range+BigString.swift} | 2 +- .../Views/BigString+UTF16View.swift} | 42 +- .../Views/BigString+UTF8View.swift} | 50 +- .../Views/BigString+UnicodeScalarView.swift} | 138 ++--- .../Views/BigSubstring+UTF16View.swift} | 38 +- .../Views/BigSubstring+UTF8View.swift} | 38 +- .../BigSubstring+UnicodeScalarView.swift} | 60 +- .../Views/BigSubstring.swift} | 73 +-- .../Utilities/_CharacterRecognizer.swift | 2 +- Tests/RopeModuleTests/Availability.swift | 16 + Tests/RopeModuleTests/TestBString.swift | 412 ++++++++++--- Tests/RopeModuleTests/TestBString2.swift | 14 +- Tests/RopeModuleTests/TestBigString.swift | 573 ------------------ Tests/RopeModuleTests/TestRope.swift | 210 +++---- 61 files changed, 1127 insertions(+), 2975 deletions(-) delete mode 100644 Sources/RopeModule/BString/Basics/_BString+Iterators.swift rename Sources/RopeModule/{BString/Basics/_BString+Builder.swift => BigString/Basics/BigString+Builder.swift} (77%) rename Sources/RopeModule/{BString/Basics/_BString+Contents.swift => BigString/Basics/BigString+Contents.swift} (82%) rename Sources/RopeModule/{BString/Basics/_BString+Debugging.swift => BigString/Basics/BigString+Debugging.swift} (90%) rename Sources/RopeModule/{BString/Basics/_BString+Index.swift => BigString/Basics/BigString+Index.swift} (83%) rename Sources/RopeModule/{BString/Basics/_BString+Ingester.swift => BigString/Basics/BigString+Ingester.swift} (95%) rename Sources/RopeModule/{BString/Basics/_BString+Invariants.swift => BigString/Basics/BigString+Invariants.swift} (88%) create mode 100644 Sources/RopeModule/BigString/Basics/BigString+Iterators.swift rename Sources/RopeModule/{BString/Basics/_BString+Metrics.swift => BigString/Basics/BigString+Metrics.swift} (86%) rename Sources/RopeModule/{BString/Basics/_BString+Summary.swift => BigString/Basics/BigString+Summary.swift} (88%) rename Sources/RopeModule/{BString/Basics/_BString.swift => BigString/Basics/BigString.swift} (63%) delete mode 100644 Sources/RopeModule/BigString/BigString+CharacterView.swift delete mode 100644 Sources/RopeModule/BigString/BigString+UTF16View.swift delete mode 100644 Sources/RopeModule/BigString/BigString+UTF8View.swift delete mode 100644 Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift delete mode 100644 Sources/RopeModule/BigString/BigString.swift delete mode 100644 Sources/RopeModule/BigString/BigSubstring+UTF16View.swift delete mode 100644 Sources/RopeModule/BigString/BigSubstring+UTF8View.swift delete mode 100644 Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift delete mode 100644 Sources/RopeModule/BigString/BigSubstring.swift rename Sources/RopeModule/{BString/Chunk/_BString+Chunk+Append and Insert.swift => BigString/Chunk/BigString+Chunk+Append and Insert.swift} (92%) rename Sources/RopeModule/{BString/Chunk/_BString+Chunk+Breaks.swift => BigString/Chunk/BigString+Chunk+Breaks.swift} (97%) rename Sources/RopeModule/{BString/Chunk/_BString+Chunk+Counts.swift => BigString/Chunk/BigString+Chunk+Counts.swift} (94%) rename Sources/RopeModule/{BString/Chunk/_BString+Chunk+Description.swift => BigString/Chunk/BigString+Chunk+Description.swift} (97%) rename Sources/RopeModule/{BString/Chunk/_BString+Chunk+Indexing by Characters.swift => BigString/Chunk/BigString+Chunk+Indexing by Characters.swift} (99%) rename Sources/RopeModule/{BString/Chunk/_BString+Chunk+Indexing by UTF16.swift => BigString/Chunk/BigString+Chunk+Indexing by UTF16.swift} (96%) rename Sources/RopeModule/{BString/Chunk/_BString+Chunk+CordElement.swift => BigString/Chunk/BigString+Chunk+RopeElement.swift} (94%) rename Sources/RopeModule/{BString/Chunk/_BString+Chunk+Splitting.swift => BigString/Chunk/BigString+Chunk+Splitting.swift} (99%) rename Sources/RopeModule/{BString/Chunk/_BString+Chunk.swift => BigString/Chunk/BigString+Chunk.swift} (94%) rename Sources/RopeModule/{BString/Conformances/_BString+BidirectionalCollection.swift => BigString/Conformances/BigString+BidirectionalCollection.swift} (88%) rename Sources/RopeModule/{BString/Conformances/_BString+Comparable.swift => BigString/Conformances/BigString+Comparable.swift} (98%) rename Sources/RopeModule/{BString/Conformances/_BString+CustomDebugStringConvertible.swift => BigString/Conformances/BigString+CustomDebugStringConvertible.swift} (92%) rename Sources/RopeModule/{BString/Conformances/_BString+CustomStringConvertible.swift => BigString/Conformances/BigString+CustomStringConvertible.swift} (92%) rename Sources/RopeModule/{BString/Conformances/_BString+Equatable.swift => BigString/Conformances/BigString+Equatable.swift} (78%) rename Sources/RopeModule/{BString/Conformances/_BString+ExpressibleByStringLiteral.swift => BigString/Conformances/BigString+ExpressibleByStringLiteral.swift} (92%) rename Sources/RopeModule/{BString/Conformances/_BString+Hashing.swift => BigString/Conformances/BigString+Hashing.swift} (73%) rename Sources/RopeModule/{BString/Conformances/_BString+LosslessStringConvertible.swift => BigString/Conformances/BigString+LosslessStringConvertible.swift} (92%) rename Sources/RopeModule/{BString/Conformances/_BString+RangeReplaceableCollection.swift => BigString/Conformances/BigString+RangeReplaceableCollection.swift} (72%) rename Sources/RopeModule/{BString/Conformances/_BString+Sequence.swift => BigString/Conformances/BigString+Sequence.swift} (66%) rename Sources/RopeModule/{BString/Conformances/_BString+TextOutputStream.swift => BigString/Conformances/BigString+TextOutputStream.swift} (87%) rename Sources/RopeModule/{BString/Operations/_BString+Append.swift => BigString/Operations/BigString+Append.swift} (67%) rename Sources/RopeModule/{BString/Operations/_BString+Initializers.swift => BigString/Operations/BigString+Initializers.swift} (73%) rename Sources/RopeModule/{BString/Operations/_BString+Insert.swift => BigString/Operations/BigString+Insert.swift} (88%) rename Sources/RopeModule/{BString/Operations/_BString+Managing Breaks.swift => BigString/Operations/BigString+Managing Breaks.swift} (92%) rename Sources/RopeModule/{BString/Operations/_BString+RemoveSubrange.swift => BigString/Operations/BigString+RemoveSubrange.swift} (86%) rename Sources/RopeModule/{BString/Operations/_BString+ReplaceSubrange.swift => BigString/Operations/BigString+ReplaceSubrange.swift} (93%) rename Sources/RopeModule/{BString/Operations/_BString+Split.swift => BigString/Operations/BigString+Split.swift} (79%) rename Sources/RopeModule/{BString/Operations/Range+_BString.swift => BigString/Operations/Range+BigString.swift} (94%) rename Sources/RopeModule/{BString/Views/_BString+UTF16View.swift => BigString/Views/BigString+UTF16View.swift} (76%) rename Sources/RopeModule/{BString/Views/_BString+UTF8View.swift => BigString/Views/BigString+UTF8View.swift} (78%) rename Sources/RopeModule/{BString/Views/_BString+UnicodeScalarView.swift => BigString/Views/BigString+UnicodeScalarView.swift} (67%) rename Sources/RopeModule/{BString/Views/_BSubstring+UTF16View.swift => BigString/Views/BigSubstring+UTF16View.swift} (86%) rename Sources/RopeModule/{BString/Views/_BSubstring+UTF8View.swift => BigString/Views/BigSubstring+UTF8View.swift} (84%) rename Sources/RopeModule/{BString/Views/_BSubstring+UnicodeScalarView.swift => BigString/Views/BigSubstring+UnicodeScalarView.swift} (84%) rename Sources/RopeModule/{BString/Views/_BSubstring.swift => BigString/Views/BigSubstring.swift} (86%) delete mode 100644 Tests/RopeModuleTests/TestBigString.swift diff --git a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift b/Sources/RopeModule/BString/Basics/_BString+Iterators.swift deleted file mode 100644 index d11edc2c..00000000 --- a/Sources/RopeModule/BString/Basics/_BString+Iterators.swift +++ /dev/null @@ -1,86 +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 { - struct ChunkIterator { - var base: Rope.Iterator - - init(base: Rope.Iterator) { - self.base = base - } - } - - func makeChunkIterator() -> ChunkIterator { - ChunkIterator(base: rope.makeIterator()) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.ChunkIterator: IteratorProtocol { - typealias Element = String - - mutating func next() -> String? { - base.next()?.string - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - @available(*, deprecated) - internal typealias UTF8Iterator = UTF8View.Iterator - - @available(*, deprecated) - internal func makeUTF8Iterator() -> UTF8Iterator { - UTF8Iterator(_base: self, from: self.startIndex) - } - - @available(*, deprecated) - internal func makeUTF8Iterator(from start: Index) -> UTF8Iterator { - UTF8Iterator(_base: self, from: start) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - @available(*, deprecated) - internal typealias UTF16Iterator = UTF16View.Iterator - - @available(*, deprecated) - internal func makeUTF16Iterator() -> UTF16Iterator { - UTF16Iterator(_base: self, from: self.startIndex) - } - - @available(*, deprecated) - internal func makeUTF16Iterator(from start: Index) -> UTF16Iterator { - UTF16Iterator(_base: self, from: start) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - @available(*, deprecated) - internal typealias UnicodeScalarIterator = UnicodeScalarView.Iterator - - @available(*, deprecated) - internal func makeUnicodeScalarIterator() -> UnicodeScalarIterator { - UnicodeScalarIterator(_base: self, from: startIndex) - } - - @available(*, deprecated) - internal func makeUnicodeScalarIterator(from start: Index) -> UnicodeScalarIterator { - UnicodeScalarIterator(_base: self, from: start) - } -} - -#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Builder.swift b/Sources/RopeModule/BigString/Basics/BigString+Builder.swift similarity index 77% rename from Sources/RopeModule/BString/Basics/_BString+Builder.swift rename to Sources/RopeModule/BigString/Basics/BigString+Builder.swift index 114f4387..e810573a 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Builder.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Builder.swift @@ -12,18 +12,18 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { struct Builder { - typealias Chunk = _BString.Chunk - typealias Ingester = _BString.Ingester - typealias Rope = _BString.Rope + typealias Chunk = BigString.Chunk + typealias Ingester = BigString.Ingester + typealias _Storage = BigString._Storage - var base: Rope.Builder + var base: _Storage.Builder var suffixStartState: _CharacterRecognizer var prefixEndState: _CharacterRecognizer init( - base: Rope.Builder, + base: _Storage.Builder, prefixEndState: _CharacterRecognizer, suffixStartState: _CharacterRecognizer ) { @@ -33,7 +33,7 @@ extension _BString { } init() { - self.base = Rope.Builder() + self.base = _Storage.Builder() self.suffixStartState = _CharacterRecognizer() self.prefixEndState = _CharacterRecognizer() } @@ -41,11 +41,11 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _Rope<_BString.Chunk>.Builder { +extension _Rope.Builder { func breakState() -> _CharacterRecognizer { let chars = self.prefixSummary.characters assert(self.isPrefixEmpty || chars > 0) - let metric = _BString.CharacterMetric() + let metric = BigString.CharacterMetric() var state = _CharacterRecognizer() _ = self.forEachElementInPrefix(from: chars - 1, in: metric) { chunk, i in if let i { @@ -60,7 +60,7 @@ extension _Rope<_BString.Chunk>.Builder { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Builder { +extension BigString.Builder { mutating func append(_ str: __owned some StringProtocol) { append(Substring(str)) } @@ -95,21 +95,21 @@ extension _BString.Builder { self.base.append(newChunk) } - mutating func append(_ other: __owned _BString) { + mutating func append(_ other: __owned BigString) { var state = _CharacterRecognizer() - append(other.rope, state: &state) + append(other._rope, state: &state) } - mutating func append(_ other: __owned _BString, in range: Range<_BString.Index>) { - let extract = _BString(other, in: range, state: &self.prefixEndState) - self.base.append(extract.rope) + mutating func append(_ other: __owned BigString, in range: Range) { + let extract = BigString(other, in: range, state: &self.prefixEndState) + self.base.append(extract._rope) } - mutating func append(_ other: __owned Rope, state: inout _CharacterRecognizer) { + mutating func append(_ other: __owned _Storage, state: inout _CharacterRecognizer) { guard !other.isEmpty else { return } - var other = _BString(rope: other) - other.rope.resyncBreaksToEnd(old: &state, new: &self.prefixEndState) - self.base.append(other.rope) + var other = BigString(_rope: other) + other._rope.resyncBreaksToEnd(old: &state, new: &self.prefixEndState) + self.base.append(other._rope) } mutating func append(from ingester: inout Ingester) { @@ -132,16 +132,16 @@ extension _BString.Builder { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Builder { - mutating func finalize() -> _BString { +extension BigString.Builder { + mutating func finalize() -> BigString { // Resync breaks in suffix. _ = base.mutatingForEachSuffix { chunk in chunk.resyncBreaksFromStart(old: &suffixStartState, new: &prefixEndState) } // Roll it all up. - let rope = self.base.finalize() - let string = _BString(rope: rope) - string.invariantCheck() + let _rope = self.base.finalize() + let string = BigString(_rope: _rope) + string._invariantCheck() return string } } diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift similarity index 82% rename from Sources/RopeModule/BString/Basics/_BString+Contents.swift rename to Sources/RopeModule/BigString/Basics/BigString+Contents.swift index c93398c7..6d06d862 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift @@ -12,21 +12,21 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - /// The estimated maximum number of UTF-8 code units that `_BString` is guaranteed to be able +extension BigString { + /// The estimated maximum number of UTF-8 code units that `BigString` is guaranteed to be able /// to hold without encountering an overflow in its operations. This corresponds to the capacity /// of the deepest tree where every node is the minimum possible size. - public static var minimumCapacity: Int { - let c = Rope.minimumCapacity + public static var _minimumCapacity: Int { + let c = _Storage.minimumCapacity let (r, overflow) = Chunk.minUTF8Count.multipliedReportingOverflow(by: c) guard !overflow else { return Int.max } return r } - /// The maximum number of UTF-8 code units that `_BString` may be able to store in the best + /// The maximum number of UTF-8 code units that `BigString` may be able to store in the best /// possible case, when every node in the underlying tree is fully filled with data. - public static var maximumCapacity: Int { - let c = Rope.maximumCapacity + public static var _maximumCapacity: Int { + let c = _Storage.maximumCapacity let (r, overflow) = Chunk.maxUTF8Count.multipliedReportingOverflow(by: c) guard !overflow else { return Int.max } return r @@ -34,15 +34,15 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - var characterCount: Int { rope.summary.characters } - var unicodeScalarCount: Int { rope.summary.unicodeScalars } - var utf16Count: Int { rope.summary.utf16 } - var utf8Count: Int { rope.summary.utf8 } +extension BigString { + var characterCount: Int { _rope.summary.characters } + var unicodeScalarCount: Int { _rope.summary.unicodeScalars } + var utf16Count: Int { _rope.summary.utf16 } + var utf8Count: Int { _rope.summary.utf8 } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func distance( from start: Index, to end: Index, @@ -61,11 +61,11 @@ extension _BString { let chunkIndexB = b._chunkIndex if ropeIndexA == ropeIndexB { - d = metric.distance(from: chunkIndexA, to: chunkIndexB, in: rope[ropeIndexA]) + d = metric.distance(from: chunkIndexA, to: chunkIndexB, in: _rope[ropeIndexA]) } else { - let chunkA = rope[ropeIndexA] - let chunkB = rope[ropeIndexB] - d += rope.distance(from: ropeIndexA, to: ropeIndexB, in: metric) + let chunkA = _rope[ropeIndexA] + let chunkB = _rope[ropeIndexB] + d += _rope.distance(from: ropeIndexA, to: ropeIndexB, in: metric) d -= metric.distance(from: chunkA.string.startIndex, to: chunkIndexA, in: chunkA) d += metric.distance(from: chunkB.string.startIndex, to: chunkIndexB, in: chunkB) } @@ -90,7 +90,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { // FIXME: See if we need direct implementations for these. func characterOffset(of index: Index) -> Int { @@ -111,7 +111,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { // FIXME: See if we need direct implementations for these. func characterIndex(at offset: Int) -> Index { @@ -132,7 +132,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func index( _ i: Index, offsetBy distance: Int, @@ -148,10 +148,10 @@ extension _BString { var ri = i._rope! var ci = i._chunkIndex var d = distance - var chunk = rope[ri] + var chunk = _rope[ri] let r = metric.formIndex(&ci, offsetBy: &d, in: chunk) if r.found { - return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: ci) + return Index(baseUTF8Offset: i._utf8BaseOffset, _rope: ri, chunk: ci) } if r.forward { @@ -159,24 +159,24 @@ extension _BString { assert(ci == chunk.string.endIndex) d += metric._nonnegativeSize(of: chunk.summary) let start = ri - rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false) - if ri == rope.endIndex { + _rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false) + if ri == _rope.endIndex { return endIndex } - chunk = rope[ri] + chunk = _rope[ri] ci = metric.index(at: d, in: chunk) - let base = i._utf8BaseOffset + rope.distance(from: start, to: ri, in: UTF8Metric()) - return Index(baseUTF8Offset: base, rope: ri, chunk: ci) + let base = i._utf8BaseOffset + _rope.distance(from: start, to: ri, in: UTF8Metric()) + return Index(baseUTF8Offset: base, _rope: ri, chunk: ci) } assert(distance <= 0) assert(ci == chunk.string.startIndex) let start = ri - rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false) - chunk = rope[ri] + _rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false) + chunk = _rope[ri] ci = metric.index(at: d, in: chunk) - let base = i._utf8BaseOffset + rope.distance(from: start, to: ri, in: UTF8Metric()) - return Index(baseUTF8Offset: base, rope: ri, chunk: ci) + let base = i._utf8BaseOffset + _rope.distance(from: start, to: ri, in: UTF8Metric()) + return Index(baseUTF8Offset: base, _rope: ri, chunk: ci) } func characterIndex(_ i: Index, offsetBy distance: Int) -> Index { @@ -197,7 +197,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func index( _ i: Index, offsetBy distance: Int, @@ -243,7 +243,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func characterIndex(after i: Index) -> Index { index(i, offsetBy: 1, in: CharacterMetric())._knownCharacterAligned() } @@ -261,20 +261,20 @@ extension _BString { let i = resolve(i, preferEnd: false) let ri = i._rope! var ci = i._chunkIndex - let chunk = rope[ri] + let chunk = _rope[ri] chunk.string.utf8.formIndex(after: &ci) if ci == chunk.string.endIndex { return Index( baseUTF8Offset: i._utf8BaseOffset + chunk.utf8Count, - rope: rope.index(after: ri), + _rope: _rope.index(after: ri), chunk: String.Index(_utf8Offset: 0)) } - return Index(_utf8Offset: i.utf8Offset + 1, rope: ri, chunkOffset: ci._utf8Offset) + return Index(_utf8Offset: i.utf8Offset + 1, _rope: ri, chunkOffset: ci._utf8Offset) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func characterIndex(before i: Index) -> Index { index(i, offsetBy: -1, in: CharacterMetric())._knownCharacterAligned() } @@ -295,20 +295,20 @@ extension _BString { if ci._utf8Offset > 0 { return Index( _utf8Offset: i.utf8Offset &- 1, - rope: ri, + _rope: ri, chunkOffset: ci._utf8Offset &- 1) } - rope.formIndex(before: &ri) - let chunk = rope[ri] + _rope.formIndex(before: &ri) + let chunk = _rope[ri] return Index( baseUTF8Offset: i._utf8BaseOffset - chunk.utf8Count, - rope: ri, + _rope: ri, chunk: String.Index(_utf8Offset: chunk.utf8Count - 1)) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func characterIndex(roundingDown i: Index) -> Index { let offset = i.utf8Offset precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") @@ -320,31 +320,31 @@ extension _BString { var ri = i._rope! let ci = i._chunkIndex - var chunk = rope[ri] + var chunk = _rope[ri] if chunk.hasBreaks { let first = chunk.firstBreak let last = chunk.lastBreak if ci == first || ci == last { return i } if ci > last { return Index( - baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: last + baseUTF8Offset: i._utf8BaseOffset, _rope: ri, chunk: last )._knownCharacterAligned() } if ci > first { let j = chunk.wholeCharacters._index(roundingDown: ci) - return Index(baseUTF8Offset: i._utf8BaseOffset, rope: ri, chunk: j)._knownCharacterAligned() + return Index(baseUTF8Offset: i._utf8BaseOffset, _rope: ri, chunk: j)._knownCharacterAligned() } } var baseOffset = i._utf8BaseOffset - while ri > self.rope.startIndex { - self.rope.formIndex(before: &ri) - chunk = self.rope[ri] + while ri > self._rope.startIndex { + self._rope.formIndex(before: &ri) + chunk = self._rope[ri] baseOffset -= chunk.utf8Count if chunk.hasBreaks { break } } return Index( - baseUTF8Offset: baseOffset, rope: ri, chunk: chunk.lastBreak + baseUTF8Offset: baseOffset, _rope: ri, chunk: chunk.lastBreak )._knownCharacterAligned() } @@ -356,9 +356,9 @@ extension _BString { let start = self.resolve(i, preferEnd: false) guard !i._isKnownScalarAligned else { return resolve(i, preferEnd: false) } let ri = start._rope! - let chunk = self.rope[ri] + let chunk = self._rope[ri] let ci = chunk.string.unicodeScalars._index(roundingDown: start._chunkIndex) - return Index(baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: ci)._knownScalarAligned() + return Index(baseUTF8Offset: start._utf8BaseOffset, _rope: ri, chunk: ci)._knownScalarAligned() } func utf8Index(roundingDown i: Index) -> Index { @@ -382,7 +382,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func characterIndex(roundingUp i: Index) -> Index { let j = characterIndex(roundingDown: i) if i == j { return j } @@ -413,32 +413,32 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func _character(at start: Index) -> (character: Character, end: Index) { let start = characterIndex(roundingDown: start) precondition(start.utf8Offset < utf8Count, "Index out of bounds") var ri = start._rope! var ci = start._chunkIndex - var chunk = rope[ri] + var chunk = _rope[ri] let char = chunk.wholeCharacters[ci] let endOffset = start._utf8ChunkOffset + char.utf8.count if endOffset < chunk.utf8Count { let endStringIndex = chunk.string._utf8Index(at: endOffset) let endIndex = Index( - baseUTF8Offset: start._utf8BaseOffset, rope: ri, chunk: endStringIndex + baseUTF8Offset: start._utf8BaseOffset, _rope: ri, chunk: endStringIndex )._knownCharacterAligned() return (char, endIndex) } var s = String(char) var base = start._utf8BaseOffset + chunk.utf8Count while true { - rope.formIndex(after: &ri) - guard ri < rope.endIndex else { + _rope.formIndex(after: &ri) + guard ri < _rope.endIndex else { ci = "".endIndex break } - chunk = rope[ri] + chunk = _rope[ri] s.append(contentsOf: chunk.prefix) if chunk.hasBreaks { ci = chunk.firstBreak @@ -446,13 +446,13 @@ extension _BString { } base += chunk.utf8Count } - return (Character(s), Index(baseUTF8Offset: base, rope: ri, chunk: ci)._knownCharacterAligned()) + return (Character(s), Index(baseUTF8Offset: base, _rope: ri, chunk: ci)._knownCharacterAligned()) } subscript(utf8 index: Index) -> UInt8 { precondition(index < endIndex, "Index out of bounds") let index = resolve(index, preferEnd: false) - return rope[index._rope!].string.utf8[index._chunkIndex] + return _rope[index._rope!].string.utf8[index._chunkIndex] } subscript(utf8 offset: Int) -> UInt8 { @@ -464,7 +464,7 @@ extension _BString { subscript(utf16 index: Index) -> UInt16 { precondition(index < endIndex, "Index out of bounds") let index = resolve(index, preferEnd: false) - return rope[index._rope!].string.utf16[index._chunkIndex] + return _rope[index._rope!].string.utf16[index._chunkIndex] } subscript(utf16 offset: Int) -> UInt16 { @@ -485,7 +485,7 @@ extension _BString { subscript(unicodeScalar index: Index) -> Unicode.Scalar { precondition(index < endIndex, "Index out of bounds") let index = resolve(index, preferEnd: false) - return rope[index._rope!].string.unicodeScalars[index._chunkIndex] + return _rope[index._rope!].string.unicodeScalars[index._chunkIndex] } subscript(unicodeScalar offset: Int) -> Unicode.Scalar { @@ -496,7 +496,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func _foreachChunk( from start: Index, to end: Index, @@ -511,21 +511,21 @@ extension _BString { let endRopeIndex = end._rope! if ri == endRopeIndex { - let str = self.rope[ri].string + let str = self._rope[ri].string body(str[start._chunkIndex ..< end._chunkIndex]) return } - let firstChunk = self.rope[ri].string + let firstChunk = self._rope[ri].string body(firstChunk[start._chunkIndex...]) - rope.formIndex(after: &ri) + _rope.formIndex(after: &ri) while ri < endRopeIndex { - let string = rope[ri].string + let string = _rope[ri].string body(string[...]) } - let lastChunk = self.rope[ri].string + let lastChunk = self._rope[ri].string body(lastChunk[..=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { public func dump(heightLimit: Int = .max) { - rope.dump(heightLimit: heightLimit) + _rope.dump(heightLimit: heightLimit) } } diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BigString/Basics/BigString+Index.swift similarity index 83% rename from Sources/RopeModule/BString/Basics/_BString+Index.swift rename to Sources/RopeModule/BigString/Basics/BigString+Index.swift index ef73ce38..44174eb8 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Index.swift @@ -12,9 +12,9 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { public struct Index: Sendable { - typealias Rope = _BString.Rope + typealias _Storage = BigString._Storage // ┌───────────────────────────────┬───┬───────────┬────────────────────┐ // │ b63:b11 │b10│ b9:b8 │ b7:b0 │ @@ -31,17 +31,17 @@ extension _BString { var _rawBits: UInt64 /// A (possibly invalid) rope index. - var _rope: Rope.Index? + var _rope: _Storage.Index? - internal init(_raw: UInt64, rope: Rope.Index?) { + internal init(_raw: UInt64, _rope: _Storage.Index?) { self._rawBits = _raw - self._rope = rope + self._rope = _rope } } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index { +extension BigString.Index { @inline(__always) internal static func _bitsForUTF8Offset(_ utf8Offset: Int) -> UInt64 { let v = UInt64(truncatingIfNeeded: UInt(bitPattern: utf8Offset)) @@ -61,11 +61,6 @@ extension _BString.Index { @inline(__always) internal static var _scalarAlignmentBit: UInt64 { 0x100 } - @available(*, deprecated, renamed: "utf8Offset") - internal var _utf8Offset: Int { - utf8Offset - } - public var utf8Offset: Int { Int(truncatingIfNeeded: _rawBits &>> 11) } @@ -101,7 +96,7 @@ extension _BString.Index { extension String.Index { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) - func _copyingAlignmentBits(from i: _BString.Index) -> String.Index { + func _copyingAlignmentBits(from i: BigString.Index) -> String.Index { var bits = _abi_rawBits & ~3 bits |= (i._flags &>> 8) & 3 return String.Index(_rawBits: bits) @@ -109,7 +104,7 @@ extension String.Index { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index { +extension BigString.Index { internal var _chunkIndex: String.Index { assert(_rope != nil) return String.Index( @@ -119,7 +114,7 @@ extension _BString.Index { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index { +extension BigString.Index { internal mutating func _clearUTF16TrailingSurrogate() { _flags = 0 } @@ -162,7 +157,7 @@ extension _BString.Index { } internal init( - _utf8Offset: Int, utf16TrailingSurrogate: Bool = false, rope: Rope.Index, chunkOffset: Int + _utf8Offset: Int, utf16TrailingSurrogate: Bool = false, _rope: _Storage.Index, chunkOffset: Int ) { _rawBits = Self._bitsForUTF8Offset(_utf8Offset) if utf16TrailingSurrogate { @@ -170,42 +165,42 @@ extension _BString.Index { } assert(chunkOffset >= 0 && chunkOffset <= 0xFF) _rawBits |= UInt64(truncatingIfNeeded: chunkOffset) & 0xFF - self._rope = rope + self._rope = _rope } - internal init(baseUTF8Offset: Int, rope: Rope.Index, chunk: String.Index) { + internal init(baseUTF8Offset: Int, _rope: _Storage.Index, chunk: String.Index) { let chunkUTF8Offset = chunk._utf8Offset self.init( _utf8Offset: baseUTF8Offset + chunkUTF8Offset, utf16TrailingSurrogate: chunk._isUTF16TrailingSurrogate, - rope: rope, + _rope: _rope, chunkOffset: chunkUTF8Offset) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index: Equatable { +extension BigString.Index: Equatable { public static func ==(left: Self, right: Self) -> Bool { left._orderingValue == right._orderingValue } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index: Comparable { +extension BigString.Index: Comparable { public static func <(left: Self, right: Self) -> Bool { left._orderingValue < right._orderingValue } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index: Hashable { +extension BigString.Index: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(_orderingValue) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Index: CustomStringConvertible { +extension BigString.Index: CustomStringConvertible { public var description: String { let utf16Offset = _isUTF16TrailingSurrogate ? "+1" : "" return "\(utf8Offset)[utf8]\(utf16Offset)" @@ -213,33 +208,33 @@ extension _BString.Index: CustomStringConvertible { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func resolve(_ i: Index, preferEnd: Bool) -> Index { - if var ri = i._rope, rope.isValid(ri) { + if var ri = i._rope, _rope.isValid(ri) { if preferEnd { guard i.utf8Offset > 0, i._utf8ChunkOffset == 0 else { return i } - rope.formIndex(before: &ri) - let length = rope[ri].utf8Count + _rope.formIndex(before: &ri) + let length = _rope[ri].utf8Count let ci = String.Index(_utf8Offset: length) - var j = Index(baseUTF8Offset: i.utf8Offset - length, rope: ri, chunk: ci) + var j = Index(baseUTF8Offset: i.utf8Offset - length, _rope: ri, chunk: ci) j._flags = i._flags return j } - guard i.utf8Offset < utf8Count, i._utf8ChunkOffset == rope[ri].utf8Count else { + guard i.utf8Offset < utf8Count, i._utf8ChunkOffset == _rope[ri].utf8Count else { return i } - rope.formIndex(after: &ri) + _rope.formIndex(after: &ri) let ci = String.Index(_utf8Offset: 0) - var j = Index(baseUTF8Offset: i.utf8Offset, rope: ri, chunk: ci) + var j = Index(baseUTF8Offset: i.utf8Offset, _rope: ri, chunk: ci) j._flags = i._flags return j } - let (ri, chunkOffset) = rope.find( + let (ri, chunkOffset) = _rope.find( at: i.utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) let ci = String.Index( _utf8Offset: chunkOffset, utf16TrailingSurrogate: i._isUTF16TrailingSurrogate) - return Index(baseUTF8Offset: i.utf8Offset - ci._utf8Offset, rope: ri, chunk: ci) + return Index(baseUTF8Offset: i.utf8Offset - ci._utf8Offset, _rope: ri, chunk: ci) } } #endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Ingester.swift b/Sources/RopeModule/BigString/Basics/BigString+Ingester.swift similarity index 95% rename from Sources/RopeModule/BString/Basics/_BString+Ingester.swift rename to Sources/RopeModule/BigString/Basics/BigString+Ingester.swift index 46beb84b..458edf72 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Ingester.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Ingester.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func ingester( forInserting input: __owned Substring, at index: Index, @@ -25,10 +25,10 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { struct Ingester { - typealias Chunk = _BString.Chunk - typealias Counts = _BString.Chunk.Counts + typealias Chunk = BigString.Chunk + typealias Counts = BigString.Chunk.Counts var input: Substring @@ -154,11 +154,11 @@ extension String { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { init(_ string: String) { guard !string.isEmpty else { self.init(); return } assert(string.utf8.count <= Self.maxUTF8Count) - var ingester = _BString.Ingester(string) + var ingester = BigString.Ingester(string) self = ingester.nextChunk()! assert(ingester.isAtEnd) } diff --git a/Sources/RopeModule/BString/Basics/_BString+Invariants.swift b/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift similarity index 88% rename from Sources/RopeModule/BString/Basics/_BString+Invariants.swift rename to Sources/RopeModule/BigString/Basics/BigString+Invariants.swift index 92206213..a4538f52 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Invariants.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift @@ -12,14 +12,14 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - public func invariantCheck() { +extension BigString { + public func _invariantCheck() { #if DEBUG - rope.invariantCheck() - let allowUndersize = rope.isSingleton + _rope.invariantCheck() + let allowUndersize = _rope.isSingleton var state = _CharacterRecognizer() - for chunk in rope { + for chunk in _rope { precondition(allowUndersize || !chunk.isUndersized, "Undersized chunk") let (characters, prefix, suffix) = state.edgeCounts(consuming: chunk.string) precondition( diff --git a/Sources/RopeModule/BigString/Basics/BigString+Iterators.swift b/Sources/RopeModule/BigString/Basics/BigString+Iterators.swift new file mode 100644 index 00000000..96709598 --- /dev/null +++ b/Sources/RopeModule/BigString/Basics/BigString+Iterators.swift @@ -0,0 +1,38 @@ +//===----------------------------------------------------------------------===// +// +// 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 BigString { + struct ChunkIterator { + var base: _Storage.Iterator + + init(base: _Storage.Iterator) { + self.base = base + } + } + + func makeChunkIterator() -> ChunkIterator { + ChunkIterator(base: _rope.makeIterator()) + } +} + +@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) +extension BigString.ChunkIterator: IteratorProtocol { + typealias Element = String + + mutating func next() -> String? { + base.next()?.string + } +} + +#endif diff --git a/Sources/RopeModule/BString/Basics/_BString+Metrics.swift b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift similarity index 86% rename from Sources/RopeModule/BString/Basics/_BString+Metrics.swift rename to Sources/RopeModule/BigString/Basics/BigString+Metrics.swift index 4e0761df..b39258b5 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Metrics.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift @@ -12,25 +12,25 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -internal protocol _StringMetric: _RopeMetric where Element == _BString.Chunk { +internal protocol _StringMetric: _RopeMetric where Element == BigString.Chunk { func distance( from start: String.Index, to end: String.Index, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> Int func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> (found: Bool, forward: Bool) } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { internal struct CharacterMetric: _StringMetric { - typealias Element = _BString.Chunk - typealias Summary = _BString.Summary + typealias Element = BigString.Chunk + typealias Summary = BigString.Summary @inline(__always) func size(of summary: Summary) -> Int { @@ -40,7 +40,7 @@ extension _BString { func distance( from start: String.Index, to end: String.Index, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> Int { chunk.characterDistance(from: start, to: end) } @@ -48,12 +48,12 @@ extension _BString { func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> (found: Bool, forward: Bool) { chunk.formCharacterIndex(&i, offsetBy: &distance) } - func index(at offset: Int, in chunk: _BString.Chunk) -> String.Index { + func index(at offset: Int, in chunk: BigString.Chunk) -> String.Index { precondition(offset < chunk.characterCount) return chunk.wholeCharacters._index(at: offset) } @@ -68,7 +68,7 @@ extension _BString { func distance( from start: String.Index, to end: String.Index, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> Int { chunk.string.unicodeScalars.distance(from: start, to: end) } @@ -76,7 +76,7 @@ extension _BString { func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> (found: Bool, forward: Bool) { guard distance != 0 else { i = chunk.string.unicodeScalars._index(roundingDown: i) @@ -98,7 +98,7 @@ extension _BString { return (distance == 0, false) } - func index(at offset: Int, in chunk: _BString.Chunk) -> String.Index { + func index(at offset: Int, in chunk: BigString.Chunk) -> String.Index { chunk.string.unicodeScalars.index(chunk.string.startIndex, offsetBy: offset) } } @@ -112,7 +112,7 @@ extension _BString { func distance( from start: String.Index, to end: String.Index, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> Int { chunk.string.utf8.distance(from: start, to: end) } @@ -120,7 +120,7 @@ extension _BString { func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> (found: Bool, forward: Bool) { // Here we make use of the fact that the UTF-8 view of native Swift strings // have O(1) index distance & offset calculations. @@ -147,7 +147,7 @@ extension _BString { return (true, false) } - func index(at offset: Int, in chunk: _BString.Chunk) -> String.Index { + func index(at offset: Int, in chunk: BigString.Chunk) -> String.Index { chunk.string.utf8.index(chunk.string.startIndex, offsetBy: offset) } } @@ -161,7 +161,7 @@ extension _BString { func distance( from start: String.Index, to end: String.Index, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> Int { chunk.string.utf16.distance(from: start, to: end) } @@ -169,7 +169,7 @@ extension _BString { func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: _BString.Chunk + in chunk: BigString.Chunk ) -> (found: Bool, forward: Bool) { if distance >= 0 { if @@ -200,7 +200,7 @@ extension _BString { return (false, false) } - func index(at offset: Int, in chunk: _BString.Chunk) -> String.Index { + func index(at offset: Int, in chunk: BigString.Chunk) -> String.Index { chunk.string.utf16.index(chunk.string.startIndex, offsetBy: offset) } } diff --git a/Sources/RopeModule/BString/Basics/_BString+Summary.swift b/Sources/RopeModule/BigString/Basics/BigString+Summary.swift similarity index 88% rename from Sources/RopeModule/BString/Basics/_BString+Summary.swift rename to Sources/RopeModule/BigString/Basics/BigString+Summary.swift index 5e0a9305..d4e72347 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Summary.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Summary.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { struct Summary { // FIXME: We only need 48 * 3 = 192 bits to represent a nonnegative value; pack these better // (Unfortunately we also need to represent negative values right now.) @@ -28,7 +28,7 @@ extension _BString { utf8 = 0 } - init(_ chunk: _BString.Chunk) { + init(_ chunk: BigString.Chunk) { self.utf8 = chunk.utf8Count self.utf16 = Int(chunk.counts.utf16) self.unicodeScalars = Int(chunk.counts.unicodeScalars) @@ -38,14 +38,14 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Summary: CustomStringConvertible { +extension BigString.Summary: CustomStringConvertible { var description: String { "❨\(utf8)⋅\(utf16)⋅\(unicodeScalars)⋅\(characters)❩" } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Summary: _RopeSummary { +extension BigString.Summary: _RopeSummary { @inline(__always) static var maxNodeSize: Int { #if DEBUG @@ -64,14 +64,14 @@ extension _BString.Summary: _RopeSummary { @inline(__always) var isZero: Bool { utf8 == 0 } - mutating func add(_ other: _BString.Summary) { + mutating func add(_ other: BigString.Summary) { characters += other.characters unicodeScalars += other.unicodeScalars utf16 += other.utf16 utf8 += other.utf8 } - mutating func subtract(_ other: _BString.Summary) { + mutating func subtract(_ other: BigString.Summary) { characters -= other.characters unicodeScalars -= other.unicodeScalars utf16 -= other.utf16 diff --git a/Sources/RopeModule/BString/Basics/_BString.swift b/Sources/RopeModule/BigString/Basics/BigString.swift similarity index 63% rename from Sources/RopeModule/BString/Basics/_BString.swift rename to Sources/RopeModule/BigString/Basics/BigString.swift index c3be84be..a32584a0 100644 --- a/Sources/RopeModule/BString/Basics/_BString.swift +++ b/Sources/RopeModule/BigString/Basics/BigString.swift @@ -13,21 +13,21 @@ /// The core of a B-tree based String implementation. @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -public struct _BString: Sendable { - typealias Rope = _Rope +public struct BigString: Sendable { + typealias _Storage = _Rope - var rope: Rope + var _rope: _Storage - internal init(rope: Rope) { - self.rope = rope + internal init(_rope: _Storage) { + self._rope = _rope } } #else -// `_BString` depends on fixes and newly exposed functionality that landed in +// `BigString` depends on fixes and newly exposed functionality that landed in // version 5.8 of the Swift Standard Library. -@available(*, unavailable, message: "_BString depends on version 5.8 of the Swift Standard Library") -public struct _BString: Sendable {} +@available(*, unavailable, message: "BigString depends on version 5.8 of the Swift Standard Library") +public struct BigString: Sendable {} #endif diff --git a/Sources/RopeModule/BigString/BigString+CharacterView.swift b/Sources/RopeModule/BigString/BigString+CharacterView.swift deleted file mode 100644 index b9e4d84c..00000000 --- a/Sources/RopeModule/BigString/BigString+CharacterView.swift +++ /dev/null @@ -1,250 +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 BigString { - public struct Index { - internal var _value: _BString.Index - - internal init(_ value: _BString.Index) { - self._value = value - } - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Index: CustomStringConvertible { - public var description: String { - "\(_value)" - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Index: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - left._value == right._value - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Index: Comparable { - public static func <(left: Self, right: Self) -> Bool { - left._value < right._value - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Index: Hashable { - public func hash(into hasher: inout Hasher) { - hasher.combine(_value) - } -} - -@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 == 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 < right._guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString: Hashable { - public func hash(into hasher: inout Hasher) { - _guts.hashCharacters(into: &hasher) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString: Sequence { - public typealias Element = Character - public typealias Iterator = _BString.Iterator - - public func makeIterator() -> Iterator { - _guts.makeIterator() - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString: BidirectionalCollection { - public typealias SubSequence = BigSubstring - - public var count: Int { _guts.count } - - public var startIndex: Index { Index(_guts.startIndex) } - public var endIndex: Index { Index(_guts.endIndex) } - public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } - public func index(before i: Index) -> Index { Index(_guts.index(before: i._value)) } - public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.index(i._value, offsetBy: distance)) - } - public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } - } - public func distance(from start: Index, to end: Index) -> Int { - _guts.distance(from: start._value, to: end._value) - } - public subscript(position: Index) -> Character { - _guts[position._value] - } - public subscript(bounds: Range) -> BigSubstring { - BigSubstring(_guts: _guts[bounds._base]) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString: RangeReplaceableCollection { - public init() { - self.init(_guts: _BString()) - } - - public mutating func reserveCapacity(_ n: Int) {} - - public mutating func replaceSubrange>( // Note: Sequence, not Collection - _ subrange: Range, - with newElements: __owned C - ) { - if C.self == BigString.self { - let newElements = _identityCast(newElements, to: BigString.self) - replaceSubrange(subrange, with: newElements) - } else if C.self == BigSubstring.self { - let newElements = _identityCast(newElements, to: BigSubstring.self) - replaceSubrange(subrange, with: newElements) - } else { - _guts.replaceSubrange(subrange._base, with: newElements) - } - } - - public mutating func replaceSubrange( - _ subrange: Range, - with newElements: __owned BigString - ) { - _guts.replaceSubrange(subrange._base, with: newElements._guts) - } - - public mutating func replaceSubrange( - _ subrange: Range, - with newElements: __owned BigSubstring - ) { - _guts.replaceSubrange(subrange._base, with: newElements._guts) - } - - public init>(_ elements: S) { - if S.self == BigString.self { - let newElements = _identityCast(elements, to: BigString.self) - self.init(_guts: newElements._guts) - } else if S.self == BigSubstring.self { - let newElements = _identityCast(elements, to: BigSubstring.self) - self.init(_guts: _BString(newElements._guts)) - } else { - self.init(_guts: _BString(elements)) - } - } - - public init(_ elements: BigString) { - self._guts = elements._guts - } - - public init(_ elements: BigSubstring) { - self._guts = _BString(elements._guts) - } - - public init(repeating repeatedValue: Character, count: Int) { - self._guts = _BString(repeating: _BString(String(repeatedValue)), count: count) - } - - public init(repeating repeatedValue: some StringProtocol, count: Int) { - self._guts = _BString(repeating: _BString(repeatedValue), count: count) - } - - public init(repeating repeatedValue: BigString, count: Int) { - self._guts = _BString(repeating: repeatedValue._guts, count: count) - } - - public init(repeating repeatedValue: BigSubstring, count: Int) { - self._guts = _BString(repeating: repeatedValue._guts, count: count) - } - - public mutating func append(_ newElement: __owned Character) { - _guts.append(newElement) - } - - public mutating func append>( - contentsOf newElements: __owned S - ) { - if S.self == BigString.self { - let newElements = _identityCast(newElements, to: BigString.self) - self.append(contentsOf: newElements) - } else if S.self == BigSubstring.self { - let newElements = _identityCast(newElements, to: BigSubstring.self) - self.append(contentsOf: newElements) - } else { - _guts.append(contentsOf: newElements) - } - } - - public mutating func append(contentsOf newElements: __owned BigString) { - _guts.append(contentsOf: newElements._guts) - } - - public mutating func append(contentsOf newElements: __owned BigSubstring) { - _guts.append(contentsOf: newElements._guts) - } - - public mutating func insert(_ newElement: __owned Character, at i: Index) { - _guts.insert(newElement, at: i._value) - } - - public mutating func insert>( // Note: Sequence, not Collection - contentsOf newElements: __owned S, at i: Index - ) { - if S.self == BigString.self { - let newElements = _identityCast(newElements, to: BigString.self) - self.insert(contentsOf: newElements, at: i) - } else if S.self == BigSubstring.self { - let newElements = _identityCast(newElements, to: BigSubstring.self) - self.insert(contentsOf: newElements, at: i) - } else { - _guts.insert(contentsOf: newElements, at: i._value) - } - } - - public mutating func insert(contentsOf newElements: __owned BigString, at i: Index) { - _guts.insert(contentsOf: newElements._guts, at: i._value) - } - - public mutating func insert(contentsOf newElements: __owned BigSubstring, at i: Index) { - _guts.insert(contentsOf: newElements._guts, at: i._value) - } - - @discardableResult - public mutating func remove(at i: Index) -> Character { - _guts.remove(at: i._value) - } - - public mutating func removeSubrange(_ bounds: Range) { - _guts.removeSubrange(bounds._base) - } - - public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - _guts.removeAll(keepingCapacity: keepCapacity) - } -} - -#endif diff --git a/Sources/RopeModule/BigString/BigString+UTF16View.swift b/Sources/RopeModule/BigString/BigString+UTF16View.swift deleted file mode 100644 index 34b27a00..00000000 --- a/Sources/RopeModule/BigString/BigString+UTF16View.swift +++ /dev/null @@ -1,114 +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 BigString { - public struct UTF16View { - internal var _guts: _BString.UTF16View - - internal init(_guts: _BString.UTF16View) { - self._guts = _guts - } - } - - public var utf16: UTF16View { - UTF16View(_guts: _guts.utf16) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString { - public init(_ content: UTF16View) { - self._guts = _BString(content._guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF16View: CustomStringConvertible { - public var description: String { - var d = "<" - d += self.lazy - .map { String($0, radix: 16, uppercase: true)._lpad(to: 4, with: "0") } - .joined(separator: " ") - d += ">" - return d - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF16View: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - left._guts == right._guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF16View: Hashable { - public func hash(into hasher: inout Hasher) { - _guts.hash(into: &hasher) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF16View: Sequence { - public typealias Element = UInt16 - public typealias Iterator = _BString.UTF16View.Iterator - - public func makeIterator() -> Iterator { - _guts.makeIterator() - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF16View: BidirectionalCollection { - public typealias Index = BigString.Index - public typealias SubSequence = BigSubstring.UTF16View - - public var count: Int { - _guts.count - } - - public var startIndex: Index { - Index(_guts.startIndex) - } - - public var endIndex: Index { - Index(_guts.endIndex) - } - - public func index(after i: Index) -> Index { - Index(_guts.index(after: i._value)) - } - - public func index(before i: Index) -> Index { - Index(_guts.index(before: i._value)) - } - - public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.index(i._value, offsetBy: distance)) - } - - public func distance(from start: Index, to end: Index) -> Int { - _guts.distance(from: start._value, to: end._value) - } - - public subscript(position: Index) -> UInt16 { - _guts[position._value] - } - - public subscript(bounds: Range) -> BigSubstring.UTF16View { - BigSubstring.UTF16View(_guts: _guts[bounds._base]) - } -} - -#endif diff --git a/Sources/RopeModule/BigString/BigString+UTF8View.swift b/Sources/RopeModule/BigString/BigString+UTF8View.swift deleted file mode 100644 index 2fa4d03c..00000000 --- a/Sources/RopeModule/BigString/BigString+UTF8View.swift +++ /dev/null @@ -1,114 +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 BigString { - public struct UTF8View { - internal var _guts: _BString.UTF8View - - internal init(_guts: _BString.UTF8View) { - self._guts = _guts - } - } - - public var utf8: UTF8View { - UTF8View(_guts: _guts.utf8) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString { - public init(_ content: UTF8View) { - self._guts = _BString(content._guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF8View: CustomStringConvertible { - public var description: String { - var d = "<" - d += self.lazy - .map { String($0, radix: 16, uppercase: true)._lpad(to: 2, with: "0") } - .joined(separator: " ") - d += ">" - return d - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF8View: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - left._guts == right._guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF8View: Hashable { - public func hash(into hasher: inout Hasher) { - _guts.hash(into: &hasher) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF8View: Sequence { - public typealias Element = UInt8 - public typealias Iterator = _BString.UTF8View.Iterator - - public func makeIterator() -> Iterator { - _guts.makeIterator() - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UTF8View: BidirectionalCollection { - public typealias Index = BigString.Index - public typealias SubSequence = BigSubstring.UTF8View - - public var count: Int { - _guts.count - } - - public var startIndex: Index { - Index(_guts.startIndex) - } - - public var endIndex: Index { - Index(_guts.endIndex) - } - - public func index(after i: Index) -> Index { - Index(_guts.index(after: i._value)) - } - - public func index(before i: Index) -> Index { - Index(_guts.index(before: i._value)) - } - - public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.index(i._value, offsetBy: distance)) - } - - public func distance(from start: Index, to end: Index) -> Int { - _guts.distance(from: start._value, to: end._value) - } - - public subscript(position: Index) -> UInt8 { - _guts[position._value] - } - - public subscript(bounds: Range) -> BigSubstring.UTF8View { - BigSubstring.UTF8View(_guts: _guts[bounds._base]) - } -} - -#endif diff --git a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift deleted file mode 100644 index 623d3557..00000000 --- a/Sources/RopeModule/BigString/BigString+UnicodeScalarView.swift +++ /dev/null @@ -1,218 +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 BigString { - public struct UnicodeScalarView { - var _guts: _BString.UnicodeScalarView - - init(_guts: _BString.UnicodeScalarView) { - self._guts = _guts - } - } - - public var unicodeScalars: UnicodeScalarView { - get { - UnicodeScalarView(_guts: _guts.unicodeScalars) - } - set { - _guts = newValue._guts._base - } - _modify { - var view = UnicodeScalarView(_guts: _guts.unicodeScalars) - self._guts = .init() - defer { - self._guts = view._guts._base - } - yield &view - } - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString { - public init(_ content: UnicodeScalarView) { - self._guts = _BString(content._guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UnicodeScalarView: ExpressibleByStringLiteral { - public init(stringLiteral value: String) { - self.init(_guts: _BString(value).unicodeScalars) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UnicodeScalarView: CustomStringConvertible { - public var description: String { - String(_guts._base) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UnicodeScalarView: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - left._guts == right._guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UnicodeScalarView: Hashable { - public func hash(into hasher: inout Hasher) { - _guts.hash(into: &hasher) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UnicodeScalarView: Sequence { - public typealias Element = Unicode.Scalar - public typealias Iterator = _BString.UnicodeScalarView.Iterator - - public func makeIterator() -> Iterator { - _guts.makeIterator() - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UnicodeScalarView: BidirectionalCollection { - public typealias Index = BigString.Index - public typealias SubSequence = BigSubstring.UnicodeScalarView - - public var count: Int { - _guts.count - } - - public var startIndex: Index { - Index(_guts.startIndex) - } - - public var endIndex: Index { - Index(_guts.endIndex) - } - - public func index(after i: Index) -> Index { - Index(_guts.index(after: i._value)) - } - - public func index(before i: Index) -> Index { - Index(_guts.index(after: i._value)) - } - - public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.index(i._value, offsetBy: distance)) - } - - public func distance(from start: Index, to end: Index) -> Int { - _guts.distance(from: start._value, to: end._value) - } - - public subscript(index: Index) -> Unicode.Scalar { - _guts[index._value] - } - - public subscript(bounds: Range) -> BigSubstring.UnicodeScalarView { - BigSubstring.UnicodeScalarView(_guts: _guts[bounds._base]) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.UnicodeScalarView: RangeReplaceableCollection { - public mutating func replaceSubrange( - _ subrange: Range, - 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 - } - _guts.replaceSubrange(subrange._base, with: newElements) - } - - public mutating func reserveCapacity(_ n: Int) {} - - public init() { - _guts = .init() - } - - 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 - return - } - self._guts = _BString.UnicodeScalarView(elements) - } - - public init(repeating scalar: UnicodeScalar, count: Int) { - self._guts = _BString.UnicodeScalarView(repeating: scalar, count: count) - } - - public mutating func append(_ newElement: __owned UnicodeScalar) { - _guts.append(newElement) - } - - 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) - let range = newElements.startIndex ..< newElements.endIndex - _guts.append(contentsOf: newElements.base._guts[range._base]) - return - } - _guts.append(contentsOf: newElements) - } - - public mutating func insert(_ newElement: __owned Unicode.Scalar, at i: Index) { - _guts.insert(newElement, 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) - let range = newElements.startIndex ..< newElements.endIndex - self._guts.insert(contentsOf: newElements.base._guts[range._base], at: i._value) - return - } - _guts.insert(contentsOf: newElements, at: i._value) - } - - @discardableResult - public mutating func remove(at i: Index) -> Unicode.Scalar { - _guts.remove(at: i._value) - } - - public mutating func removeSubrange(_ bounds: Range) { - _guts.removeSubrange(bounds._base) - } - - public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - _guts.removeAll(keepingCapacity: keepCapacity) - } -} - -#endif diff --git a/Sources/RopeModule/BigString/BigString.swift b/Sources/RopeModule/BigString/BigString.swift deleted file mode 100644 index d8d0354a..00000000 --- a/Sources/RopeModule/BigString/BigString.swift +++ /dev/null @@ -1,96 +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, *) -public struct BigString: Sendable { - internal var _guts: _BString - - internal init(_guts: _BString) { - self._guts = _guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString: ExpressibleByStringLiteral { - public init(stringLiteral value: String) { - self.init(value) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString: CustomStringConvertible, LosslessStringConvertible { - public var description: String { - String(_guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString: TextOutputStream { - public mutating func write(_ string: String) { - self.append(contentsOf: string) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString { - public static var _minimumCapacity: Int { _BString.minimumCapacity } - public static var _maximumCapacity: Int { _BString.maximumCapacity } - - public func _invariantCheck() { - _guts.invariantCheck() - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension String { - public init(_ big: BigString) { - self.init(big._guts) - } - - public init(_ big: BigSubstring) { - self.init(big._guts) - } - - public init(_ big: BigString.UnicodeScalarView) { - self.init(big._guts) - } - - public init(_ big: BigSubstring.UnicodeScalarView) { - self.init(big._guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension String.UnicodeScalarView { - public init(_ big: BigString.UnicodeScalarView) { - self = String(big._guts._base).unicodeScalars - } - - public init(_ big: BigSubstring.UnicodeScalarView) { - self = String(big._guts._base).unicodeScalars - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension Range { - internal var _base: Range<_BString.Index> { - Range<_BString.Index>(uncheckedBounds: (lowerBound._value, upperBound._value)) - } -} - -#else - -@available(*, unavailable, message: "BigString requires Swift 5.8") -public struct BigString: Sendable {} - -#endif diff --git a/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift b/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift deleted file mode 100644 index f13f0b96..00000000 --- a/Sources/RopeModule/BigString/BigSubstring+UTF16View.swift +++ /dev/null @@ -1,106 +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 BigSubstring { - public struct UTF16View: Sendable { - internal var _guts: _BSubstring.UTF16View - - internal init(_guts: _BSubstring.UTF16View) { - self._guts = _guts - } - } - - public var utf16: UTF16View { - UTF16View(_guts: _guts.utf16) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString { - public init?(_ utf8: BigSubstring.UTF16View) { - guard let guts = _BString(utf8._guts) else { return nil } - self.init(_guts: guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF16View { - public var base: BigString.UTF16View { - BigString.UTF16View(_guts: _guts.base) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF16View: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - left._guts == right._guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF16View: Hashable { - public func hash(into hasher: inout Hasher) { - _guts.hash(into: &hasher) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF16View: Sequence { - public typealias Element = UInt16 - public typealias Iterator = _BSubstring.UTF16View.Iterator - - public func makeIterator() -> Iterator { - _guts.makeIterator() - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF16View: BidirectionalCollection { - public typealias Index = BigString.Index - public typealias SubSequence = Self - - public var startIndex: Index { Index(_guts.startIndex) } - public var endIndex: Index { Index(_guts.endIndex) } - public var count: Int { _guts.count } - public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } - public func index(before i: Index) -> Index { Index(_guts.index(after: i._value)) } - public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.index(i._value, offsetBy: distance)) - } - public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } - } - public func distance(from start: Index, to end: Index) -> Int { - _guts.distance(from: start._value, to: end._value) - } - public subscript(position: Index) -> UInt16 { - _guts[position._value] - } - public subscript(bounds: Range) -> Self { - BigSubstring.UTF16View(_guts: _guts[bounds._base]) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF16View { - internal func index(roundingDown i: Index) -> Index { - Index(_guts.index(roundingDown: i._value)) - } - - internal func index(roundingUp i: Index) -> Index { - Index(_guts.index(roundingUp: i._value)) - } -} - -#endif diff --git a/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift b/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift deleted file mode 100644 index eb6640b4..00000000 --- a/Sources/RopeModule/BigString/BigSubstring+UTF8View.swift +++ /dev/null @@ -1,106 +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 BigSubstring { - public struct UTF8View: Sendable { - internal var _guts: _BSubstring.UTF8View - - internal init(_guts: _BSubstring.UTF8View) { - self._guts = _guts - } - } - - public var utf8: UTF8View { - UTF8View(_guts: _guts.utf8) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString { - public init?(_ utf8: BigSubstring.UTF8View) { - guard let guts = _BString(utf8._guts) else { return nil } - self.init(_guts: guts) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF8View { - public var base: BigString.UTF8View { - BigString.UTF8View(_guts: _guts.base) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF8View: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - left._guts == right._guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF8View: Hashable { - public func hash(into hasher: inout Hasher) { - _guts.hash(into: &hasher) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF8View: Sequence { - public typealias Element = UInt8 - public typealias Iterator = _BSubstring.UTF8View.Iterator - - public func makeIterator() -> Iterator { - _guts.makeIterator() - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF8View: BidirectionalCollection { - public typealias Index = BigString.Index - public typealias SubSequence = Self - - public var startIndex: Index { Index(_guts.startIndex) } - public var endIndex: Index { Index(_guts.endIndex) } - public var count: Int { _guts.count } - public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } - public func index(before i: Index) -> Index { Index(_guts.index(after: i._value)) } - public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.index(i._value, offsetBy: distance)) - } - public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } - } - public func distance(from start: Index, to end: Index) -> Int { - _guts.distance(from: start._value, to: end._value) - } - public subscript(position: Index) -> UInt8 { - _guts[position._value] - } - public subscript(bounds: Range) -> Self { - BigSubstring.UTF8View(_guts: _guts[bounds._base]) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UTF8View { - internal func index(roundingDown i: Index) -> Index { - Index(_guts.index(roundingDown: i._value)) - } - - internal func index(roundingUp i: Index) -> Index { - Index(_guts.index(roundingUp: i._value)) - } -} - -#endif diff --git a/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift deleted file mode 100644 index fb5ff876..00000000 --- a/Sources/RopeModule/BigString/BigSubstring+UnicodeScalarView.swift +++ /dev/null @@ -1,216 +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 BigSubstring { - public struct UnicodeScalarView: Sendable { - internal var _guts: _BSubstring.UnicodeScalarView - - internal init(_guts: _BSubstring.UnicodeScalarView) { - self._guts = _guts - } - } - - public var unicodeScalars: UnicodeScalarView { - UnicodeScalarView(_guts: _guts.unicodeScalars) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString { - public init(_ unicodeScalars: BigSubstring.UnicodeScalarView) { - self.init(_guts: _BString(unicodeScalars._guts)) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView { - public var base: BigString.UnicodeScalarView { - BigString.UnicodeScalarView(_guts: _guts.base) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView: ExpressibleByStringLiteral { - public init(stringLiteral value: String) { - self.init(_guts: _BSubstring.UnicodeScalarView(value.unicodeScalars)) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView: CustomStringConvertible { - public var description: String { - _guts.description - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView: CustomDebugStringConvertible { - public var debugDescription: String { - _guts.debugDescription - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - left._guts == right._guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView: Hashable { - public func hash(into hasher: inout Hasher) { - _guts.hash(into: &hasher) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView: Sequence { - public typealias Element = UnicodeScalar - public typealias Iterator = _BSubstring.UnicodeScalarView.Iterator - - public func makeIterator() -> Iterator { - _guts.makeIterator() - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView: BidirectionalCollection { - public typealias Index = BigString.Index - public typealias SubSequence = Self - - public var startIndex: Index { Index(_guts.startIndex) } - public var endIndex: Index { Index(_guts.endIndex) } - public var count: Int { _guts.count } - public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } - public func index(before i: Index) -> Index { Index(_guts.index(after: i._value)) } - public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.index(i._value, offsetBy: distance)) - } - public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } - } - public func distance(from start: Index, to end: Index) -> Int { - _guts.distance(from: start._value, to: end._value) - } - public subscript(position: Index) -> UnicodeScalar { - _guts[position._value] - } - public subscript(bounds: Range) -> Self { - BigSubstring.UnicodeScalarView(_guts: _guts[bounds._base]) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView { - internal func index(roundingDown i: Index) -> Index { - Index(_guts.index(roundingDown: i._value)) - } - - internal func index(roundingUp i: Index) -> Index { - Index(_guts.index(roundingUp: i._value)) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring.UnicodeScalarView: RangeReplaceableCollection { - public init() { - self.init(_guts: _BSubstring.UnicodeScalarView()) - } - - public mutating func reserveCapacity(_ n: Int) {} - - public mutating func replaceSubrange>( // Note: Sequence, not Collection - _ subrange: Range, - with newElements: __owned C - ) { - if C.self == BigString.UnicodeScalarView.self { - let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) - _guts.replaceSubrange(subrange._base, with: newElements._guts) - } else if C.self == BigSubstring.UnicodeScalarView.self { - let newElements = _identityCast(newElements, to: BigSubstring.UnicodeScalarView.self) - _guts.replaceSubrange(subrange._base, with: newElements._guts) - } else { - _guts.replaceSubrange(subrange._base, with: newElements) - } - } - - public init>(_ elements: S) { - if S.self == BigString.UnicodeScalarView.self { - let newElements = _identityCast(elements, to: BigString.UnicodeScalarView.self) - self.init(_guts: _BSubstring.UnicodeScalarView(newElements._guts)) - } else if S.self == BigSubstring.UnicodeScalarView.self { - let newElements = _identityCast(elements, to: BigSubstring.UnicodeScalarView.self) - let base = _BString.UnicodeScalarView(newElements._guts) - self.init(_guts: _BSubstring.UnicodeScalarView(base)) - } else { - self.init(_guts: _BSubstring.UnicodeScalarView(elements)) - } - } - - public init(repeating repeatedValue: UnicodeScalar, count: Int) { - self._guts = _BSubstring.UnicodeScalarView(repeating: repeatedValue, count: count) - } - - public mutating func append(_ newElement: UnicodeScalar) { - _guts.append(newElement) - } - - public mutating func append>( - contentsOf newElements: __owned S - ) { - if S.self == BigString.UnicodeScalarView.self { - let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) - _guts.append(contentsOf: newElements._guts) - } else if S.self == BigSubstring.UnicodeScalarView.self { - let newElements = _identityCast(newElements, to: BigSubstring.UnicodeScalarView.self) - _guts.append(contentsOf: newElements._guts) - } else { - _guts.append(contentsOf: newElements) - } - } - - public mutating func insert(_ newElement: UnicodeScalar, at i: Index) { - _guts.insert(newElement, at: i._value) - } - - public mutating func insert>( // Note: Sequence, not Collection - contentsOf newElements: __owned C, at i: Index - ) { - if C.self == BigString.UnicodeScalarView.self { - let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) - _guts.insert(contentsOf: newElements._guts, at: i._value) - } else if C.self == BigSubstring.UnicodeScalarView.self { - let newElements = _identityCast(newElements, to: BigSubstring.UnicodeScalarView.self) - _guts.insert(contentsOf: newElements._guts, at: i._value) - } else { - _guts.insert(contentsOf: newElements, at: i._value) - } - } - - @discardableResult - public mutating func remove(at i: Index) -> UnicodeScalar { - _guts.remove(at: i._value) - } - - public mutating func removeSubrange(_ bounds: Range) { - _guts.removeSubrange(bounds._base) - } - - public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - _guts.removeAll(keepingCapacity: keepCapacity) - } -} - -#endif diff --git a/Sources/RopeModule/BigString/BigSubstring.swift b/Sources/RopeModule/BigString/BigSubstring.swift deleted file mode 100644 index ca62209e..00000000 --- a/Sources/RopeModule/BigString/BigSubstring.swift +++ /dev/null @@ -1,217 +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, *) -public struct BigSubstring: Sendable { - internal var _guts: _BSubstring - - internal init(_guts: _BSubstring) { - self._guts = _guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring { - public var base: BigString { BigString(_guts: _guts._base) } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: CustomStringConvertible { - public var description: String { _guts.description } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: CustomDebugStringConvertible { - public var debugDescription: String { _guts.debugDescription } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: ExpressibleByStringLiteral { - public init(stringLiteral value: String) { - self.init(_guts: _BSubstring(stringLiteral: value)) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: LosslessStringConvertible { - // init?(_: String) is implemented by RangeReplaceableCollection.init(_:) -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: Equatable { - public static func ==(left: Self, right: Self) -> Bool { - left._guts == right._guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: Hashable { - public func hash(into hasher: inout Hasher) { - _guts.hash(into: &hasher) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: Comparable { - public static func < (left: Self, right: Self) -> Bool { - left._guts < right._guts - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: Sequence { - public typealias Element = Character - public typealias Iterator = _BSubstring.Iterator - - public func makeIterator() -> Iterator { - _guts.makeIterator() - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: BidirectionalCollection { - public typealias Index = BigString.Index - public typealias SubSequence = Self - - public var startIndex: Index { Index(_guts.startIndex) } - public var endIndex: Index { Index(_guts.endIndex) } - public var count: Int { _guts.count } - public func index(after i: Index) -> Index { Index(_guts.index(after: i._value)) } - public func index(before i: Index) -> Index { Index(_guts.index(after: i._value)) } - public func index(_ i: Index, offsetBy distance: Int) -> Index { - Index(_guts.index(i._value, offsetBy: distance)) - } - public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _guts.index(i._value, offsetBy: distance, limitedBy: limit._value).map { Index($0) } - } - public func distance(from start: Index, to end: Index) -> Int { - _guts.distance(from: start._value, to: end._value) - } - public subscript(position: Index) -> Character { - _guts[position._value] - } - public subscript(bounds: Range) -> Self { - BigSubstring(_guts: _guts[bounds._base]) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring { - public func index(roundingDown i: Index) -> Index { - Index(_guts.index(roundingDown: i._value)) - } - public func index(roundingUp i: Index) -> Index { - Index(_guts.index(roundingUp: i._value)) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigSubstring: RangeReplaceableCollection { - public init() { - self.init(_guts: _BSubstring()) - } - - public mutating func reserveCapacity(_ n: Int) {} - - public mutating func replaceSubrange>( // Note: Sequence, not Collection - _ subrange: Range, - with newElements: __owned C - ) { - if C.self == BigString.self { - let newElements = _identityCast(newElements, to: BigString.self) - _guts.replaceSubrange(subrange._base, with: newElements._guts) - } else if C.self == BigSubstring.self { - let newElements = _identityCast(newElements, to: BigSubstring.self) - _guts.replaceSubrange(subrange._base, with: newElements._guts) - } else { - _guts.replaceSubrange(subrange._base, with: newElements) - } - } - - public init>(_ elements: S) { - if S.self == BigString.self { - let newElements = _identityCast(elements, to: BigString.self) - self.init(_guts: _BSubstring(newElements._guts)) - } else if S.self == BigSubstring.self { - let newElements = _identityCast(elements, to: BigSubstring.self) - self.init(_guts: _BSubstring(_BString(newElements._guts))) - } else { - self.init(_guts: _BSubstring(elements)) - } - } - - public init(repeating repeatedValue: Character, count: Int) { - self._guts = _BSubstring(repeating: repeatedValue, count: count) - } - - public init(repeating repeatedValue: some StringProtocol, count: Int) { - self._guts = _BSubstring(repeating: repeatedValue, count: count) - } - - public init(repeating repeatedValue: BigString, count: Int) { - self._guts = _BSubstring(repeating: repeatedValue._guts, count: count) - } - - public init(repeating repeatedValue: BigSubstring, count: Int) { - self._guts = _BSubstring(repeating: repeatedValue._guts, count: count) - } - - public mutating func append(_ newElement: Character) { - _guts.append(newElement) - } - - public mutating func append>(contentsOf newElements: __owned S) { - if S.self == BigString.self { - let newElements = _identityCast(newElements, to: BigString.self) - _guts.append(contentsOf: newElements._guts) - } else if S.self == BigSubstring.self { - let newElements = _identityCast(newElements, to: BigSubstring.self) - _guts.append(contentsOf: newElements._guts) - } else { - _guts.append(contentsOf: newElements) - } - } - - public mutating func insert(_ newElement: Character, at i: Index) { - _guts.insert(newElement, at: i._value) - } - - public mutating func insert>( // Note: Sequence, not Collection - contentsOf newElements: __owned C, at i: Index - ) { - if C.self == BigString.self { - let newElements = _identityCast(newElements, to: BigString.self) - _guts.insert(contentsOf: newElements._guts, at: i._value) - } else if C.self == BigSubstring.self { - let newElements = _identityCast(newElements, to: BigSubstring.self) - _guts.insert(contentsOf: newElements._guts, at: i._value) - } else { - _guts.insert(contentsOf: newElements, at: i._value) - } - } - - @discardableResult - public mutating func remove(at i: Index) -> Character { - _guts.remove(at: i._value) - } - - public mutating func removeSubrange(_ bounds: Range) { - _guts.removeSubrange(bounds._base) - } - - public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - _guts.removeAll(keepingCapacity: keepCapacity) - } -} - -#endif diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift similarity index 92% rename from Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift rename to Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift index b0d7016b..51af9b03 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Append and Insert.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift @@ -12,13 +12,13 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { mutating func append(_ other: __owned Self) { self._append(other.string[...], other.counts) } - mutating func append(from ingester: inout _BString.Ingester) -> Self? { - let desired = _BString.Ingester.desiredNextChunkSize( + mutating func append(from ingester: inout BigString.Ingester) -> Self? { + let desired = BigString.Ingester.desiredNextChunkSize( remaining: self.utf8Count + ingester.remainingUTF8) if desired == self.utf8Count { return nil @@ -67,7 +67,7 @@ extension _BString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { mutating func _insert( _ slice: Slice, at index: String.Index, @@ -92,7 +92,7 @@ extension _BString.Chunk { typealias States = (increment: Int, old: _CharacterRecognizer, new: _CharacterRecognizer) mutating func insertAll( - from ingester: inout _BString.Ingester, + from ingester: inout BigString.Ingester, at index: String.Index ) -> States? { let remaining = ingester.remainingUTF8 @@ -110,12 +110,12 @@ extension _BString.Chunk { enum InsertResult { case inline(States?) - case split(spawn: _BString.Chunk, endStates: States?) + case split(spawn: BigString.Chunk, endStates: States?) case large } mutating func insert( - from ingester: inout _BString.Ingester, + from ingester: inout BigString.Ingester, at index: String.Index ) -> InsertResult { let origCount = self.utf8Count @@ -129,7 +129,7 @@ extension _BString.Chunk { return .inline(r) } - let desired = _BString.Ingester.desiredNextChunkSize(remaining: sum) + let desired = BigString.Ingester.desiredNextChunkSize(remaining: sum) guard sum - desired + Self.maxSlicingError <= Self.maxUTF8Count else { return .large } if desired <= offset { diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Breaks.swift similarity index 97% rename from Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift rename to Sources/RopeModule/BigString/Chunk/BigString+Chunk+Breaks.swift index fe85a115..abaa74b1 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Breaks.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Breaks.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { @inline(__always) var hasBreaks: Bool { counts.hasBreaks } @@ -41,7 +41,7 @@ extension _BString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { var immediateLastBreakState: _CharacterRecognizer? { guard hasBreaks else { return nil } return _CharacterRecognizer(partialCharacter: string[lastBreak...]) diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Counts.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Counts.swift similarity index 94% rename from Sources/RopeModule/BString/Chunk/_BString+Chunk+Counts.swift rename to Sources/RopeModule/BigString/Chunk/BigString+Chunk+Counts.swift index 803416c6..da4a4357 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Counts.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Counts.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { struct Counts: Equatable { /// The number of UTF-8 code units within this chunk. var utf8: UInt8 @@ -87,7 +87,7 @@ extension _BString.Chunk { init(_ slice: Slice) { let c = slice.string.utf8.count - precondition(c <= _BString.Chunk.maxUTF8Count) + precondition(c <= BigString.Chunk.maxUTF8Count) self.init( utf8: slice.string.utf8.count, utf16: slice.string.utf16.count, @@ -100,7 +100,7 @@ extension _BString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk.Counts { +extension BigString.Chunk.Counts { var characters: Int { get { Int(_characters) } set { _characters = UInt8(newValue) } @@ -121,12 +121,12 @@ extension _BString.Chunk.Counts { } func hasSpaceToMerge(_ other: Self) -> Bool { - Int(utf8) + Int(other.utf8) <= _BString.Chunk.maxUTF8Count + Int(utf8) + Int(other.utf8) <= BigString.Chunk.maxUTF8Count } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk.Counts { +extension BigString.Chunk.Counts { mutating func append(_ other: Self) { assert(hasSpaceToMerge(other)) diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Description.swift similarity index 97% rename from Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift rename to Sources/RopeModule/BigString/Chunk/BigString+Chunk+Description.swift index f97d1c3c..75b9d164 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Description.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Description.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk: CustomStringConvertible { +extension BigString.Chunk: CustomStringConvertible { var description: String { let counts = """ ❨\(utf8Count)⋅\(utf16Count)⋅\(unicodeScalarCount)⋅\(characterCount)❩ diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift similarity index 99% rename from Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift rename to Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift index f97e128c..f4877cd9 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by Characters.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift @@ -19,7 +19,7 @@ extension UInt8 { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { func characterDistance(from start: String.Index, to end: String.Index) -> Int { let firstBreak = self.firstBreak let (start, a) = start < firstBreak ? (firstBreak, 1) : (start, 0) diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by UTF16.swift similarity index 96% rename from Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift rename to Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by UTF16.swift index 0982ab6d..e17349a0 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Indexing by UTF16.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by UTF16.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { /// UTF-16 index lookup. func index(at utf8Offset: Int, utf16TrailingSurrogate: Bool) -> String.Index { var index = string._utf8Index(at: utf8Offset) diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift similarity index 94% rename from Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift rename to Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift index 8f704210..7dcfc286 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+CordElement.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift @@ -12,11 +12,11 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk: _RopeElement { - typealias Summary = _BString.Summary +extension BigString.Chunk: _RopeElement { + typealias Summary = BigString.Summary typealias Index = String.Index - var summary: _BString.Summary { + var summary: BigString.Summary { Summary(self) } @@ -65,7 +65,7 @@ extension _BString.Chunk: _RopeElement { guard !right.isEmpty else { return true } guard self.isUndersized || right.isUndersized else { return false } let sum = self.utf8Count + right.utf8Count - let desired = _BString.Ingester.desiredNextChunkSize(remaining: sum) + let desired = BigString.Ingester.desiredNextChunkSize(remaining: sum) precondition(desired != self.utf8Count) if desired < self.utf8Count { @@ -89,7 +89,7 @@ extension _BString.Chunk: _RopeElement { guard !left.isEmpty else { return true } guard left.isUndersized || self.isUndersized else { return false } let sum = left.utf8Count + self.utf8Count - let desired = _BString.Ingester.desiredNextChunkSize(remaining: sum) + let desired = BigString.Ingester.desiredNextChunkSize(remaining: sum) precondition(desired != self.utf8Count) if desired < self.utf8Count { @@ -117,7 +117,7 @@ extension _BString.Chunk: _RopeElement { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { static func _redistributeData( _ left: inout Self, _ right: inout Self, diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Splitting.swift similarity index 99% rename from Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift rename to Sources/RopeModule/BigString/Chunk/BigString+Chunk+Splitting.swift index 73898e4e..dcff9e3f 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk+Splitting.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Splitting.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { func splitCounts(at i: String.Index) -> (left: Counts, right: Counts) { precondition(i <= string.endIndex) guard i < string.endIndex else { diff --git a/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift similarity index 94% rename from Sources/RopeModule/BString/Chunk/_BString+Chunk.swift rename to Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift index aeddaa60..ac9a5111 100644 --- a/Sources/RopeModule/BString/Chunk/_BString+Chunk.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { struct Chunk { typealias Slice = (string: Substring, characters: Int, prefix: Int, suffix: Int) @@ -47,7 +47,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { @inline(__always) static var maxUTF8Count: Int { 255 } @@ -59,7 +59,7 @@ extension _BString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { @inline(__always) mutating func take() -> Self { let r = self @@ -76,7 +76,7 @@ extension _BString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { @inline(__always) var characterCount: Int { counts.characters } @@ -100,7 +100,7 @@ extension _BString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { var availableSpace: Int { Swift.max(0, Self.maxUTF8Count - utf8Count) } mutating func clear() { @@ -110,7 +110,7 @@ extension _BString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { func hasSpaceToMerge(_ other: some StringProtocol) -> Bool { utf8Count + other.utf8.count <= Self.maxUTF8Count } diff --git a/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift b/Sources/RopeModule/BigString/Conformances/BigString+BidirectionalCollection.swift similarity index 88% rename from Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift rename to Sources/RopeModule/BigString/Conformances/BigString+BidirectionalCollection.swift index 8cb61c2d..22acb9d4 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+BidirectionalCollection.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+BidirectionalCollection.swift @@ -12,11 +12,11 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: BidirectionalCollection { - public typealias SubSequence = _BSubstring +extension BigString: BidirectionalCollection { + public typealias SubSequence = BigSubstring public var isEmpty: Bool { - rope.summary.isZero + _rope.summary.isZero } public var startIndex: Index { @@ -56,13 +56,13 @@ extension _BString: BidirectionalCollection { self[character: position] } - public subscript(bounds: Range) -> _BSubstring { - _BSubstring(self, in: bounds) + public subscript(bounds: Range) -> BigSubstring { + BigSubstring(self, in: bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { public func index(roundingDown i: Index) -> Index { characterIndex(roundingDown: i) } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift b/Sources/RopeModule/BigString/Conformances/BigString+Comparable.swift similarity index 98% rename from Sources/RopeModule/BString/Conformances/_BString+Comparable.swift rename to Sources/RopeModule/BigString/Conformances/BigString+Comparable.swift index deb4677c..69a34944 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Comparable.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+Comparable.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: Comparable { +extension BigString: Comparable { public static func < (left: Self, right: Self) -> Bool { // FIXME: Implement properly normalized comparisons & hashing. // This is somewhat tricky as we shouldn't just normalize individual pieces of the string @@ -37,7 +37,7 @@ extension _BString: Comparable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { /// 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 { diff --git a/Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift b/Sources/RopeModule/BigString/Conformances/BigString+CustomDebugStringConvertible.swift similarity index 92% rename from Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift rename to Sources/RopeModule/BigString/Conformances/BigString+CustomDebugStringConvertible.swift index 75b738c5..f5baca1f 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+CustomDebugStringConvertible.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+CustomDebugStringConvertible.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: CustomDebugStringConvertible { +extension BigString: CustomDebugStringConvertible { public var debugDescription: String { description.debugDescription } diff --git a/Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift b/Sources/RopeModule/BigString/Conformances/BigString+CustomStringConvertible.swift similarity index 92% rename from Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift rename to Sources/RopeModule/BigString/Conformances/BigString+CustomStringConvertible.swift index 1b6f1696..6bec8792 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+CustomStringConvertible.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+CustomStringConvertible.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: CustomStringConvertible { +extension BigString: CustomStringConvertible { public var description: String { String(self) } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift b/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift similarity index 78% rename from Sources/RopeModule/BString/Conformances/_BString+Equatable.swift rename to Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift index e5f77ac5..2d650646 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Equatable.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift @@ -12,14 +12,14 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { public func isIdentical(to other: Self) -> Bool { - self.rope.isIdentical(to: other.rope) + self._rope.isIdentical(to: other._rope) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: Equatable { +extension BigString: Equatable { public static func ==(left: Self, right: Self) -> Bool { // FIXME: Implement properly normalized comparisons & hashing. // This is somewhat tricky as we shouldn't just normalize individual pieces of the string @@ -29,8 +29,8 @@ extension _BString: Equatable { if left.isIdentical(to: right) { return true } guard left.characterCount == right.characterCount else { return false } // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. - var it1 = left.makeCharacterIterator() - var it2 = right.makeCharacterIterator() + var it1 = left.makeIterator() + var it2 = right.makeIterator() var a: Character? = nil var b: Character? = nil repeat { @@ -43,30 +43,12 @@ extension _BString: Equatable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - @available(*, deprecated, renamed: "==") - internal func characterwiseIsEqual(to other: Self) -> Bool { - self == other - } - - @available(*, deprecated, message: "Use _BSubstring.==") - internal static func characterwiseIsEqual( - _ left: Self, - in leftRange: Range, - to right: Self, - in rightRange: Range - ) -> Bool { - _BSubstring(_unchecked: left, in: leftRange) == _BSubstring(_unchecked: right, in: rightRange) - } -} - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { /// Lexicographically compare the UTF-8 representations of `left` to `right`, returning a Boolean /// value indicating whether `left` is equal to `right`. internal static func utf8IsEqual(_ left: Self, to right: Self) -> Bool { if left.isIdentical(to: right) { return true } - guard left.rope.summary == right.rope.summary else { return false } + guard left._rope.summary == right._rope.summary else { 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 @@ -102,8 +84,8 @@ extension _BString { guard leftUTF8Count == rightUTF8Count else { return false } var remaining = leftUTF8Count - var it1 = _BString.UTF8View.Iterator(_base: left, from: leftRange.lowerBound) - var it2 = _BString.UTF8View.Iterator(_base: right, from: rightRange.lowerBound) + var it1 = BigString.UTF8View.Iterator(_base: left, from: leftRange.lowerBound) + var it2 = BigString.UTF8View.Iterator(_base: right, from: rightRange.lowerBound) while remaining > 0 { let consumed = it1.next(maximumCount: remaining) { b1 in diff --git a/Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift b/Sources/RopeModule/BigString/Conformances/BigString+ExpressibleByStringLiteral.swift similarity index 92% rename from Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift rename to Sources/RopeModule/BigString/Conformances/BigString+ExpressibleByStringLiteral.swift index 6c2bc6c4..c804216e 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+ExpressibleByStringLiteral.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+ExpressibleByStringLiteral.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: ExpressibleByStringLiteral { +extension BigString: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(value) } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift b/Sources/RopeModule/BigString/Conformances/BigString+Hashing.swift similarity index 73% rename from Sources/RopeModule/BString/Conformances/_BString+Hashing.swift rename to Sources/RopeModule/BigString/Conformances/BigString+Hashing.swift index 2e95cc2a..958084f2 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Hashing.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+Hashing.swift @@ -12,21 +12,21 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: Hashable { +extension BigString: Hashable { public func hash(into hasher: inout Hasher) { hashCharacters(into: &hasher) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { internal func hashCharacters(into hasher: inout Hasher) { // 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. :-/ - var it = self.makeCharacterIterator() + var it = self.makeIterator() while let character = it.next() { let s = String(character) s._withNFCCodeUnits { hasher.combine($0) } @@ -34,26 +34,9 @@ extension _BString { hasher.combine(0xFF as UInt8) } - internal func hashCharacters(into hasher: inout Hasher, from range: Range) { - var it = self.makeCharacterIterator(from: range.lowerBound) - let endOffset = range.upperBound.utf8Offset - while let character = it.next() { - var s = String(character) - if it.utf8Offset > endOffset { - let i = s.unicodeScalars._index(roundingDown: s._utf8Index(at: it.utf8Offset - endOffset)) - s.removeSubrange(i...) - } - s._withNFCCodeUnits { hasher.combine($0) } - if it.utf8Offset >= endOffset { - break - } - } - hasher.combine(0xFF as UInt8) - } - /// Feed the UTF-8 encoding of `self` into hasher, with a terminating byte. internal func hashUTF8(into hasher: inout Hasher) { - for chunk in self.rope { + for chunk in self._rope { var string = chunk.string string.withUTF8 { hasher.combine(bytes: .init($0)) diff --git a/Sources/RopeModule/BString/Conformances/_BString+LosslessStringConvertible.swift b/Sources/RopeModule/BigString/Conformances/BigString+LosslessStringConvertible.swift similarity index 92% rename from Sources/RopeModule/BString/Conformances/_BString+LosslessStringConvertible.swift rename to Sources/RopeModule/BigString/Conformances/BigString+LosslessStringConvertible.swift index b7b77efd..4e7af744 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+LosslessStringConvertible.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+LosslessStringConvertible.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: LosslessStringConvertible { +extension BigString: LosslessStringConvertible { // init?(_: String) is implemented by RangeReplaceableCollection.init(_:) } diff --git a/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift b/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift similarity index 72% rename from Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift rename to Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift index 8081bc4b..53b14d37 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+RangeReplaceableCollection.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift @@ -12,9 +12,9 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: RangeReplaceableCollection { +extension BigString: RangeReplaceableCollection { public init() { - self.init(rope: Rope()) + self.init(_rope: _Storage()) } public mutating func reserveCapacity(_ n: Int) { @@ -30,14 +30,14 @@ extension _BString: RangeReplaceableCollection { } else if S.self == Substring.self { let newElements = _identityCast(newElements, to: Substring.self) self._replaceSubrange(subrange, with: newElements) - } else if S.self == _BString.self { - let newElements = _identityCast(newElements, to: _BString.self) + } else if S.self == BigString.self { + let newElements = _identityCast(newElements, to: BigString.self) self._replaceSubrange(subrange, with: newElements) - } else if S.self == _BSubstring.self { - let newElements = _identityCast(newElements, to: _BSubstring.self) + } else if S.self == BigSubstring.self { + let newElements = _identityCast(newElements, to: BigSubstring.self) self._replaceSubrange(subrange, with: newElements) } else { - self._replaceSubrange(subrange, with: _BString(newElements)) + self._replaceSubrange(subrange, with: BigString(newElements)) } } @@ -54,13 +54,13 @@ extension _BString: RangeReplaceableCollection { } public mutating func replaceSubrange( - _ subrange: Range, with newElements: __owned _BString + _ subrange: Range, with newElements: __owned BigString ) { _replaceSubrange(subrange, with: newElements) } public mutating func replaceSubrange( - _ subrange: Range, with newElements: __owned _BSubstring + _ subrange: Range, with newElements: __owned BigSubstring ) { _replaceSubrange(subrange, with: newElements) } @@ -72,10 +72,10 @@ extension _BString: RangeReplaceableCollection { } 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) + } else if S.self == BigString.self { + self = _identityCast(elements, to: BigString.self) + } else if S.self == BigSubstring.self { + let elements = _identityCast(elements, to: BigSubstring.self) self.init(_from: elements) } else { self.init(_from: elements) @@ -90,20 +90,20 @@ extension _BString: RangeReplaceableCollection { self.init(_from: elements) } - public init(_ elements: _BString) { + public init(_ elements: BigString) { self = elements } - public init(_ elements: _BSubstring) { + public init(_ elements: BigSubstring) { self.init(_from: elements) } public init(repeating repeatedValue: Character, count: Int) { - self.init(repeating: _BString(String(repeatedValue)), count: count) + self.init(repeating: BigString(String(repeatedValue)), count: count) } public init(repeating repeatedValue: some StringProtocol, count: Int) { - self.init(repeating: _BString(repeatedValue), count: count) + self.init(repeating: BigString(repeatedValue), count: count) } public init(repeating value: Self, count: Int) { @@ -128,8 +128,8 @@ extension _BString: RangeReplaceableCollection { } } - public init(repeating value: _BSubstring, count: Int) { - self.init(repeating: _BString(value), count: count) + public init(repeating value: BigSubstring, count: Int) { + self.init(repeating: BigString(value), count: count) } public mutating func append(_ newElement: __owned Character) { @@ -143,14 +143,14 @@ extension _BString: RangeReplaceableCollection { } 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) + } else if S.self == BigString.self { + let newElements = _identityCast(newElements, to: BigString.self) append(contentsOf: newElements) - } else if S.self == _BSubstring.self { - let newElements = _identityCast(newElements, to: _BSubstring.self) + } else if S.self == BigSubstring.self { + let newElements = _identityCast(newElements, to: BigSubstring.self) append(contentsOf: newElements) } else { - append(contentsOf: _BString(newElements)) + append(contentsOf: BigString(newElements)) } } @@ -162,11 +162,11 @@ extension _BString: RangeReplaceableCollection { _append(contentsOf: newElements) } - public mutating func append(contentsOf newElements: __owned _BString) { + public mutating func append(contentsOf newElements: __owned BigString) { _append(contentsOf: newElements) } - public mutating func append(contentsOf newElements: __owned _BSubstring) { + public mutating func append(contentsOf newElements: __owned BigSubstring) { _append(contentsOf: newElements._base, in: newElements._bounds) } @@ -183,14 +183,14 @@ extension _BString: RangeReplaceableCollection { } else if S.self == Substring.self { let newElements = _identityCast(newElements, to: Substring.self) insert(contentsOf: newElements, at: i) - } else if S.self == _BString.self { - let newElements = _identityCast(newElements, to: _BString.self) + } else if S.self == BigString.self { + let newElements = _identityCast(newElements, to: BigString.self) insert(contentsOf: newElements, at: i) - } else if S.self == _BSubstring.self { - let newElements = _identityCast(newElements, to: _BSubstring.self) + } else if S.self == BigSubstring.self { + let newElements = _identityCast(newElements, to: BigSubstring.self) insert(contentsOf: newElements, at: i) } else { - insert(contentsOf: _BString(newElements), at: i) + insert(contentsOf: BigString(newElements), at: i) } } @@ -202,11 +202,11 @@ extension _BString: RangeReplaceableCollection { _insert(contentsOf: newElements, at: i) } - public mutating func insert(contentsOf newElements: __owned _BString, at i: Index) { + public mutating func insert(contentsOf newElements: __owned BigString, at i: Index) { _insert(contentsOf: newElements, at: i) } - public mutating func insert(contentsOf newElements: __owned _BSubstring, at i: Index) { + public mutating func insert(contentsOf newElements: __owned BigSubstring, at i: Index) { _insert(contentsOf: newElements._base, in: newElements._bounds, at: i) } @@ -220,7 +220,7 @@ extension _BString: RangeReplaceableCollection { } public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - self = _BString() + self = BigString() } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+Sequence.swift b/Sources/RopeModule/BigString/Conformances/BigString+Sequence.swift similarity index 66% rename from Sources/RopeModule/BString/Conformances/_BString+Sequence.swift rename to Sources/RopeModule/BigString/Conformances/BigString+Sequence.swift index 4c0d849f..ff2afcfb 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+Sequence.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+Sequence.swift @@ -12,60 +12,49 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: Sequence { +extension BigString: Sequence { public typealias Element = Character - @available(*, deprecated, renamed: "Iterator") - internal typealias CharacterIterator = Iterator - public func makeIterator() -> Iterator { Iterator(self) } - - internal func makeCharacterIterator() -> Iterator { - Iterator(self) - } - - internal func makeCharacterIterator(from index: Index) -> Iterator { - Iterator(self, from: index) - } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { public struct Iterator { - internal let _base: _BString + internal let _base: BigString internal var _utf8BaseOffset: Int - internal var _ropeIndex: Rope.Index + internal var _ropeIndex: _Storage.Index internal var _chunkIndex: String.Index internal var _next: String.Index - internal init(_ string: _BString) { + internal init(_ string: BigString) { self._base = string - self._ropeIndex = string.rope.startIndex - string.rope.ensureLeaf(in: &_ropeIndex) + self._ropeIndex = string._rope.startIndex + string._rope.ensureLeaf(in: &_ropeIndex) self._utf8BaseOffset = 0 - guard _ropeIndex < string.rope.endIndex else { + guard _ropeIndex < string._rope.endIndex else { _chunkIndex = "".startIndex _next = "".endIndex return } - let chunk = _base.rope[_ropeIndex] + let chunk = _base._rope[_ropeIndex] assert(chunk.firstBreak == chunk.string.startIndex) self._chunkIndex = chunk.firstBreak self._next = chunk.string[_chunkIndex...].index(after: _chunkIndex) } internal init( - _ string: _BString, + _ string: BigString, from start: Index ) { self._base = string self._utf8BaseOffset = start.utf8Offset if start == string.endIndex { - self._ropeIndex = string.rope.endIndex + self._ropeIndex = string._rope.endIndex self._chunkIndex = "".startIndex self._next = "".endIndex return @@ -74,13 +63,13 @@ extension _BString { self._ropeIndex = i._rope! self._utf8BaseOffset = i._utf8BaseOffset self._chunkIndex = i._chunkIndex - self._next = _base.rope[_ropeIndex].wholeCharacters.index(after: _chunkIndex) + self._next = _base._rope[_ropeIndex].wholeCharacters.index(after: _chunkIndex) } } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Iterator: IteratorProtocol { +extension BigString.Iterator: IteratorProtocol { public typealias Element = Character internal var isAtEnd: Bool { @@ -88,38 +77,38 @@ extension _BString.Iterator: IteratorProtocol { } internal var isAtStart: Bool { - _ropeIndex == _base.rope.startIndex && _chunkIndex._utf8Offset == 0 + _ropeIndex == _base._rope.startIndex && _chunkIndex._utf8Offset == 0 } internal var current: Element { assert(!isAtEnd) - let chunk = _base.rope[_ropeIndex] + let chunk = _base._rope[_ropeIndex] var str = String(chunk.string[_chunkIndex ..< _next]) if _next < chunk.string.endIndex { return Character(str) } - var i = _base.rope.index(after: _ropeIndex) - while i < _base.rope.endIndex { - let chunk = _base.rope[i] + var i = _base._rope.index(after: _ropeIndex) + while i < _base._rope.endIndex { + let chunk = _base._rope[i] let b = chunk.firstBreak str += chunk.string[.. Bool { guard !isAtEnd else { return false } - let chunk = _base.rope[_ropeIndex] + let chunk = _base._rope[_ropeIndex] if _next < chunk.string.endIndex { _chunkIndex = _next _next = chunk.wholeCharacters.index(after: _next) return true } var baseOffset = _utf8BaseOffset + chunk.utf8Count - var i = _base.rope.index(after: _ropeIndex) - while i < _base.rope.endIndex { - let chunk = _base.rope[i] + var i = _base._rope.index(after: _ropeIndex) + while i < _base._rope.endIndex { + let chunk = _base._rope[i] let b = chunk.firstBreak if b < chunk.string.endIndex { _ropeIndex = i @@ -129,14 +118,14 @@ extension _BString.Iterator: IteratorProtocol { return true } baseOffset += chunk.utf8Count - _base.rope.formIndex(after: &i) + _base._rope.formIndex(after: &i) } return false } mutating func stepBackward() -> Bool { if !isAtEnd { - let chunk = _base.rope[_ropeIndex] + let chunk = _base._rope[_ropeIndex] let i = chunk.firstBreak if _chunkIndex > i { _next = _chunkIndex @@ -146,9 +135,9 @@ extension _BString.Iterator: IteratorProtocol { } var i = _ropeIndex var baseOffset = _utf8BaseOffset - while i > _base.rope.startIndex { - _base.rope.formIndex(before: &i) - let chunk = _base.rope[i] + while i > _base._rope.startIndex { + _base._rope.formIndex(before: &i) + let chunk = _base._rope[i] baseOffset -= chunk.utf8Count if chunk.hasBreaks { _ropeIndex = i @@ -172,32 +161,32 @@ extension _BString.Iterator: IteratorProtocol { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Iterator { +extension BigString.Iterator { // The UTF-8 offset of the current position, from the start of the string. var utf8Offset: Int { _utf8BaseOffset + _chunkIndex._utf8Offset } - var index: _BString.Index { - _BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _chunkIndex) + var index: BigString.Index { + BigString.Index(baseUTF8Offset: _utf8BaseOffset, _rope: _ropeIndex, chunk: _chunkIndex) } - internal var nextIndex: _BString.Index { + internal var nextIndex: BigString.Index { assert(!isAtEnd) - let chunk = _base.rope[_ropeIndex] + let chunk = _base._rope[_ropeIndex] if _next < chunk.string.endIndex { - return _BString.Index(baseUTF8Offset: _utf8BaseOffset, rope: _ropeIndex, chunk: _next) + return BigString.Index(baseUTF8Offset: _utf8BaseOffset, _rope: _ropeIndex, chunk: _next) } - var i = _base.rope.index(after: _ropeIndex) + var i = _base._rope.index(after: _ropeIndex) var base = _utf8BaseOffset - while i < _base.rope.endIndex { - let chunk = _base.rope[i] + while i < _base._rope.endIndex { + let chunk = _base._rope[i] let b = chunk.firstBreak if b < chunk.string.endIndex { - return _BString.Index(baseUTF8Offset: base, rope: i, chunk: b) + return BigString.Index(baseUTF8Offset: base, _rope: i, chunk: b) } base += chunk.utf8Count - _base.rope.formIndex(after: &i) + _base._rope.formIndex(after: &i) } return _base.endIndex } @@ -207,31 +196,31 @@ extension _BString.Iterator { assert(!isAtEnd) let start = utf8Offset var end = _utf8BaseOffset - var chunk = _base.rope[_ropeIndex] + var chunk = _base._rope[_ropeIndex] if _next < chunk.string.endIndex { end += _next._utf8Offset return Range(uncheckedBounds: (start, end)) } end += chunk.utf8Count - var i = _base.rope.index(after: _ropeIndex) - while i < _base.rope.endIndex { - chunk = _base.rope[i] + var i = _base._rope.index(after: _ropeIndex) + while i < _base._rope.endIndex { + chunk = _base._rope[i] let b = chunk.firstBreak if b < chunk.string.endIndex { end += b._utf8Offset break } end += chunk.utf8Count - _base.rope.formIndex(after: &i) + _base._rope.formIndex(after: &i) } return Range(uncheckedBounds: (start, end)) } - func isAbove(_ index: _BString.Index) -> Bool { + func isAbove(_ index: BigString.Index) -> Bool { self.utf8Offset > index.utf8Offset } - func isBelow(_ index: _BString.Index) -> Bool { + func isBelow(_ index: BigString.Index) -> Bool { self.utf8Offset < index.utf8Offset } } diff --git a/Sources/RopeModule/BString/Conformances/_BString+TextOutputStream.swift b/Sources/RopeModule/BigString/Conformances/BigString+TextOutputStream.swift similarity index 87% rename from Sources/RopeModule/BString/Conformances/_BString+TextOutputStream.swift rename to Sources/RopeModule/BigString/Conformances/BigString+TextOutputStream.swift index 4e25e4f4..3fb8007a 100644 --- a/Sources/RopeModule/BString/Conformances/_BString+TextOutputStream.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+TextOutputStream.swift @@ -12,16 +12,16 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString: TextOutputStream { +extension BigString: 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 { +extension BigString: TextOutputStreamable { public func write(to target: inout some TextOutputStream) { - for chunk in rope { + for chunk in _rope { chunk.string.write(to: &target) } } diff --git a/Sources/RopeModule/BString/Operations/_BString+Append.swift b/Sources/RopeModule/BigString/Operations/BigString+Append.swift similarity index 67% rename from Sources/RopeModule/BString/Operations/_BString+Append.swift rename to Sources/RopeModule/BigString/Operations/BigString+Append.swift index cee94405..ec2d23ef 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Append.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Append.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { mutating func _append(contentsOf other: __owned Substring) { if other.isEmpty { return } if isEmpty { @@ -21,34 +21,34 @@ extension _BString { } var ingester = ingester(forInserting: other, at: endIndex, allowForwardPeek: true) - let last = rope.index(before: rope.endIndex) - if let final = rope[last].append(from: &ingester) { + let last = _rope.index(before: _rope.endIndex) + if let final = _rope[last].append(from: &ingester) { precondition(!final.isUndersized) - rope.append(final) + _rope.append(final) return } // Make a temp rope out of the rest of the chunks and then join the two trees together. if !ingester.isAtEnd { - var builder = Rope.Builder() + var builder = _Storage.Builder() while let chunk = ingester.nextWellSizedChunk() { precondition(!chunk.isUndersized) builder.append(chunk) } precondition(ingester.isAtEnd) - rope = Rope.join(rope, builder.finalize()) + _rope = _Storage.join(_rope, builder.finalize()) } } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { var _firstUnicodeScalar: Unicode.Scalar { assert(!isEmpty) - return rope.root.firstItem.value.string.unicodeScalars.first! + return _rope.root.firstItem.value.string.unicodeScalars.first! } - mutating func _append(contentsOf other: __owned _BString) { + mutating func _append(contentsOf other: __owned BigString) { guard !other.isEmpty else { return } guard !self.isEmpty else { self = other @@ -56,29 +56,29 @@ extension _BString { } let hint = other._firstUnicodeScalar - var other = other.rope + var other = other._rope var old = _CharacterRecognizer() var new = self._breakState(upTo: endIndex, nextScalarHint: hint) _ = other.resyncBreaks(old: &old, new: &new) _append(other) } - mutating func _append(contentsOf other: __owned _BString, in range: Range) { + mutating func _append(contentsOf other: __owned BigString, in range: Range) { guard !range._isEmptyUTF8 else { return } guard !self.isEmpty else { self = Self(_from: other, in: range) return } - var other = _BString(_from: other, in: range) + var other = BigString(_from: other, in: range) let hint = other._firstUnicodeScalar var old = _CharacterRecognizer() var new = self._breakState(upTo: endIndex, nextScalarHint: hint) - _ = other.rope.resyncBreaks(old: &old, new: &new) - _append(other.rope) + _ = other._rope.resyncBreaks(old: &old, new: &new) + _append(other._rope) } - mutating func prepend(contentsOf other: __owned _BString) { + mutating func prepend(contentsOf other: __owned BigString) { guard !other.isEmpty else { return } guard !self.isEmpty else { self = other @@ -87,11 +87,11 @@ extension _BString { let hint = self._firstUnicodeScalar var old = _CharacterRecognizer() var new = other._breakState(upTo: other.endIndex, nextScalarHint: hint) - _ = self.rope.resyncBreaks(old: &old, new: &new) - _prepend(other.rope) + _ = self._rope.resyncBreaks(old: &old, new: &new) + _prepend(other._rope) } - mutating func prepend(contentsOf other: __owned _BString, in range: Range) { + mutating func prepend(contentsOf other: __owned BigString, in range: Range) { guard !range._isEmptyUTF8 else { return } let extract = Self(_from: other, in: range) guard !self.isEmpty else { @@ -101,36 +101,36 @@ extension _BString { let hint = self._firstUnicodeScalar var old = _CharacterRecognizer() var new = extract._breakState(upTo: extract.endIndex, nextScalarHint: hint) - _ = self.rope.resyncBreaks(old: &old, new: &new) - _prepend(extract.rope) + _ = self._rope.resyncBreaks(old: &old, new: &new) + _prepend(extract._rope) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { var isUndersized: Bool { utf8Count < Chunk.minUTF8Count } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { /// Note: This assumes `other` already has the correct break positions. mutating func _append(_ other: __owned Chunk) { assert(!other.isEmpty) guard !self.isEmpty else { - self.rope.append(other) + self._rope.append(other) return } guard self.isUndersized || other.isUndersized else { - self.rope.append(other) + self._rope.append(other) return } var other = other - let last = self.rope.index(before: self.rope.endIndex) - if !self.rope[last].rebalance(nextNeighbor: &other) { + let last = self._rope.index(before: self._rope.endIndex) + if !self._rope[last].rebalance(nextNeighbor: &other) { assert(!other.isUndersized) - self.rope.append(other) + self._rope.append(other) } } @@ -138,25 +138,25 @@ extension _BString { mutating func _prepend(_ other: __owned Chunk) { assert(!other.isEmpty) guard !self.isEmpty else { - self.rope.prepend(other) + self._rope.prepend(other) return } guard self.isUndersized || other.isUndersized else { - self.rope.prepend(other) + self._rope.prepend(other) return } var other = other - let first = self.rope.startIndex - if !self.rope[first].rebalance(prevNeighbor: &other) { - self.rope.prepend(other) + let first = self._rope.startIndex + if !self._rope[first].rebalance(prevNeighbor: &other) { + self._rope.prepend(other) } } /// Note: This assumes `other` already has the correct break positions. - mutating func _append(_ other: __owned Rope) { + mutating func _append(_ other: __owned _Storage) { guard !other.isEmpty else { return } - guard !self.rope.isEmpty else { - self.rope = other + guard !self._rope.isEmpty else { + self._rope = other return } if other.isSingleton { @@ -164,20 +164,20 @@ extension _BString { return } if self.isUndersized { - assert(self.rope.isSingleton) - let chunk = self.rope.first! - self.rope = other + assert(self._rope.isSingleton) + let chunk = self._rope.first! + self._rope = other self._prepend(chunk) return } - self.rope = Rope.join(self.rope, other) + self._rope = _Storage.join(self._rope, other) } /// Note: This assumes `self` and `other` already have the correct break positions. - mutating func _prepend(_ other: __owned Rope) { + mutating func _prepend(_ other: __owned _Storage) { guard !other.isEmpty else { return } guard !self.isEmpty else { - self.rope = other + self._rope = other return } if other.isSingleton { @@ -185,13 +185,13 @@ extension _BString { return } if self.isUndersized { - assert(self.rope.isSingleton) - let chunk = self.rope.first! - self.rope = other + assert(self._rope.isSingleton) + let chunk = self._rope.first! + self._rope = other self._append(chunk) return } - self.rope = Rope.join(other, self.rope) + self._rope = _Storage.join(other, self._rope) } } diff --git a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift similarity index 73% rename from Sources/RopeModule/BString/Operations/_BString+Initializers.swift rename to Sources/RopeModule/BigString/Operations/BigString+Initializers.swift index c0da8835..a04495dc 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Initializers.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift @@ -12,14 +12,14 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { internal init(_from input: some StringProtocol) { - var builder = Rope.Builder() + var builder = _Storage.Builder() var ingester = Ingester(input) while let chunk = ingester.nextWellSizedChunk() { builder.append(chunk) } - self.rope = builder.finalize() + self._rope = builder.finalize() } internal init(_from input: some Sequence) { @@ -50,11 +50,11 @@ extension _BString { self = builder.finalize() } - internal init(_from other: _BSubstring) { + internal init(_from other: BigSubstring) { self.init(_from: other._base, in: other._bounds) } - internal init(_from other: _BSubstring.UnicodeScalarView) { + internal init(_from other: BigSubstring.UnicodeScalarView) { self.init(_from: other._base, in: other._bounds) } @@ -62,13 +62,13 @@ extension _BString { _from other: Self, in range: Range ) { - self.rope = other.rope.extract( + self._rope = other._rope.extract( from: range.lowerBound.utf8Offset, to: range.upperBound.utf8Offset, in: UTF8Metric()) var old = other._breakState(upTo: range.lowerBound) var new = _CharacterRecognizer() - _ = self.rope.resyncBreaks(old: &old, new: &new) + _ = self._rope.resyncBreaks(old: &old, new: &new) } internal init( @@ -76,35 +76,35 @@ extension _BString { in range: Range, state: inout _CharacterRecognizer ) { - self.rope = other.rope.extract( + self._rope = other._rope.extract( from: range.lowerBound.utf8Offset, to: range.upperBound.utf8Offset, in: UTF8Metric()) var old = other._breakState(upTo: range.lowerBound) var new = state - self.rope.resyncBreaksToEnd(old: &old, new: &new) + self._rope.resyncBreaksToEnd(old: &old, new: &new) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension String { - public init(_ big: _BString) { + public init(_ big: BigString) { guard !big.isEmpty else { self.init() return } - if big.rope.isSingleton { - self = big.rope[big.rope.startIndex].string + if big._rope.isSingleton { + self = big._rope[big._rope.startIndex].string return } self.init() self.reserveCapacity(big.utf8Count) - for chunk in big.rope { + for chunk in big._rope { self.append(chunk.string) } } - internal init(_from big: _BString, in range: Range<_BString.Index>) { + internal init(_from big: BigString, in range: Range) { self.init() var start = big.unicodeScalarIndex(roundingDown: range.lowerBound) @@ -121,28 +121,28 @@ extension String { let startRopeIndex = start._rope! let endRopeIndex = end._rope! if startRopeIndex == endRopeIndex { - self += big.rope[startRopeIndex].string[start._chunkIndex ..< end._chunkIndex] + self += big._rope[startRopeIndex].string[start._chunkIndex ..< end._chunkIndex] return } - self += big.rope[startRopeIndex].string[start._chunkIndex...] - var i = big.rope.index(after: startRopeIndex) + self += big._rope[startRopeIndex].string[start._chunkIndex...] + var i = big._rope.index(after: startRopeIndex) while i < endRopeIndex { - self += big.rope[i].string - big.rope.formIndex(after: &i) + self += big._rope[i].string + big._rope.formIndex(after: &i) } - self += big.rope[endRopeIndex].string[..=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { mutating func _insert( contentsOf other: __owned Substring, at index: Index @@ -31,20 +31,20 @@ extension _BString { var ingester = ingester(forInserting: other, at: index, allowForwardPeek: false) var ri = index._rope! var ci = index._chunkIndex - let r = rope.update(at: &ri) { $0.insert(from: &ingester, at: ci) } + let r = _rope.update(at: &ri) { $0.insert(from: &ingester, at: ci) } switch r { case let .inline(r): assert(ingester.isAtEnd) guard var r = r else { break } ci = String.Index(_utf8Offset: ci._utf8Offset + r.increment) - let i = Index(baseUTF8Offset: index._utf8BaseOffset, rope: ri, chunk: ci) + let i = Index(baseUTF8Offset: index._utf8BaseOffset, _rope: ri, chunk: ci) resyncBreaks(startingAt: i, old: &r.old, new: &r.new) case let .split(spawn: spawn, endStates: r): assert(ingester.isAtEnd) - rope.formIndex(after: &ri) - rope.insert(spawn, at: ri) + _rope.formIndex(after: &ri) + _rope.insert(spawn, at: ri) guard var r = r else { break } - let i = Index(_utf8Offset: index.utf8Offset + r.increment, rope: ri, chunkOffset: spawn.utf8Count) + let i = Index(_utf8Offset: index.utf8Offset + r.increment, _rope: ri, chunkOffset: spawn.utf8Count) resyncBreaks(startingAt: i, old: &r.old, new: &r.new) case .large: var builder = self.split(at: index, state: ingester.state) @@ -55,7 +55,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { mutating func _insert(contentsOf other: __owned Self, at index: Index) { guard index < endIndex else { precondition(index == endIndex, "Index out of bounds") @@ -66,9 +66,9 @@ extension _BString { self.prepend(contentsOf: other) return } - if other.rope.isSingleton { + if other._rope.isSingleton { // Fast path when `other` is tiny. - let chunk = other.rope.first! + let chunk = other._rope.first! insert(contentsOf: chunk.string, at: index) return } @@ -79,7 +79,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { mutating func _insert(contentsOf other: __owned Self, in range: Range, at index: Index) { guard index < endIndex else { precondition(index == endIndex, "Index out of bounds") diff --git a/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift b/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift similarity index 92% rename from Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift rename to Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift index 80035b5c..c662559b 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Managing Breaks.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { func _breakState( upTo index: Index, nextScalarHint: Unicode.Scalar? = nil @@ -24,9 +24,9 @@ extension _BString { let index = resolve(index, preferEnd: true) let ropeIndex = index._rope! let chunkIndex = index._chunkIndex - let chunk = rope[ropeIndex] + let chunk = _rope[ropeIndex] - guard ropeIndex > rope.startIndex || chunkIndex > chunk.string.startIndex else { + guard ropeIndex > _rope.startIndex || chunkIndex > chunk.string.startIndex else { return _CharacterRecognizer() } @@ -43,18 +43,18 @@ extension _BString { } // Find chunk that includes the start of the character. var ri = ropeIndex - while ri > rope.startIndex { - rope.formIndex(before: &ri) - if rope[ri].hasBreaks { break } + while ri > _rope.startIndex { + _rope.formIndex(before: &ri) + if _rope[ri].hasBreaks { break } } precondition(ri < ropeIndex) // Collect grapheme breaking state. - var state = _CharacterRecognizer(partialCharacter: rope[ri].suffix) - rope.formIndex(after: &ri) + var state = _CharacterRecognizer(partialCharacter: _rope[ri].suffix) + _rope.formIndex(after: &ri) while ri < ropeIndex { - state.consumePartialCharacter(rope[ri].string[...]) - rope.formIndex(after: &ri) + state.consumePartialCharacter(_rope[ri].string[...]) + _rope.formIndex(after: &ri) } state.consumePartialCharacter(chunk.string[.. (ropeIndex: Rope.Index, chunkIndex: String.Index)? { + ) -> (ropeIndex: _Storage.Index, chunkIndex: String.Index)? { guard index < endIndex else { return nil } let i = resolve(index, preferEnd: false) var ropeIndex = i._rope! var chunkIndex = i._chunkIndex - let end = rope.mutatingForEach(from: &ropeIndex) { chunk in + let end = _rope.mutatingForEach(from: &ropeIndex) { chunk in let start = chunkIndex chunkIndex = String.Index(_utf8Offset: 0) if let i = chunk.resyncBreaks(startingAt: start, old: &old, new: &new) { @@ -100,7 +100,7 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Rope { +extension BigString._Storage { mutating func resyncBreaks( old: inout _CharacterRecognizer, new: inout _CharacterRecognizer @@ -158,7 +158,7 @@ extension _BString.Rope { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.Chunk { +extension BigString.Chunk { /// Resyncronize chunk metadata with the (possibly) reshuffled grapheme /// breaks after an insertion that ended at `index`. /// diff --git a/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift b/Sources/RopeModule/BigString/Operations/BigString+RemoveSubrange.swift similarity index 86% rename from Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift rename to Sources/RopeModule/BigString/Operations/BigString+RemoveSubrange.swift index 475d86ed..32d1ba68 100644 --- a/Sources/RopeModule/BString/Operations/_BString+RemoveSubrange.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+RemoveSubrange.swift @@ -12,18 +12,18 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { mutating func _removeSubrange(_ bounds: Range) { precondition(bounds.upperBound <= endIndex, "Index out of bounds") if bounds.isEmpty { return } let lower = bounds.lowerBound.utf8Offset let upper = bounds.upperBound.utf8Offset - rope.removeSubrange(lower ..< upper, in: UTF8Metric()) + _rope.removeSubrange(lower ..< upper, in: UTF8Metric()) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { mutating func removeCharacter(at i: Index) -> Character { let start = self.resolve(i, preferEnd: false) let (character, end) = self._character(at: start) @@ -36,10 +36,10 @@ extension _BString { let start = unicodeScalarIndex(roundingDown: i) let ropeIndex = start._rope! let chunkIndex = start._chunkIndex - let chunk = rope[ropeIndex] + let chunk = _rope[ropeIndex] let scalar = chunk.string.unicodeScalars[chunkIndex] let next = chunk.string.unicodeScalars.index(after: chunkIndex) - let end = Index(baseUTF8Offset: start._utf8BaseOffset, rope: ropeIndex, chunk: next) + let end = Index(baseUTF8Offset: start._utf8BaseOffset, _rope: ropeIndex, chunk: next) self.removeSubrange(start ..< end) return scalar } diff --git a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift b/Sources/RopeModule/BigString/Operations/BigString+ReplaceSubrange.swift similarity index 93% rename from Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift rename to Sources/RopeModule/BigString/Operations/BigString+ReplaceSubrange.swift index 45ce4195..93d6f823 100644 --- a/Sources/RopeModule/BString/Operations/_BString+ReplaceSubrange.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+ReplaceSubrange.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { mutating func _replaceSubrange(_ range: Range, with newElements: some StringProtocol) { precondition(range.upperBound <= endIndex, "Index out of bounds") if range.isEmpty { @@ -25,7 +25,7 @@ extension _BString { self = builder.finalize() } - mutating func _replaceSubrange(_ range: Range, with newElements: _BString) { + mutating func _replaceSubrange(_ range: Range, with newElements: BigString) { precondition(range.upperBound <= endIndex, "Index out of bounds") if range.isEmpty { insert(contentsOf: newElements, at: range.lowerBound) @@ -38,14 +38,14 @@ extension _BString { mutating func _replaceSubrange( _ targetRange: Range, - with newElements: _BSubstring + with newElements: BigSubstring ) { _replaceSubrange(targetRange, with: newElements._base, in: newElements._bounds) } mutating func _replaceSubrange( _ targetRange: Range, - with newElements: _BString, + with newElements: BigString, in sourceRange: Range ) { if sourceRange._isEmptyUTF8 { @@ -74,7 +74,7 @@ extension _BString { let startState = _breakState(upTo: range.lowerBound) let endState = _breakState(upTo: range.upperBound) - let b = rope.builder(removing: lower ..< upper, in: UTF8Metric()) + let b = _rope.builder(removing: lower ..< upper, in: UTF8Metric()) return Builder(base: b, prefixEndState: startState, suffixStartState: endState) } } diff --git a/Sources/RopeModule/BString/Operations/_BString+Split.swift b/Sources/RopeModule/BigString/Operations/BigString+Split.swift similarity index 79% rename from Sources/RopeModule/BString/Operations/_BString+Split.swift rename to Sources/RopeModule/BigString/Operations/BigString+Split.swift index 91f9e008..e3ec13ae 100644 --- a/Sources/RopeModule/BString/Operations/_BString+Split.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Split.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { mutating func split( at index: Index ) -> Builder { @@ -31,11 +31,11 @@ extension _BString { return builder } - mutating func _ropeBuilder(at index: Index) -> Rope.Builder { - if let ri = index._rope, rope.isValid(ri) { - return rope.split(at: ri, index._chunkIndex) + mutating func _ropeBuilder(at index: Index) -> _Storage.Builder { + if let ri = index._rope, _rope.isValid(ri) { + return _rope.split(at: ri, index._chunkIndex) } - return rope.builder(splittingAt: index.utf8Offset, in: UTF8Metric()) + return _rope.builder(splittingAt: index.utf8Offset, in: UTF8Metric()) } } diff --git a/Sources/RopeModule/BString/Operations/Range+_BString.swift b/Sources/RopeModule/BigString/Operations/Range+BigString.swift similarity index 94% rename from Sources/RopeModule/BString/Operations/Range+_BString.swift rename to Sources/RopeModule/BigString/Operations/Range+BigString.swift index a8361fa4..6eb38a59 100644 --- a/Sources/RopeModule/BString/Operations/Range+_BString.swift +++ b/Sources/RopeModule/BigString/Operations/Range+BigString.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension Range<_BString.Index> { +extension Range { internal var _isEmptyUTF8: Bool { lowerBound.utf8Offset == upperBound.utf8Offset } diff --git a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift b/Sources/RopeModule/BigString/Views/BigString+UTF16View.swift similarity index 76% rename from Sources/RopeModule/BString/Views/_BString+UTF16View.swift rename to Sources/RopeModule/BigString/Views/BigString+UTF16View.swift index 76e405e0..e3c7e3d9 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF16View.swift +++ b/Sources/RopeModule/BigString/Views/BigString+UTF16View.swift @@ -12,12 +12,12 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { public struct UTF16View: Sendable { - var _base: _BString + var _base: BigString @inline(__always) - init(_base: _BString) { + init(_base: BigString) { self._base = _base } } @@ -33,9 +33,9 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF16View: Equatable { +extension BigString.UTF16View: Equatable { public static func ==(left: Self, right: Self) -> Bool { - _BString.utf8IsEqual(left._base, to: right._base) + BigString.utf8IsEqual(left._base, to: right._base) } public func isIdentical(to other: Self) -> Bool { @@ -44,21 +44,21 @@ extension _BString.UTF16View: Equatable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF16View: Hashable { +extension BigString.UTF16View: Hashable { public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF16View: Sequence { +extension BigString.UTF16View: Sequence { public typealias Element = UInt16 public struct Iterator { - internal let _base: _BString - internal var _index: _BString.Index + internal let _base: BigString + internal var _index: BigString.Index - internal init(_base: _BString, from start: _BString.Index) { + internal init(_base: BigString, from start: BigString.Index) { self._base = _base self._index = _base.utf16Index(roundingDown: start) } @@ -70,23 +70,23 @@ extension _BString.UTF16View: Sequence { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF16View.Iterator: IteratorProtocol { +extension BigString.UTF16View.Iterator: IteratorProtocol { public typealias Element = UInt16 public mutating func next() -> UInt16? { guard _index < _base.endIndex else { return nil } let ri = _index._rope! var ci = _index._chunkIndex - let chunk = _base.rope[ri] + let chunk = _base._rope[ri] let result = chunk.string.utf16[ci] chunk.string.utf16.formIndex(after: &ci) if ci < chunk.string.endIndex { - _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) + _index = BigString.Index(baseUTF8Offset: _index._utf8BaseOffset, _rope: ri, chunk: ci) } else { - _index = _BString.Index( + _index = BigString.Index( baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, - rope: _base.rope.index(after: ri), + _rope: _base._rope.index(after: ri), chunk: String.Index(_utf8Offset: 0)) } return result @@ -94,9 +94,9 @@ extension _BString.UTF16View.Iterator: IteratorProtocol { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF16View: BidirectionalCollection { - public typealias Index = _BString.Index - public typealias SubSequence = _BSubstring.UTF16View +extension BigString.UTF16View: BidirectionalCollection { + public typealias Index = BigString.Index + public typealias SubSequence = BigSubstring.UTF16View @inline(__always) public var startIndex: Index { _base.startIndex } @@ -133,13 +133,13 @@ extension _BString.UTF16View: BidirectionalCollection { _base[utf16: position] } - public subscript(bounds: Range) -> _BSubstring.UTF16View { - _BSubstring.UTF16View(_base, in: bounds) + public subscript(bounds: Range) -> BigSubstring.UTF16View { + BigSubstring.UTF16View(_base, in: bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF16View { +extension BigString.UTF16View { public func index(roundingDown i: Index) -> Index { _base.utf16Index(roundingDown: i) } diff --git a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift b/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift similarity index 78% rename from Sources/RopeModule/BString/Views/_BString+UTF8View.swift rename to Sources/RopeModule/BigString/Views/BigString+UTF8View.swift index 582e0d6f..9428ae6c 100644 --- a/Sources/RopeModule/BString/Views/_BString+UTF8View.swift +++ b/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift @@ -12,12 +12,12 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { public struct UTF8View: Sendable { - var _base: _BString + var _base: BigString @inline(__always) - init(_base: _BString) { + init(_base: BigString) { self._base = _base } } @@ -33,9 +33,9 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF8View: Equatable { +extension BigString.UTF8View: Equatable { public static func ==(left: Self, right: Self) -> Bool { - _BString.utf8IsEqual(left._base, to: right._base) + BigString.utf8IsEqual(left._base, to: right._base) } public func isIdentical(to other: Self) -> Bool { @@ -44,21 +44,21 @@ extension _BString.UTF8View: Equatable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF8View: Hashable { +extension BigString.UTF8View: Hashable { public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF8View: Sequence { +extension BigString.UTF8View: Sequence { public typealias Element = UInt8 public struct Iterator { - internal let _base: _BString - internal var _index: _BString.Index + internal let _base: BigString + internal var _index: BigString.Index - internal init(_base: _BString, from start: _BString.Index) { + internal init(_base: BigString, from start: BigString.Index) { self._base = _base self._index = _base.utf8Index(roundingDown: start) } @@ -70,7 +70,7 @@ extension _BString.UTF8View: Sequence { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF8View.Iterator: IteratorProtocol { +extension BigString.UTF8View.Iterator: IteratorProtocol { public typealias Element = UInt8 public mutating func next() -> UInt8? { @@ -78,16 +78,16 @@ extension _BString.UTF8View.Iterator: IteratorProtocol { // Hand-optimized from `_base.subscript(utf8:)` and `_base.utf8Index(after:)`. let ri = _index._rope! var ci = _index._chunkIndex - let chunk = _base.rope[ri] + let chunk = _base._rope[ri] let result = chunk.string.utf8[ci] chunk.string.utf8.formIndex(after: &ci) if ci < chunk.string.endIndex { - _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) + _index = BigString.Index(baseUTF8Offset: _index._utf8BaseOffset, _rope: ri, chunk: ci) } else { - _index = _BString.Index( + _index = BigString.Index( baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, - rope: _base.rope.index(after: ri), + _rope: _base._rope.index(after: ri), chunk: String.Index(_utf8Offset: 0)) } return result @@ -105,7 +105,7 @@ extension _BString.UTF8View.Iterator: IteratorProtocol { let ri = _index._rope! var ci = _index._utf8ChunkOffset var utf8Offset = _index.utf8Offset - var string = _base.rope[ri].string + var string = _base._rope[ri].string let (haveMore, result) = string.withUTF8 { buffer in let slice = buffer[ci...].prefix(maximumCount) assert(!slice.isEmpty) @@ -116,11 +116,11 @@ extension _BString.UTF8View.Iterator: IteratorProtocol { return (ci < buffer.count, result) } if haveMore { - _index = _BString.Index(_utf8Offset: utf8Offset, rope: ri, chunkOffset: ci) + _index = BigString.Index(_utf8Offset: utf8Offset, _rope: ri, chunkOffset: ci) } else { - _index = _BString.Index( + _index = BigString.Index( baseUTF8Offset: _index._utf8BaseOffset + string.utf8.count, - rope: _base.rope.index(after: ri), + _rope: _base._rope.index(after: ri), chunk: String.Index(_utf8Offset: 0)) } return result @@ -130,9 +130,9 @@ extension _BString.UTF8View.Iterator: IteratorProtocol { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF8View: BidirectionalCollection { - public typealias Index = _BString.Index - public typealias SubSequence = _BSubstring.UTF8View +extension BigString.UTF8View: BidirectionalCollection { + public typealias Index = BigString.Index + public typealias SubSequence = BigSubstring.UTF8View @inline(__always) public var startIndex: Index { _base.startIndex } @@ -169,13 +169,13 @@ extension _BString.UTF8View: BidirectionalCollection { _base[utf8: position] } - public subscript(bounds: Range) -> _BSubstring.UTF8View { - _BSubstring.UTF8View(_base, in: bounds) + public subscript(bounds: Range) -> BigSubstring.UTF8View { + BigSubstring.UTF8View(_base, in: bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UTF8View { +extension BigString.UTF8View { public func index(roundingDown i: Index) -> Index { _base.utf8Index(roundingDown: i) } diff --git a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/Views/BigString+UnicodeScalarView.swift similarity index 67% rename from Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift rename to Sources/RopeModule/BigString/Views/BigString+UnicodeScalarView.swift index f1789383..18aea1ac 100644 --- a/Sources/RopeModule/BString/Views/_BString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/Views/BigString+UnicodeScalarView.swift @@ -12,12 +12,12 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { +extension BigString { public struct UnicodeScalarView: Sendable { - var _base: _BString + var _base: BigString @inline(__always) - init(_base: _BString) { + init(_base: BigString) { self._base = _base } } @@ -40,36 +40,36 @@ extension _BString { } } - public init(_ view: _BString.UnicodeScalarView) { + public init(_ view: BigString.UnicodeScalarView) { self = view._base } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView: ExpressibleByStringLiteral { +extension BigString.UnicodeScalarView: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(value.unicodeScalars) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView: CustomStringConvertible { +extension BigString.UnicodeScalarView: CustomStringConvertible { public var description: String { String(_base) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView: CustomDebugStringConvertible { +extension BigString.UnicodeScalarView: CustomDebugStringConvertible { public var debugDescription: String { description.debugDescription } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView: Equatable { +extension BigString.UnicodeScalarView: Equatable { public static func ==(left: Self, right: Self) -> Bool { - _BString.utf8IsEqual(left._base, to: right._base) + BigString.utf8IsEqual(left._base, to: right._base) } public func isIdentical(to other: Self) -> Bool { @@ -78,21 +78,21 @@ extension _BString.UnicodeScalarView: Equatable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView: Hashable { +extension BigString.UnicodeScalarView: Hashable { public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView: Sequence { +extension BigString.UnicodeScalarView: Sequence { public typealias Element = UnicodeScalar public struct Iterator { - internal let _base: _BString - internal var _index: _BString.Index + internal let _base: BigString + internal var _index: BigString.Index - internal init(_base: _BString, from start: _BString.Index) { + internal init(_base: BigString, from start: BigString.Index) { self._base = _base self._index = _base.unicodeScalarIndex(roundingDown: start) } @@ -104,23 +104,23 @@ extension _BString.UnicodeScalarView: Sequence { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView.Iterator: IteratorProtocol { +extension BigString.UnicodeScalarView.Iterator: IteratorProtocol { public typealias Element = UnicodeScalar public mutating func next() -> UnicodeScalar? { guard _index < _base.endIndex else { return nil } let ri = _index._rope! var ci = _index._chunkIndex - let chunk = _base.rope[ri] + let chunk = _base._rope[ri] let result = chunk.string.unicodeScalars[ci] chunk.string.unicodeScalars.formIndex(after: &ci) if ci < chunk.string.endIndex { - _index = _BString.Index(baseUTF8Offset: _index._utf8BaseOffset, rope: ri, chunk: ci) + _index = BigString.Index(baseUTF8Offset: _index._utf8BaseOffset, _rope: ri, chunk: ci) } else { - _index = _BString.Index( + _index = BigString.Index( baseUTF8Offset: _index._utf8BaseOffset + chunk.utf8Count, - rope: _base.rope.index(after: ri), + _rope: _base._rope.index(after: ri), chunk: String.Index(_utf8Offset: 0)) } return result @@ -128,9 +128,9 @@ extension _BString.UnicodeScalarView.Iterator: IteratorProtocol { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView: BidirectionalCollection { - public typealias Index = _BString.Index - public typealias SubSequence = _BSubstring.UnicodeScalarView +extension BigString.UnicodeScalarView: BidirectionalCollection { + public typealias Index = BigString.Index + public typealias SubSequence = BigSubstring.UnicodeScalarView @inline(__always) public var startIndex: Index { _base.startIndex } @@ -167,13 +167,13 @@ extension _BString.UnicodeScalarView: BidirectionalCollection { _base[unicodeScalar: position] } - public subscript(bounds: Range) -> _BSubstring.UnicodeScalarView { - _BSubstring.UnicodeScalarView(_base, in: bounds) + public subscript(bounds: Range) -> BigSubstring.UnicodeScalarView { + BigSubstring.UnicodeScalarView(_base, in: bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView { +extension BigString.UnicodeScalarView { public func index(roundingDown i: Index) -> Index { _base.unicodeScalarIndex(roundingDown: i) } @@ -184,9 +184,9 @@ extension _BString.UnicodeScalarView { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString.UnicodeScalarView: RangeReplaceableCollection { +extension BigString.UnicodeScalarView: RangeReplaceableCollection { public init() { - self._base = _BString() + self._base = BigString() } public mutating func reserveCapacity(_ n: Int) { @@ -202,14 +202,14 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } 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) + } else if C.self == BigString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) _base._replaceSubrange(subrange, with: newElements._base) - } else if C.self == _BSubstring.UnicodeScalarView.self { - let newElements = _identityCast(newElements, to: _BSubstring.UnicodeScalarView.self) + } else if C.self == BigSubstring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigSubstring.UnicodeScalarView.self) _base._replaceSubrange(subrange, with: newElements._base, in: newElements._bounds) } else { - _base._replaceSubrange(subrange, with: _BString(_from: newElements)) + _base._replaceSubrange(subrange, with: BigString(_from: newElements)) } } @@ -226,13 +226,13 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } public mutating func replaceSubrange( - _ subrange: Range, with newElements: __owned _BString.UnicodeScalarView + _ subrange: Range, with newElements: __owned BigString.UnicodeScalarView ) { _base._replaceSubrange(subrange, with: newElements._base) } public mutating func replaceSubrange( - _ subrange: Range, with newElements: __owned _BSubstring.UnicodeScalarView + _ subrange: Range, with newElements: __owned BigSubstring.UnicodeScalarView ) { _base._replaceSubrange(subrange, with: newElements._base, in: newElements._bounds) } @@ -240,52 +240,52 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { public init>(_ elements: S) { if S.self == String.UnicodeScalarView.self { let elements = _identityCast(elements, to: String.UnicodeScalarView.self) - self.init(_base: _BString(_from: elements)) + self.init(_base: BigString(_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: BigString(_from: elements)) + } else if S.self == BigString.UnicodeScalarView.self { + let elements = _identityCast(elements, to: BigString.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 if S.self == BigSubstring.UnicodeScalarView.self { + let elements = _identityCast(elements, to: BigSubstring.UnicodeScalarView.self) + self.init(_base: BigString(_from: elements._base, in: elements._bounds)) } else { - self.init(_base: _BString(_from: elements)) + self.init(_base: BigString(_from: elements)) } } public init(_ elements: String.UnicodeScalarView) { - self.init(_base: _BString(_from: elements)) + self.init(_base: BigString(_from: elements)) } public init(_ elements: Substring.UnicodeScalarView) { - self.init(_base: _BString(_from: elements)) + self.init(_base: BigString(_from: elements)) } - public init(_ elements: _BString.UnicodeScalarView) { + public init(_ elements: BigString.UnicodeScalarView) { self.init(_base: elements._base) } - public init(_ elements: _BSubstring.UnicodeScalarView) { - self.init(_base: _BString(_from: elements._base, in: elements._bounds)) + public init(_ elements: BigSubstring.UnicodeScalarView) { + self.init(_base: BigString(_from: elements._base, in: elements._bounds)) } public init(repeating repeatedValue: UnicodeScalar, count: Int) { - self.init(_base: _BString(repeating: _BString(String(repeatedValue)), count: count)) + self.init(_base: BigString(repeating: BigString(String(repeatedValue)), count: count)) } public init(repeating repeatedValue: some StringProtocol, count: Int) { - self.init(_base: _BString(repeating: _BString(_from: repeatedValue), count: count)) + self.init(_base: BigString(repeating: BigString(_from: repeatedValue), count: count)) } - public init(repeating value: _BString.UnicodeScalarView, count: Int) { - self.init(_base: _BString(repeating: value._base, count: count)) + public init(repeating value: BigString.UnicodeScalarView, count: Int) { + self.init(_base: BigString(repeating: value._base, count: count)) } - public init(repeating value: _BSubstring.UnicodeScalarView, count: Int) { - let value = _BString(value) - self.init(_base: _BString(repeating: value, count: count)) + public init(repeating value: BigSubstring.UnicodeScalarView, count: Int) { + let value = BigString(value) + self.init(_base: BigString(repeating: value, count: count)) } public mutating func append(_ newElement: __owned UnicodeScalar) { @@ -299,14 +299,14 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } 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) + } else if S.self == BigString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) append(contentsOf: newElements) - } else if S.self == _BSubstring.UnicodeScalarView.self { - let newElements = _identityCast(newElements, to: _BSubstring.UnicodeScalarView.self) + } else if S.self == BigSubstring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigSubstring.UnicodeScalarView.self) append(contentsOf: newElements) } else { - _base.append(contentsOf: _BString(_from: newElements)) + _base.append(contentsOf: BigString(_from: newElements)) } } @@ -318,11 +318,11 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { _base.append(contentsOf: Substring(newElements)) } - public mutating func append(contentsOf newElements: __owned _BString.UnicodeScalarView) { + public mutating func append(contentsOf newElements: __owned BigString.UnicodeScalarView) { _base.append(contentsOf: newElements._base) } - public mutating func append(contentsOf newElements: __owned _BSubstring.UnicodeScalarView) { + public mutating func append(contentsOf newElements: __owned BigSubstring.UnicodeScalarView) { _base._append(contentsOf: newElements._base, in: newElements._bounds) } @@ -339,14 +339,14 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } 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) + } else if C.self == BigString.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigString.UnicodeScalarView.self) insert(contentsOf: newElements, at: i) - } else if C.self == _BSubstring.UnicodeScalarView.self { - let newElements = _identityCast(newElements, to: _BSubstring.UnicodeScalarView.self) + } else if C.self == BigSubstring.UnicodeScalarView.self { + let newElements = _identityCast(newElements, to: BigSubstring.UnicodeScalarView.self) insert(contentsOf: newElements, at: i) } else { - _base.insert(contentsOf: _BString(_from: newElements), at: i) + _base.insert(contentsOf: BigString(_from: newElements), at: i) } } @@ -365,14 +365,14 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } public mutating func insert( - contentsOf newElements: __owned _BString.UnicodeScalarView, + contentsOf newElements: __owned BigString.UnicodeScalarView, at i: Index ) { _base.insert(contentsOf: newElements._base, at: i) } public mutating func insert( - contentsOf newElements: __owned _BSubstring.UnicodeScalarView, + contentsOf newElements: __owned BigSubstring.UnicodeScalarView, at i: Index ) { _base._insert(contentsOf: newElements._base, in: newElements._bounds, at: i) @@ -388,7 +388,7 @@ extension _BString.UnicodeScalarView: RangeReplaceableCollection { } public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - self._base = _BString() + self._base = BigString() } } diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift similarity index 86% rename from Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift rename to Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift index 1ef974e2..7e13196f 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF16View.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift @@ -12,24 +12,24 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring { +extension BigSubstring { public struct UTF16View: Sendable { - internal var _base: _BString + internal var _base: BigString internal var _bounds: Range - public init(_unchecked base: _BString, in bounds: Range) { + public init(_unchecked base: BigString, in bounds: Range) { self._base = base self._bounds = bounds } - public init(_ base: _BString, in bounds: Range) { + public init(_ base: BigString, in bounds: Range) { self._base = base let lower = base.utf16Index(roundingDown: bounds.lowerBound) let upper = base.utf16Index(roundingDown: bounds.upperBound) self._bounds = Range(uncheckedBounds: (lower, upper)) } - internal init(_substring: _BSubstring) { + internal init(_substring: BigSubstring) { self.init(_unchecked: _substring._base, in: _substring._bounds) } } @@ -40,8 +40,8 @@ extension _BSubstring { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - public init?(_ utf16: _BSubstring.UTF16View) { +extension BigString { + public init?(_ utf16: BigSubstring.UTF16View) { guard !utf16.startIndex._isUTF16TrailingSurrogate, !utf16.endIndex._isUTF16TrailingSurrogate @@ -53,12 +53,12 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF16View { - public var base: _BString.UTF16View { _base.utf16 } +extension BigSubstring.UTF16View { + public var base: BigString.UTF16View { _base.utf16 } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF16View: Equatable { +extension BigSubstring.UTF16View: Equatable { public static func ==(left: Self, right: Self) -> Bool { var i1 = left._bounds.lowerBound var i2 = right._bounds.lowerBound @@ -83,7 +83,7 @@ extension _BSubstring.UTF16View: Equatable { guard left[j1] == right[j2] else { return false} } - return _BString.utf8IsEqual(left._base, in: i1 ..< j1, to: right._base, in: i2 ..< j2) + return BigString.utf8IsEqual(left._base, in: i1 ..< j1, to: right._base, in: i2 ..< j2) } public func isIdentical(to other: Self) -> Bool { @@ -93,7 +93,7 @@ extension _BSubstring.UTF16View: Equatable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF16View: Hashable { +extension BigSubstring.UTF16View: Hashable { public func hash(into hasher: inout Hasher) { for codeUnit in self { hasher.combine(codeUnit) @@ -103,14 +103,14 @@ extension _BSubstring.UTF16View: Hashable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF16View: Sequence { +extension BigSubstring.UTF16View: Sequence { public typealias Element = UInt16 public struct Iterator: IteratorProtocol { - var _it: _BString.UTF16View.Iterator - var _end: _BString.Index + var _it: BigString.UTF16View.Iterator + var _end: BigString.Index - init(_substring: _BSubstring.UTF16View) { + init(_substring: BigSubstring.UTF16View) { self._it = .init(_base: _substring._base, from: _substring.startIndex) self._end = _substring.endIndex } @@ -127,8 +127,8 @@ extension _BSubstring.UTF16View: Sequence { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF16View: BidirectionalCollection { - public typealias Index = _BString.Index +extension BigSubstring.UTF16View: BidirectionalCollection { + public typealias Index = BigString.Index public typealias SubSequence = Self @inline(__always) @@ -188,7 +188,7 @@ extension _BSubstring.UTF16View: BidirectionalCollection { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF16View { +extension BigSubstring.UTF16View { public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.utf16Index(roundingDown: i) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift similarity index 84% rename from Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift rename to Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift index 7f164071..b2ce342d 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UTF8View.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift @@ -12,24 +12,24 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring { +extension BigSubstring { public struct UTF8View: Sendable { - internal var _base: _BString + internal var _base: BigString internal var _bounds: Range - public init(_unchecked base: _BString, in bounds: Range) { + public init(_unchecked base: BigString, in bounds: Range) { self._base = base self._bounds = bounds } - public init(_ base: _BString, in bounds: Range) { + public init(_ base: BigString, in bounds: Range) { self._base = base let lower = base.utf8Index(roundingDown: bounds.lowerBound) let upper = base.utf8Index(roundingDown: bounds.upperBound) self._bounds = Range(uncheckedBounds: (lower, upper)) } - internal init(_substring: _BSubstring) { + internal init(_substring: BigSubstring) { self.init(_unchecked: _substring._base, in: _substring._bounds) } } @@ -40,8 +40,8 @@ extension _BSubstring { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - public init?(_ utf8: _BSubstring.UTF8View) { +extension BigString { + public init?(_ utf8: BigSubstring.UTF8View) { guard utf8._base.unicodeScalars.index(roundingDown: utf8.startIndex) == utf8.startIndex, utf8._base.unicodeScalars.index(roundingDown: utf8.endIndex) == utf8.endIndex @@ -53,14 +53,14 @@ extension _BString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF8View { - public var base: _BString.UTF8View { _base.utf8 } +extension BigSubstring.UTF8View { + public var base: BigString.UTF8View { _base.utf8 } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF8View: Equatable { +extension BigSubstring.UTF8View: Equatable { public static func ==(left: Self, right: Self) -> Bool { - _BString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) + BigString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) } public func isIdentical(to other: Self) -> Bool { @@ -70,21 +70,21 @@ extension _BSubstring.UTF8View: Equatable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF8View: Hashable { +extension BigSubstring.UTF8View: Hashable { public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher, from: _bounds.lowerBound, to: _bounds.upperBound) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF8View: Sequence { +extension BigSubstring.UTF8View: Sequence { public typealias Element = UInt8 public struct Iterator: IteratorProtocol { - var _it: _BString.UTF8View.Iterator - var _end: _BString.Index + var _it: BigString.UTF8View.Iterator + var _end: BigString.Index - init(_substring: _BSubstring.UTF8View) { + init(_substring: BigSubstring.UTF8View) { self._it = .init(_base: _substring._base, from: _substring.startIndex) self._end = _substring.endIndex } @@ -101,8 +101,8 @@ extension _BSubstring.UTF8View: Sequence { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF8View: BidirectionalCollection { - public typealias Index = _BString.Index +extension BigSubstring.UTF8View: BidirectionalCollection { + public typealias Index = BigString.Index public typealias SubSequence = Self @inline(__always) @@ -162,7 +162,7 @@ extension _BSubstring.UTF8View: BidirectionalCollection { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UTF8View { +extension BigSubstring.UTF8View { public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.utf8Index(roundingDown: i) diff --git a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift similarity index 84% rename from Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift rename to Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift index ed20b68b..3b4d8dc0 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift @@ -12,26 +12,26 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring { +extension BigSubstring { public struct UnicodeScalarView: Sendable { - internal var _base: _BString + internal var _base: BigString internal var _bounds: Range - public init(_unchecked base: _BString, in bounds: Range) { + public init(_unchecked base: BigString, in bounds: Range) { assert(bounds.lowerBound == base.unicodeScalarIndex(roundingDown: bounds.lowerBound)) assert(bounds.upperBound == base.unicodeScalarIndex(roundingDown: bounds.upperBound)) self._base = base self._bounds = bounds } - public init(_ base: _BString, in bounds: Range) { + public init(_ base: BigString, in bounds: Range) { self._base = base let lower = base.unicodeScalarIndex(roundingDown: bounds.lowerBound) let upper = base.unicodeScalarIndex(roundingDown: bounds.upperBound) self._bounds = Range(uncheckedBounds: (lower, upper)) } - internal init(_substring: _BSubstring) { + internal init(_substring: BigSubstring) { self.init(_unchecked: _substring._base, in: _substring._bounds) } } @@ -55,42 +55,42 @@ extension _BSubstring { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BString { - public init(_ unicodeScalars: _BSubstring.UnicodeScalarView) { +extension BigString { + public init(_ unicodeScalars: BigSubstring.UnicodeScalarView) { self.init(_from: unicodeScalars._base, in: unicodeScalars._bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView { - public var base: _BString.UnicodeScalarView { _base.unicodeScalars } +extension BigSubstring.UnicodeScalarView { + public var base: BigString.UnicodeScalarView { _base.unicodeScalars } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView: ExpressibleByStringLiteral { +extension BigSubstring.UnicodeScalarView: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(value.unicodeScalars) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView: CustomStringConvertible { +extension BigSubstring.UnicodeScalarView: CustomStringConvertible { public var description: String { String(_from: _base, in: _bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView: CustomDebugStringConvertible { +extension BigSubstring.UnicodeScalarView: CustomDebugStringConvertible { public var debugDescription: String { description.debugDescription } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView: Equatable { +extension BigSubstring.UnicodeScalarView: Equatable { public static func ==(left: Self, right: Self) -> Bool { - _BString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) + BigString.utf8IsEqual(left._base, in: left._bounds, to: right._base, in: right._bounds) } public func isIdentical(to other: Self) -> Bool { @@ -100,21 +100,21 @@ extension _BSubstring.UnicodeScalarView: Equatable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView: Hashable { +extension BigSubstring.UnicodeScalarView: Hashable { public func hash(into hasher: inout Hasher) { _base.hashUTF8(into: &hasher, from: _bounds.lowerBound, to: _bounds.upperBound) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView: Sequence { +extension BigSubstring.UnicodeScalarView: Sequence { public typealias Element = UnicodeScalar public struct Iterator: IteratorProtocol { - var _it: _BString.UnicodeScalarView.Iterator - let _end: _BString.Index + var _it: BigString.UnicodeScalarView.Iterator + let _end: BigString.Index - internal init(_substring: _BSubstring.UnicodeScalarView) { + internal init(_substring: BigSubstring.UnicodeScalarView) { self._it = .init(_base: _substring._base, from: _substring.startIndex) self._end = _substring._base.resolve(_substring.endIndex, preferEnd: true) } @@ -131,8 +131,8 @@ extension _BSubstring.UnicodeScalarView: Sequence { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView: BidirectionalCollection { - public typealias Index = _BString.Index +extension BigSubstring.UnicodeScalarView: BidirectionalCollection { + public typealias Index = BigString.Index public typealias SubSequence = Self @inline(__always) @@ -192,7 +192,7 @@ extension _BSubstring.UnicodeScalarView: BidirectionalCollection { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView { +extension BigSubstring.UnicodeScalarView { public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.unicodeScalarIndex(roundingDown: i) @@ -205,13 +205,13 @@ extension _BSubstring.UnicodeScalarView { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView { +extension BigSubstring.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 + with body: (inout BigString.UnicodeScalarView) -> R ) -> R { precondition( range.lowerBound >= _bounds.lowerBound && range.upperBound <= _bounds.upperBound, @@ -221,8 +221,8 @@ extension _BSubstring.UnicodeScalarView { let endOffset = self.endIndex.utf8Offset let oldCount = self._base.utf8Count - var view = _BString.UnicodeScalarView(_base: self._base) - self._base = _BString() + var view = BigString.UnicodeScalarView(_base: self._base) + self._base = BigString() defer { // The Unicode scalar view is regular -- we just need to maintain the UTF-8 offsets of @@ -238,9 +238,9 @@ extension _BSubstring.UnicodeScalarView { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring.UnicodeScalarView: RangeReplaceableCollection { +extension BigSubstring.UnicodeScalarView: RangeReplaceableCollection { public init() { - self.init(_substring: _BSubstring()) + self.init(_substring: BigSubstring()) } public mutating func reserveCapacity(_ n: Int) { @@ -254,12 +254,12 @@ extension _BSubstring.UnicodeScalarView: RangeReplaceableCollection { } public init>(_ elements: S) { - let base = _BString.UnicodeScalarView(elements) + let base = BigString.UnicodeScalarView(elements) self.init(base._base, in: base.startIndex ..< base.endIndex) } public init(repeating repeatedValue: UnicodeScalar, count: Int) { - let base = _BString.UnicodeScalarView(repeating: repeatedValue, count: count) + let base = BigString.UnicodeScalarView(repeating: repeatedValue, count: count) self.init(base._base, in: base.startIndex ..< base.endIndex) } diff --git a/Sources/RopeModule/BString/Views/_BSubstring.swift b/Sources/RopeModule/BigString/Views/BigSubstring.swift similarity index 86% rename from Sources/RopeModule/BString/Views/_BSubstring.swift rename to Sources/RopeModule/BigString/Views/BigSubstring.swift index f135b297..1b067a78 100644 --- a/Sources/RopeModule/BString/Views/_BSubstring.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring.swift @@ -12,18 +12,18 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -public struct _BSubstring: Sendable { - var _base: _BString +public struct BigSubstring: Sendable { + var _base: BigString var _bounds: Range - public init(_unchecked base: _BString, in bounds: Range) { + public init(_unchecked base: BigString, in bounds: Range) { assert(bounds.lowerBound == base.characterIndex(roundingDown: bounds.lowerBound)) assert(bounds.upperBound == base.characterIndex(roundingDown: bounds.upperBound)) self._base = base self._bounds = bounds } - public init(_ base: _BString, in bounds: Range) { + public init(_ base: BigString, in bounds: Range) { self._base = base // Sub-character slicing could change character boundaries in the tree, requiring // resyncing metadata. This would not be acceptable to do during slicing, so let's @@ -35,12 +35,12 @@ public struct _BSubstring: Sendable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring { - public var base: _BString { _base } +extension BigSubstring { + public var base: BigString { _base } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring { +extension BigSubstring { func _foreachChunk( _ body: (Substring) -> Void ) { @@ -49,33 +49,33 @@ extension _BSubstring { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: CustomStringConvertible { +extension BigSubstring: CustomStringConvertible { public var description: String { String(_from: _base, in: _bounds) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: CustomDebugStringConvertible { +extension BigSubstring: CustomDebugStringConvertible { public var debugDescription: String { description.debugDescription } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: ExpressibleByStringLiteral { +extension BigSubstring: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(value) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: LosslessStringConvertible { +extension BigSubstring: LosslessStringConvertible { // init?(_: String) is implemented by RangeReplaceableCollection.init(_:) } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: Equatable { +extension BigSubstring: Equatable { public static func ==(left: Self, right: Self) -> Bool { // FIXME: Implement properly normalized comparisons & hashing. // This is somewhat tricky as we shouldn't just normalize individual pieces of the string @@ -106,14 +106,19 @@ extension _BSubstring: Equatable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: Hashable { +extension BigSubstring: Hashable { public func hash(into hasher: inout Hasher) { - _base.hashCharacters(into: &hasher, from: _bounds) + var it = self.makeIterator() + while let character = it.next() { + let s = String(character) + s._withNFCCodeUnits { hasher.combine($0) } + } + hasher.combine(0xFF as UInt8) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: Comparable { +extension BigSubstring: Comparable { public static func < (left: Self, right: Self) -> Bool { // FIXME: Implement properly normalized comparisons & hashing. // This is somewhat tricky as we shouldn't just normalize individual pieces of the string @@ -138,15 +143,15 @@ extension _BSubstring: Comparable { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: Sequence { +extension BigSubstring: Sequence { public typealias Element = Character public struct Iterator: IteratorProtocol { - let _end: _BString.Index - var _it: _BString.Iterator + let _end: BigString.Index + var _it: BigString.Iterator - init(_substring: _BSubstring) { - self._it = _substring._base.makeCharacterIterator(from: _substring.startIndex) + init(_substring: BigSubstring) { + self._it = BigString.Iterator(_substring._base, from: _substring.startIndex) self._end = _substring.endIndex } @@ -162,8 +167,8 @@ extension _BSubstring: Sequence { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: BidirectionalCollection { - public typealias Index = _BString.Index +extension BigSubstring: BidirectionalCollection { + public typealias Index = BigString.Index public typealias SubSequence = Self @inline(__always) @@ -223,7 +228,7 @@ extension _BSubstring: BidirectionalCollection { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring { +extension BigSubstring { public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") return _base.characterIndex(roundingDown: i) @@ -236,7 +241,7 @@ extension _BSubstring { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring { +extension BigSubstring { /// 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. @@ -244,7 +249,7 @@ extension _BSubstring { /// 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 + with body: (inout BigString) -> R ) -> R { precondition( range.lowerBound >= _bounds.lowerBound && range.upperBound <= _bounds.upperBound, @@ -271,9 +276,9 @@ extension _BSubstring { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _BSubstring: RangeReplaceableCollection { +extension BigSubstring: RangeReplaceableCollection { public init() { - let str = _BString() + let str = BigString() let bounds = Range(uncheckedBounds: (str.startIndex, str.endIndex)) self.init(_unchecked: str, in: bounds) } @@ -291,24 +296,24 @@ extension _BSubstring: RangeReplaceableCollection { } public init>(_ elements: S) { - let base = _BString(elements) + let base = BigString(elements) self.init(base, in: base.startIndex ..< base.endIndex) } public init(repeating repeatedValue: Character, count: Int) { - self.init(_BString(repeating: repeatedValue, count: count)) + self.init(BigString(repeating: repeatedValue, count: count)) } public init(repeating repeatedValue: some StringProtocol, count: Int) { - self.init(_BString(repeating: repeatedValue, count: count)) + self.init(BigString(repeating: repeatedValue, count: count)) } - public init(repeating repeatedValue: _BString, count: Int) { - self.init(_BString(repeating: repeatedValue, count: count)) + public init(repeating repeatedValue: BigString, count: Int) { + self.init(BigString(repeating: repeatedValue, count: count)) } - public init(repeating repeatedValue: _BSubstring, count: Int) { - self.init(_BString(repeating: repeatedValue, count: count)) + public init(repeating repeatedValue: BigSubstring, count: Int) { + self.init(BigString(repeating: repeatedValue, count: count)) } public mutating func append(_ newElement: Character) { diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift index 9aa58bb6..4423387c 100644 --- a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -146,7 +146,7 @@ extension _CharacterRecognizer { } mutating func consume( - _ chunk: _BString.Chunk, upTo index: String.Index + _ chunk: BigString.Chunk, upTo index: String.Index ) -> (firstBreak: String.Index, prevBreak: String.Index)? { let index = chunk.string.unicodeScalars._index(roundingDown: index) let first = chunk.firstBreak diff --git a/Tests/RopeModuleTests/Availability.swift b/Tests/RopeModuleTests/Availability.swift index 3587f8d3..a20b578c 100644 --- a/Tests/RopeModuleTests/Availability.swift +++ b/Tests/RopeModuleTests/Availability.swift @@ -15,3 +15,19 @@ var isRunningOnSwiftStdlib5_8: Bool { } return false } + + +#if swift(<5.8) +extension String.Index { + var _description: String { + let raw = unsafeBitCast(self, to: UInt64.self) + let encodedOffset = Int(truncatingIfNeeded: raw &>> 16) + let transcodedOffset = Int(truncatingIfNeeded: (raw &>> 14) & 0x3) + var d = "\(encodedOffset)[unknown]" + if transcodedOffset > 0 { + d += "+\(transcodedOffset)" + } + return d + } +} +#endif diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index 974205df..e272254f 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -15,7 +15,7 @@ import _RopeModule import XCTest @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -class TestBString: CollectionTestCase { +class TestBigString: CollectionTestCase { override var isAvailable: Bool { isRunningOnSwiftStdlib5_8 } override class func setUp() { @@ -31,8 +31,8 @@ class TestBString: CollectionTestCase { } func test_capacity() { - let min = _BString.minimumCapacity - let max = _BString.maximumCapacity + let min = BigString._minimumCapacity + let max = BigString._maximumCapacity XCTAssertLessThanOrEqual(min, max) #if !DEBUG // Debug builds have smaller nodes @@ -43,8 +43,8 @@ class TestBString: CollectionTestCase { } func test_empty() { - let s = _BString() - s.invariantCheck() + let s = BigString() + s._invariantCheck() XCTAssertEqual(s.count, 0) XCTAssertEqual(s.unicodeScalars.count, 0) XCTAssertEqual(s.utf16.count, 0) @@ -56,11 +56,30 @@ class TestBString: CollectionTestCase { XCTAssertEqual(String(s), "") XCTAssertEqual(String(s[...]), "") } - + + func test_Equatable() { + let a: BigString = "Cafe\u{301}" + let b: BigString = "Café" + XCTAssertEqual(a, b) + XCTAssertNotEqual(a.unicodeScalars, b.unicodeScalars) + XCTAssertNotEqual(a.utf8, b.utf8) + XCTAssertNotEqual(a.utf16, b.utf16) + } + + func test_descriptions() { + let s: BigString = "Café" + XCTAssertEqual(s.description, "Café") + XCTAssertEqual(s.unicodeScalars.description, "Café") + #if false // Should we? + XCTAssertEqual(s.utf8.description, "<43 61 66 C3 A9>") + XCTAssertEqual(s.utf16.description, "<0043 0061 0066 00E9>") + #endif + } + func test_string_conversion() { - let big = _BString(sampleString) + let big = BigString(sampleString) - big.invariantCheck() + big._invariantCheck() XCTAssertEqual(big.count, sampleString.count) XCTAssertEqual(big.unicodeScalars.count, sampleString.unicodeScalars.count) XCTAssertEqual(big.utf16.count, sampleString.utf16.count) @@ -73,9 +92,9 @@ class TestBString: CollectionTestCase { @discardableResult func checkCharacterIndices( _ flat: String, - _ big: _BString, + _ big: BigString, file: StaticString = #file, line: UInt = #line - ) -> (flat: [String.Index], big: [_BString.Index]) { + ) -> (flat: [String.Index], big: [BigString.Index]) { // Check iterators var it1 = flat.makeIterator() var it2 = big.makeIterator() @@ -98,10 +117,24 @@ class TestBString: CollectionTestCase { ) XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) - for i in 0 ..< min(indices1.count, indices2.count) { - let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + + let c = min(indices1.count, indices2.count) + + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + guard i1 < flat.endIndex, i2 < big.endIndex else { continue } + let c1 = flat[i1] + let c2 = big[i2] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) + } + + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) + let d2 = big.utf8.distance(from: big.startIndex, to: i2) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } return (indices1, indices2) } @@ -109,9 +142,9 @@ class TestBString: CollectionTestCase { @discardableResult func checkScalarIndices( _ flat: String, - _ big: _BString, + _ big: BigString, file: StaticString = #file, line: UInt = #line - ) -> (flat: [String.Index], big: [_BString.Index]) { + ) -> (flat: [String.Index], big: [BigString.Index]) { // Check iterators var it1 = flat.unicodeScalars.makeIterator() var it2 = big.unicodeScalars.makeIterator() @@ -134,10 +167,24 @@ class TestBString: CollectionTestCase { ) XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) - for i in 0 ..< min(indices1.count, indices2.count) { - let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + + let c = min(indices1.count, indices2.count) + + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + guard i1 < flat.endIndex, i2 < big.endIndex else { continue } + let c1 = flat.unicodeScalars[i1] + let c2 = big.unicodeScalars[i2] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) + } + + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) + let d2 = big.utf8.distance(from: big.startIndex, to: i2) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } return (indices1, indices2) } @@ -145,9 +192,9 @@ class TestBString: CollectionTestCase { @discardableResult func checkUTF8Indices( _ flat: String, - _ big: _BString, + _ big: BigString, file: StaticString = #file, line: UInt = #line - ) -> (flat: [String.Index], big: [_BString.Index]) { + ) -> (flat: [String.Index], big: [BigString.Index]) { // Check iterators var it1 = flat.utf8.makeIterator() var it2 = big.utf8.makeIterator() @@ -170,10 +217,24 @@ class TestBString: CollectionTestCase { ) XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) - for i in 0 ..< min(indices1.count, indices2.count) { - let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]), i2: \(indices2[i])", file: file, line: line) + + let c = min(indices1.count, indices2.count) + + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + guard i1 < flat.endIndex, i2 < big.endIndex else { continue } + let c1 = flat.utf8[i1] + let c2 = big.utf8[i2] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) + } + + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) + let d2 = big.utf8.distance(from: big.startIndex, to: i2) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } return (indices1, indices2) } @@ -181,9 +242,9 @@ class TestBString: CollectionTestCase { @discardableResult func checkUTF16Indices( _ flat: String, - _ big: _BString, + _ big: BigString, file: StaticString = #file, line: UInt = #line - ) -> (flat: [String.Index], big: [_BString.Index]) { + ) -> (flat: [String.Index], big: [BigString.Index]) { // Check iterators var it1 = flat.utf16.makeIterator() var it2 = big.utf16.makeIterator() @@ -204,19 +265,94 @@ class TestBString: CollectionTestCase { $0 == big.endIndex ? nil : big.utf16.index(after: $0) } ) - + XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) - for i in 0 ..< min(indices1.count, indices2.count) { - let d1 = flat.utf8.distance(from: flat.startIndex, to: indices1[i]) - let d2 = big.utf8.distance(from: big.startIndex, to: indices2[i]) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(indices1[i]._description), i2: \(indices2[i])", file: file, line: line) + + let c = min(indices1.count, indices2.count) + + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + guard i1 < flat.endIndex, i2 < big.endIndex else { continue } + let c1 = flat.utf16[i1] + let c2 = big.utf16[i2] + XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) + } + + for i in 0 ..< c { + let i1 = indices1[i] + let i2 = indices2[i] + let d1 = flat.utf16.distance(from: flat.startIndex, to: i1) + let d2 = big.utf16.distance(from: big.startIndex, to: i2) + XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } return (indices1, indices2) } - + + func test_iterator_character() { + let small: BigString = "Cafe\u{301} 👩‍👩‍👧" + var it = small.makeIterator() + XCTAssertEqual(it.next(), "C") + XCTAssertEqual(it.next(), "a") + XCTAssertEqual(it.next(), "f") + XCTAssertEqual(it.next(), "e\u{301}") + XCTAssertEqual(it.next(), " ") + XCTAssertEqual(it.next(), "👩‍👩‍👧") + XCTAssertNil(it.next()) + + let flat = sampleString + let big = BigString(flat) + + let c1 = Array(flat) + let c2 = Array(big) + XCTAssertEqual(c1, c2) + } + + func test_iterator_scalar() { + let small: BigString = "Cafe\u{301} 👩‍👩‍👧" + var it = small.unicodeScalars.makeIterator() + XCTAssertEqual(it.next(), "C") + XCTAssertEqual(it.next(), "a") + XCTAssertEqual(it.next(), "f") + XCTAssertEqual(it.next(), "e") + XCTAssertEqual(it.next(), "\u{301}") + XCTAssertEqual(it.next(), " ") + XCTAssertEqual(it.next(), "👩") + XCTAssertEqual(it.next(), "\u{200D}") + XCTAssertEqual(it.next(), "👩") + XCTAssertEqual(it.next(), "\u{200D}") + XCTAssertEqual(it.next(), "👧") + XCTAssertNil(it.next()) + + let flat = sampleString + let big = BigString(flat) + + let c1 = Array(flat.unicodeScalars) + let c2 = Array(big.unicodeScalars) + XCTAssertEqual(c1, c2) + } + + func test_iterator_utf8() { + let flat = sampleString + let big = BigString(flat) + + let c1 = Array(flat.utf8) + let c2 = Array(big.utf8) + XCTAssertEqual(c1, c2) + } + + func test_iterator_utf16() { + let flat = sampleString + let big = BigString(flat) + + let c1 = Array(flat.utf16) + let c2 = Array(big.utf16) + XCTAssertEqual(c1, c2) + } + func test_indices_character() { let flat = sampleString - let big = _BString(flat) + let big = BigString(flat) let (indices1, indices2) = checkCharacterIndices(flat, big) @@ -229,8 +365,9 @@ class TestBString: CollectionTestCase { let i2 = indices2[i] let j2 = big.index(i2, offsetBy: j - i) - let slice = _BSubstring(_unchecked: big, in: i2 ..< j2) - let b = String(slice) + XCTAssertEqual(big.index(roundingDown: i2), i2) + XCTAssertEqual(big.index(roundingDown: j2), j2) + let b = String(big[i2 ..< j2]) XCTAssertEqual(b, a) } } @@ -238,7 +375,7 @@ class TestBString: CollectionTestCase { func test_indices_scalar() { let flat = sampleString - let big = _BString(flat) + let big = BigString(flat) let (indices1, indices2) = checkScalarIndices(flat, big) @@ -249,7 +386,9 @@ class TestBString: CollectionTestCase { let i2 = indices2[i] let j2 = big.unicodeScalars.index(i2, offsetBy: j - i) - let slice = _BSubstring.UnicodeScalarView(_unchecked: big, in: i2 ..< j2) + XCTAssertEqual(big.unicodeScalars.index(roundingDown: i2), i2) + XCTAssertEqual(big.unicodeScalars.index(roundingDown: j2), j2) + let slice = big.unicodeScalars[i2 ..< j2] let b = String(slice) XCTAssertEqual(b, a) } @@ -258,7 +397,7 @@ class TestBString: CollectionTestCase { func test_indices_utf16() { let flat = sampleString - let big = _BString(flat) + let big = BigString(flat) let (indices1, indices2) = checkUTF16Indices(flat, big) @@ -269,6 +408,8 @@ class TestBString: CollectionTestCase { let i2 = indices2[i] let j2 = big.utf16.index(i2, offsetBy: j - i) + XCTAssertEqual(big.utf16.index(roundingDown: i2), i2) + XCTAssertEqual(big.utf16.index(roundingDown: j2), j2) let b = big.utf16[i2 ..< j2] XCTAssertEqual(b.first, a.first) // FIXME: Crash when i == 10 && j == 1282, seed == -3769053804926450170 @@ -279,7 +420,7 @@ class TestBString: CollectionTestCase { func test_indices_utf8() { let flat = sampleString - let big = _BString(flat) + let big = BigString(flat) let (indices1, indices2) = checkUTF8Indices(flat, big) @@ -290,6 +431,8 @@ class TestBString: CollectionTestCase { let i2 = indices2[i] let j2 = big.utf8.index(i2, offsetBy: j - i) + XCTAssertEqual(big.utf8.index(roundingDown: i2), i2) + XCTAssertEqual(big.utf8.index(roundingDown: j2), j2) let b = big.utf8[i2 ..< j2] XCTAssertEqual(b.first, a.first) XCTAssertEqual(b.last, a.last) @@ -299,9 +442,9 @@ class TestBString: CollectionTestCase { func test_append_string() { let flat = sampleString - let ref = _BString(flat) + let ref = BigString(flat) for stride in [1, 2, 4, 8, 16, 32, 64, 128, 250, 1000, 10000, 20000] { - var big: _BString = "" + var big: BigString = "" var i = flat.startIndex while i < flat.endIndex { let j = flat.unicodeScalars.index(i, offsetBy: stride, limitedBy: flat.endIndex) ?? flat.endIndex @@ -321,18 +464,18 @@ class TestBString: CollectionTestCase { func test_append_big() { let flat = sampleString - let ref = _BString(flat) + let ref = BigString(flat) for stride in [16, 32, 64, 128, 250, 1000, 10000, 20000] { - var big: _BString = "" + var big: BigString = "" var i = flat.startIndex while i < flat.endIndex { let j = flat.unicodeScalars.index(i, offsetBy: stride, limitedBy: flat.endIndex) ?? flat.endIndex let s = flat[i ..< j] - let piece = _BString(s) - piece.invariantCheck() + let piece = BigString(s) + piece._invariantCheck() XCTAssertEqual(piece.utf8.count, s.utf8.count) big.append(contentsOf: piece) - big.invariantCheck() + big._invariantCheck() i = j } checkUTF8Indices(flat, big) @@ -359,14 +502,14 @@ class TestBString: CollectionTestCase { func test_insert_string() { let flat = sampleString - let ref = _BString(flat) + let ref = BigString(flat) for stride in [1, 2, 4, 8, 16, 32, 64, 128, 250, 1000, 10000, 20000] { print("Stride: \(stride)") var pieces = pieces(of: flat, by: stride) var rng = RepeatableRandomNumberGenerator(seed: 0) pieces.shuffle(using: &rng) - var big: _BString = "" + var big: BigString = "" var smol = "" for i in pieces.indices { let piece = pieces[i] @@ -383,7 +526,7 @@ class TestBString: CollectionTestCase { big.insert(contentsOf: piece.str, at: index) if i % 20 == 0 { - big.invariantCheck() + big._invariantCheck() XCTAssertEqual(String(big), smol) checkUTF8Indices(smol, big) @@ -392,7 +535,7 @@ class TestBString: CollectionTestCase { checkCharacterIndices(smol, big) } } - big.invariantCheck() + big._invariantCheck() XCTAssertTrue(big.utf8 == ref.utf8) checkUTF8Indices(flat, big) checkUTF16Indices(flat, big) @@ -403,14 +546,14 @@ class TestBString: CollectionTestCase { func test_insert_big() { let flat = sampleString - let ref = _BString(flat) + let ref = BigString(flat) for stride in [64, 128, 250, 256, 257, 500, 512, 513, 1000, 2000, 10000, 20000] { print("Stride: \(stride)") var pieces = pieces(of: flat, by: stride) var rng = RepeatableRandomNumberGenerator(seed: 0) pieces.shuffle(using: &rng) - var big: _BString = "" + var big: BigString = "" var smol = "" for i in pieces.indices { let piece = pieces[i] @@ -425,11 +568,11 @@ class TestBString: CollectionTestCase { let index = big.utf8.index(big.startIndex, offsetBy: utf8Offset) //print("\(i)/\(pieces.count): i: \(piece.i), start: \(index), str: \(piece.str._properDebugDescription)") - let p = _BString(piece.str) + let p = BigString(piece.str) big.insert(contentsOf: p, at: index) if i % 20 == 0 { - big.invariantCheck() + big._invariantCheck() XCTAssertEqual(String(big), smol) checkUTF8Indices(smol, big) checkUTF16Indices(smol, big) @@ -437,7 +580,7 @@ class TestBString: CollectionTestCase { checkCharacterIndices(smol, big) } } - big.invariantCheck() + big._invariantCheck() XCTAssertTrue(big.utf8 == ref.utf8) checkUTF8Indices(flat, big) checkUTF16Indices(flat, big) @@ -445,13 +588,110 @@ class TestBString: CollectionTestCase { checkCharacterIndices(flat, big) } } - + + func test_replaceSubrange_string() { + let input = sampleString + let ref = BigString(input) + for stride in [1, 2, 4, 8, 16, 32, 64, 128, 250, 1000, 10000, 20000] { + print("Stride: \(stride)") + var pieces = pieces(of: input, by: stride) + var rng = RepeatableRandomNumberGenerator(seed: 0) + pieces.shuffle(using: &rng) + + let placeholder: Character = " " // To make this super slow, replace with "\u{200D}" + var big = BigString(repeating: placeholder, count: pieces.count) + var smol = String(repeating: placeholder, count: pieces.count) + for i in pieces.indices { + let piece = pieces[i] + let utf8Offset = pieces[.., + _ indices: some Sequence, file: StaticString = #file, line: UInt = #line ) { @@ -479,10 +719,10 @@ class TestBString: CollectionTestCase { func testCharacterIndexRoundingUp() { let ref = sampleString - let str = _BString(ref) + let str = BigString(ref) func check( - _ indices: some Sequence<_BString.Index>, + _ indices: some Sequence, file: StaticString = #file, line: UInt = #line ) { @@ -507,10 +747,10 @@ class TestBString: CollectionTestCase { func testUnicodeScalarIndexRoundingDown() { let ref = sampleString - let str = _BString(ref) + let str = BigString(ref) func check( - _ indices: some Sequence<_BString.Index>, + _ indices: some Sequence, file: StaticString = #file, line: UInt = #line ) { @@ -536,10 +776,10 @@ class TestBString: CollectionTestCase { func testUnicodeScalarIndexRoundingUp() { let ref = sampleString - let str = _BString(ref) + let str = BigString(ref) func check( - _ indices: some Sequence<_BString.Index>, + _ indices: some Sequence, file: StaticString = #file, line: UInt = #line ) { @@ -562,10 +802,10 @@ class TestBString: CollectionTestCase { func testUTF8IndexRoundingDown() { let ref = sampleString - let str = _BString(ref) + let str = BigString(ref) func check( - _ indices: some Sequence<_BString.Index>, + _ indices: some Sequence, file: StaticString = #file, line: UInt = #line ) { @@ -591,10 +831,10 @@ class TestBString: CollectionTestCase { func testUTF8IndexRoundingUp() { let ref = sampleString - let str = _BString(ref) + let str = BigString(ref) func check( - _ indices: some Sequence<_BString.Index>, + _ indices: some Sequence, file: StaticString = #file, line: UInt = #line ) { @@ -617,10 +857,10 @@ class TestBString: CollectionTestCase { func testUTF16IndexRoundingDown() { let ref = sampleString - let str = _BString(ref) + let str = BigString(ref) func check( - _ indices: some Sequence<_BString.Index>, + _ indices: some Sequence, file: StaticString = #file, line: UInt = #line ) { @@ -654,10 +894,10 @@ class TestBString: CollectionTestCase { func testUTF1t6IndexRoundingUp() { let ref = sampleString - let str = _BString(ref) + let str = BigString(ref) func check( - _ indices: some Sequence<_BString.Index>, + _ indices: some Sequence, file: StaticString = #file, line: UInt = #line ) { @@ -679,22 +919,22 @@ class TestBString: CollectionTestCase { } func testSubstringMutationIndexRounding() { - let b1: _BString = "Foobar" + let b1: BigString = "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) + let b2: BigString = "Foo👩👧bar" // WOMAN, GIRL + var s2: BigSubstring = 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(6) + let b3: BigString = "Foo🇺🇸🇨🇦🇺🇸🇨🇦bar" // Regional indicators "USCAUSCA" + var s3: BigSubstring = b3.prefix(6) XCTAssertEqual(s3, "Foo🇺🇸🇨🇦🇺🇸") s3.insert("\u{1f1ed}", at: s3.index(s3.startIndex, offsetBy: 3)) // Regional indicator "H" XCTAssertEqual(s3, "Foo🇭🇺🇸🇨🇦🇺") // Regional indicators "HUSCAUSCA" @@ -702,7 +942,7 @@ class TestBString: CollectionTestCase { } func test_unicodeScalars_mutations() { - let b1: _BString = "Foo👩👧bar" // WOMAN, GIRL + let b1: BigString = "Foo👩👧bar" // WOMAN, GIRL var s1 = b1.prefix(4) XCTAssertEqual(s1, "Foo👩") @@ -720,26 +960,26 @@ class TestBString: CollectionTestCase { } func test_ExpressibleByStringLiteral_and_CustomStringConvertible() { - let a: _BString = "foobar" + let a: BigString = "foobar" XCTAssertEqual(a.description, "foobar") XCTAssertEqual(a.debugDescription, "\"foobar\"") - let b: _BSubstring = "foobar" + let b: BigSubstring = "foobar" XCTAssertEqual(b.description, "foobar") XCTAssertEqual(b.debugDescription, "\"foobar\"") - let c: _BString.UnicodeScalarView = "foobar" + let c: BigString.UnicodeScalarView = "foobar" XCTAssertEqual(c.description, "foobar") XCTAssertEqual(c.debugDescription, "\"foobar\"") - let d: _BSubstring.UnicodeScalarView = "foobar" + let d: BigSubstring.UnicodeScalarView = "foobar" XCTAssertEqual(d.description, "foobar") XCTAssertEqual(d.debugDescription, "\"foobar\"") } func testCharacterwiseEquality() { - let cafe1: _BString = "Cafe\u{301}" - let cafe2: _BString = "Café" + let cafe1: BigString = "Cafe\u{301}" + let cafe2: BigString = "Café" XCTAssertEqual(cafe1, cafe2) XCTAssertNotEqual(cafe1.unicodeScalars, cafe2.unicodeScalars) XCTAssertNotEqual(cafe1.utf8, cafe2.utf8) diff --git a/Tests/RopeModuleTests/TestBString2.swift b/Tests/RopeModuleTests/TestBString2.swift index 86971857..cc650b38 100644 --- a/Tests/RopeModuleTests/TestBString2.swift +++ b/Tests/RopeModuleTests/TestBString2.swift @@ -15,31 +15,31 @@ import XCTest @testable import _RopeModule @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -class TestBString2: CollectionTestCase { +class TestBigString2: CollectionTestCase { override var isAvailable: Bool { isRunningOnSwiftStdlib5_8 } func testUTF8View() { - let str = _BString(shortSample) + let str = BigString(shortSample) checkBidirectionalCollection(str.utf8, expectedContents: shortSample.utf8) } func testUTF16View() { - let str = _BString(shortSample) + let str = BigString(shortSample) checkBidirectionalCollection(str.utf16, expectedContents: shortSample.utf16) } func testUnicodeScalarView() { - let str = _BString(shortSample) + let str = BigString(shortSample) checkBidirectionalCollection(str.unicodeScalars, expectedContents: shortSample.unicodeScalars) } func testCharacterView() { - let str = _BString(shortSample) + let str = BigString(shortSample) checkBidirectionalCollection(str, expectedContents: shortSample) } func testHashable_Characters() { - let classes: [[_BString]] = [ + let classes: [[BigString]] = [ ["Cafe\u{301}", "Café"], ["Foo\u{301}\u{327}", "Foo\u{327}\u{301}"], ["Foo;bar", "Foo\u{37e}bar"], @@ -48,7 +48,7 @@ class TestBString2: CollectionTestCase { } func testHashable_Scalars() { - let classes: [_BString] = [ + let classes: [BigString] = [ "Cafe\u{301}", "Café", "Foo\u{301}\u{327}", diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift deleted file mode 100644 index b3e3de3f..00000000 --- a/Tests/RopeModuleTests/TestBigString.swift +++ /dev/null @@ -1,573 +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) -import _CollectionsTestSupport -import _RopeModule -import XCTest - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -class TestBigString: CollectionTestCase { - override var isAvailable: Bool { isRunningOnSwiftStdlib5_8 } - - override class func setUp() { - // Turn off output buffering. - setbuf(stdout, nil) - setbuf(stderr, nil) - super.setUp() - } - - override func setUp() { - print("Global seed: \(globalSeed)") - super.setUp() - } - - func test_capacity() { - let min = BigString._minimumCapacity - let max = BigString._maximumCapacity - - XCTAssertLessThanOrEqual(min, max) -#if !DEBUG // Debug builds have smaller nodes - // We want big strings to hold at least as many UTF-8 code units as a regular String. - XCTAssertGreaterThanOrEqual(min, 1 << 48) -#endif - } - - func test_empty() { - let s = BigString() - s._invariantCheck() - XCTAssertEqual(s.count, 0) - XCTAssertEqual(s.unicodeScalars.count, 0) - XCTAssertEqual(s.utf16.count, 0) - XCTAssertEqual(s.utf8.count, 0) - XCTAssertTrue(s.isEmpty) - XCTAssertEqual(s.startIndex, s.endIndex) - XCTAssertEqual(s.utf8.distance(from: s.startIndex, to: s.endIndex), 0) - XCTAssertEqual(s.utf16.distance(from: s.startIndex, to: s.endIndex), 0) - XCTAssertEqual(s.unicodeScalars.distance(from: s.startIndex, to: s.endIndex), 0) - XCTAssertEqual(s.distance(from: s.startIndex, to: s.endIndex), 0) - } - - func test_Equatable() { - let a: BigString = "Cafe\u{301}" - let b: BigString = "Café" - XCTAssertEqual(a, b) - XCTAssertNotEqual(a.unicodeScalars, b.unicodeScalars) - XCTAssertNotEqual(a.utf8, b.utf8) - XCTAssertNotEqual(a.utf16, b.utf16) - } - - func test_descriptions() { - let s: BigString = "Café" - XCTAssertEqual(s.description, "Café") - XCTAssertEqual(s.unicodeScalars.description, "Café") - XCTAssertEqual(s.utf8.description, "<43 61 66 C3 A9>") - XCTAssertEqual(s.utf16.description, "<0043 0061 0066 00E9>") - } - - func test_string_conversion() { - let big = BigString(sampleString) - - big._invariantCheck() - XCTAssertEqual(big.count, sampleString.count) - XCTAssertEqual(big.unicodeScalars.count, sampleString.unicodeScalars.count) - XCTAssertEqual(big.utf16.count, sampleString.utf16.count) - XCTAssertEqual(big.utf8.count, sampleString.utf8.count) - - let flat = String(big) - XCTAssertEqual(flat, sampleString) - } - - @discardableResult - func checkCharacterIndices( - _ flat: String, - _ big: BigString, - file: StaticString = #file, line: UInt = #line - ) -> (flat: [String.Index], big: [BigString.Index]) { - let indices1 = Array(flat.indices) + [flat.endIndex] - let indices2 = Array( - sequence(first: big.startIndex) { - $0 == big.endIndex ? nil : big.index(after: $0) - } - ) - - XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) - - let c = min(indices1.count, indices2.count) - - for i in 0 ..< c { - let i1 = indices1[i] - let i2 = indices2[i] - guard i1 < flat.endIndex, i2 < big.endIndex else { continue } - let c1 = flat[i1] - let c2 = big[i2] - XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) - } - - for i in 0 ..< c { - let i1 = indices1[i] - let i2 = indices2[i] - let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) - let d2 = big.utf8.distance(from: big.startIndex, to: i2) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) - } - - return (indices1, indices2) - } - - @discardableResult - func checkScalarIndices( - _ flat: String, - _ big: BigString, - file: StaticString = #file, line: UInt = #line - ) -> (flat: [String.Index], big: [BigString.Index]) { - let indices1 = Array(flat.unicodeScalars.indices) + [flat.unicodeScalars.endIndex] - let indices2 = Array( - sequence(first: big.startIndex) { - $0 == big.endIndex ? nil : big.unicodeScalars.index(after: $0) - } - ) - - XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) - - let c = min(indices1.count, indices2.count) - - for i in 0 ..< c { - let i1 = indices1[i] - let i2 = indices2[i] - guard i1 < flat.endIndex, i2 < big.endIndex else { continue } - let c1 = flat.unicodeScalars[i1] - let c2 = big.unicodeScalars[i2] - XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1), i2: \(i2)", file: file, line: line) - } - - for i in 0 ..< min(indices1.count, indices2.count) { - let i1 = indices1[i] - let i2 = indices2[i] - let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) - let d2 = big.utf8.distance(from: big.startIndex, to: i2) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) - } - - return (indices1, indices2) - } - - @discardableResult - func checkUTF8Indices( - _ flat: String, - _ big: BigString, - file: StaticString = #file, line: UInt = #line - ) -> (flat: [String.Index], big: [BigString.Index]) { - let indices1 = Array(flat.utf8.indices) + [flat.utf8.endIndex] - let indices2 = Array( - sequence(first: big.startIndex) { - $0 == big.endIndex ? nil : big.utf8.index(after: $0) - } - ) - - XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) - - let c = min(indices1.count, indices2.count) - - for i in 0 ..< c { - let i1 = indices1[i] - let i2 = indices2[i] - guard i1 < flat.endIndex, i2 < big.endIndex else { continue } - let c1 = flat.utf8[i1] - let c2 = big.utf8[i2] - XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) - } - - for i in 0 ..< min(indices1.count, indices2.count) { - let i1 = indices1[i] - let i2 = indices2[i] - let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) - let d2 = big.utf8.distance(from: big.startIndex, to: i2) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) - } - - return (indices1, indices2) - } - - @discardableResult - func checkUTF16Indices( - _ flat: String, - _ big: BigString, - file: StaticString = #file, line: UInt = #line - ) -> (flat: [String.Index], big: [BigString.Index]) { - let indices1 = Array(flat.utf16.indices) + [flat.utf16.endIndex] - let indices2 = Array( - sequence(first: big.startIndex) { - $0 == big.endIndex ? nil : big.utf16.index(after: $0) - } - ) - - XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) - - let c = min(indices1.count, indices2.count) - - for i in 0 ..< c { - let i1 = indices1[i] - let i2 = indices2[i] - guard i1 < flat.endIndex, i2 < big.endIndex else { continue } - let c1 = flat.utf16[i1] - let c2 = big.utf16[i2] - XCTAssertEqual(c1, c2, "i: \(i), i1: \(i1), i2: \(i2)", file: file, line: line) - } - - for i in 0 ..< min(indices1.count, indices2.count) { - let i1 = indices1[i] - let i2 = indices2[i] - let d1 = flat.utf8.distance(from: flat.startIndex, to: i1) - let d2 = big.utf8.distance(from: big.startIndex, to: i2) - XCTAssertEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) - } - - return (indices1, indices2) - } - - func test_iterator_character() { - let small: BigString = "Cafe\u{301} 👩‍👩‍👧" - var it = small.makeIterator() - XCTAssertEqual(it.next(), "C") - XCTAssertEqual(it.next(), "a") - XCTAssertEqual(it.next(), "f") - XCTAssertEqual(it.next(), "e\u{301}") - XCTAssertEqual(it.next(), " ") - XCTAssertEqual(it.next(), "👩‍👩‍👧") - XCTAssertNil(it.next()) - - let flat = sampleString - let big = BigString(flat) - - let c1 = Array(flat) - let c2 = Array(big) - XCTAssertEqual(c1, c2) - } - - func test_iterator_scalar() { - let flat = sampleString - let big = BigString(flat) - - let c1 = Array(flat.unicodeScalars) - let c2 = Array(big.unicodeScalars) - XCTAssertEqual(c1, c2) - } - - func test_iterator_utf8() { - let flat = sampleString - let big = BigString(flat) - - let c1 = Array(flat.utf8) - let c2 = Array(big.utf8) - XCTAssertEqual(c1, c2) - } - - func test_iterator_utf16() { - let flat = sampleString - let big = BigString(flat) - - let c1 = Array(flat.utf16) - let c2 = Array(big.utf16) - XCTAssertEqual(c1, c2) - } - - func test_indices_character() { - let flat = sampleString - let big = BigString(flat) - - let (indices1, indices2) = checkCharacterIndices(flat, big) - - let c = min(indices1.count, indices2.count) - for i in randomStride(from: 0, to: c, by: 5, seed: 0) { - for j in randomStride(from: i, to: c, by: 5, seed: i) { - let i1 = indices1[i] - let j1 = indices1[j] - let a = String(sampleString[i1 ..< j1]) - - let i2 = indices2[i] - let j2 = big.index(i2, offsetBy: j - i) - let b = String(big[i2 ..< j2]) - XCTAssertEqual(b, a) - } - } - } - - func test_indices_scalar() { - let flat = sampleString - let big = BigString(flat) - - let (indices1, indices2) = checkScalarIndices(flat, big) - - let c = min(indices1.count, indices2.count) - for i in randomStride(from: 0, to: c, by: 20, seed: 0) { - for j in randomStride(from: i, to: c, by: 20, seed: i) { - let i2 = indices2[i] - let j2 = big.unicodeScalars.index(i2, offsetBy: j - i) - XCTAssertEqual(j2, indices2[j]) - } - } - } - - func test_indices_utf16() { - let flat = sampleString - let big = BigString(flat) - - let (indices1, indices2) = checkUTF16Indices(flat, big) - - let c = min(indices1.count, indices2.count) - for i in randomStride(from: 0, to: c, by: 20, seed: 0) { - for j in randomStride(from: i, to: c, by: 20, seed: i) { - let i2 = indices2[i] - let j2 = big.utf16.index(i2, offsetBy: j - i) - XCTAssertEqual(j2, indices2[j]) - } - } - } - - func test_indices_utf8() { - let flat = sampleString - let big = BigString(flat) - - let (indices1, indices2) = checkUTF8Indices(flat, big) - - let c = min(indices1.count, indices2.count) - for i in randomStride(from: 0, to: c, by: 40, seed: 0) { - for j in randomStride(from: i, to: c, by: 40, seed: i) { - let i2 = indices2[i] - let j2 = big.utf8.index(i2, offsetBy: j - i) - XCTAssertEqual(j2, indices2[j]) - } - } - } - - func test_append_string() { - let flat = sampleString - let ref = BigString(flat) - for stride in [1, 2, 4, 8, 16, 32, 64, 128, 250, 1000, 10000, 20000] { - var big: BigString = "" - var i = flat.startIndex - while i < flat.endIndex { - let j = flat.unicodeScalars.index(i, offsetBy: stride, limitedBy: flat.endIndex) ?? flat.endIndex - let next = String(flat[i ..< j]) - big.append(contentsOf: next) - //big._invariantCheck() - //XCTAssertEqual(String(big)[...], s[.. [(i: Int, str: String)] { - var pieces: [(i: Int, str: String)] = [] - var c = 0 - var i = str.startIndex - while i < str.endIndex { - let j = str.unicodeScalars.index(i, offsetBy: stride, limitedBy: str.endIndex) ?? str.endIndex - let next = String(str[i ..< j]) - pieces.append((c, next)) - c += 1 - i = j - } - return pieces - } - - func test_insert_string() { - let flat = sampleString - let ref = BigString(flat) - for stride in [1, 2, 4, 8, 16, 32, 64, 128, 250, 1000, 10000, 20000] { - print("Stride: \(stride)") - var pieces = pieces(of: flat, by: stride) - var rng = RepeatableRandomNumberGenerator(seed: 0) - pieces.shuffle(using: &rng) - - var big: BigString = "" - var smol = "" - for i in pieces.indices { - let piece = pieces[i] - let utf8Offset = pieces[...Index] = [] - var i = rope.startIndex - while i != rope.endIndex { + var i = _rope.startIndex + while i != _rope.endIndex { indices.append(i) - i = rope.index(after: i) + i = _rope.index(after: i) } while let j = indices.popLast() { - i = rope.index(before: i) + i = _rope.index(before: i) XCTAssertEqual(i, j) } } @@ -215,13 +215,13 @@ class TestRope: XCTestCase { let ref = (0 ..< c).map { Chunk(length: ($0 % 4) + 1, value: $0) } - let rope = _Rope(ref) + let _rope = _Rope(ref) - let indices = Array(rope.indices) + [rope.endIndex] + let indices = Array(_rope.indices) + [_rope.endIndex] XCTAssertEqual(indices.count, c + 1) for i in indices.indices { for j in indices.indices { - let d = rope.distance(from: indices[i], to: indices[j], in: Chunk.Metric()) + let d = _rope.distance(from: indices[i], to: indices[j], in: Chunk.Metric()) let r = ( i <= j ? ref[i..(ref) + let _rope = _Rope(ref) - let indices = Array(rope.indices) + [rope.endIndex] + let indices = Array(_rope.indices) + [_rope.endIndex] XCTAssertEqual(indices.count, c + 1) for i in indices.indices { for j in indices.indices { @@ -247,7 +247,7 @@ class TestRope: XCTestCase { i <= j ? ref[i..() + var _rope = _Rope() var ref: [Chunk] = [] for i in 0 ..< c { let chunk = Chunk(length: (i % 4) + 1, value: i) ref.append(chunk) - rope.append(chunk) - rope.invariantCheck() + _rope.append(chunk) + _rope.invariantCheck() } - let actualSum = rope.summary + let actualSum = _rope.summary let expectedSum: Chunk.Summary = ref.reduce(into: .zero) { $0.add($1.summary) } XCTAssertEqual(actualSum, expectedSum) - XCTAssertTrue(rope.elementsEqual(ref)) + XCTAssertTrue(_rope.elementsEqual(ref)) } func test_prepend_item() { @@ -280,17 +280,17 @@ class TestRope: XCTestCase { Chunk(length: ($0 % 4) + 1, value: $0) } - var rope = _Rope() + var _rope = _Rope() for chunk in ref.reversed() { - rope.insert(chunk, at: 0, in: Chunk.Metric()) - rope.invariantCheck() + _rope.insert(chunk, at: 0, in: Chunk.Metric()) + _rope.invariantCheck() } - let actualSum = rope.summary + let actualSum = _rope.summary let expectedSum: Chunk.Summary = ref.reduce(into: .zero) { $0.add($1.summary) } XCTAssertEqual(actualSum, expectedSum) - XCTAssertTrue(rope.elementsEqual(ref)) + XCTAssertTrue(_rope.elementsEqual(ref)) } func test_insert_item() { @@ -302,21 +302,21 @@ class TestRope: XCTestCase { var rng = RepeatableRandomNumberGenerator(seed: 0) let input = ref.shuffled(using: &rng) - var rope = _Rope() + var _rope = _Rope() for i in input.indices { let chunk = input[i] let position = input[..(ref) + var _rope = _Rope(ref) var rng = RepeatableRandomNumberGenerator(seed: 0) let input = ref.shuffled(using: &rng) @@ -335,13 +335,13 @@ class TestRope: XCTestCase { let offset = input[i...].reduce(into: 0) { $0 += $1.value < chunk.value ? 1 : 0 } - let index = rope.index(rope.startIndex, offsetBy: offset) - let removed = rope.remove(at: index) + let index = _rope.index(_rope.startIndex, offsetBy: offset) + let removed = _rope.remove(at: index) XCTAssertEqual(removed, chunk) - rope.invariantCheck() + _rope.invariantCheck() } - XCTAssertTrue(rope.isEmpty) - XCTAssertEqual(rope.summary, .zero) + XCTAssertTrue(_rope.isEmpty) + XCTAssertEqual(_rope.summary, .zero) } func test_remove_at_position() { @@ -350,7 +350,7 @@ class TestRope: XCTestCase { Chunk(length: ($0 % 4) + 1, value: $0) } - var rope = _Rope(ref) + var _rope = _Rope(ref) var rng = RepeatableRandomNumberGenerator(seed: 0) let input = ref.shuffled(using: &rng) @@ -360,12 +360,12 @@ class TestRope: XCTestCase { let position = input[i...].reduce(into: 0) { $0 += $1.value < chunk.value ? $1.length : 0 } - let removed = rope.remove(at: position, in: Chunk.Metric()) + let removed = _rope.remove(at: position, in: Chunk.Metric()) XCTAssertEqual(removed, chunk) - rope.invariantCheck() + _rope.invariantCheck() } - XCTAssertTrue(rope.isEmpty) - XCTAssertEqual(rope.summary, .zero) + XCTAssertTrue(_rope.isEmpty) + XCTAssertEqual(_rope.summary, .zero) } func test_join() { @@ -441,91 +441,91 @@ class TestRope: XCTestCase { } func test_removeSubrange_simple() { - var rope = _Rope() + var _rope = _Rope() for i in 0 ..< 10 { - rope.append(Chunk(length: 10, value: i)) + _rope.append(Chunk(length: 10, value: i)) } let ref = (0 ..< 10).flatMap { Array(repeating: $0, count: 10) } // Basics - checkRemoveSubrange(rope, ref, range: 0 ..< 0) - checkRemoveSubrange(rope, ref, range: 30 ..< 30) - checkRemoveSubrange(rope, ref, range: 0 ..< 100) + checkRemoveSubrange(_rope, ref, range: 0 ..< 0) + checkRemoveSubrange(_rope, ref, range: 30 ..< 30) + checkRemoveSubrange(_rope, ref, range: 0 ..< 100) // Whole individual chunks - checkRemoveSubrange(rope, ref, range: 90 ..< 100) - checkRemoveSubrange(rope, ref, range: 0 ..< 10) - checkRemoveSubrange(rope, ref, range: 30 ..< 40) - checkRemoveSubrange(rope, ref, range: 70 ..< 80) + checkRemoveSubrange(_rope, ref, range: 90 ..< 100) + checkRemoveSubrange(_rope, ref, range: 0 ..< 10) + checkRemoveSubrange(_rope, ref, range: 30 ..< 40) + checkRemoveSubrange(_rope, ref, range: 70 ..< 80) // Prefixes of single chunks - checkRemoveSubrange(rope, ref, range: 0 ..< 1) - checkRemoveSubrange(rope, ref, range: 30 ..< 35) - checkRemoveSubrange(rope, ref, range: 60 ..< 66) - checkRemoveSubrange(rope, ref, range: 90 ..< 98) + checkRemoveSubrange(_rope, ref, range: 0 ..< 1) + checkRemoveSubrange(_rope, ref, range: 30 ..< 35) + checkRemoveSubrange(_rope, ref, range: 60 ..< 66) + checkRemoveSubrange(_rope, ref, range: 90 ..< 98) // Suffixes of single chunks - checkRemoveSubrange(rope, ref, range: 9 ..< 10) - checkRemoveSubrange(rope, ref, range: 35 ..< 40) - checkRemoveSubrange(rope, ref, range: 64 ..< 70) - checkRemoveSubrange(rope, ref, range: 98 ..< 100) + checkRemoveSubrange(_rope, ref, range: 9 ..< 10) + checkRemoveSubrange(_rope, ref, range: 35 ..< 40) + checkRemoveSubrange(_rope, ref, range: 64 ..< 70) + checkRemoveSubrange(_rope, ref, range: 98 ..< 100) // Neighboring couple of whole chunks - checkRemoveSubrange(rope, ref, range: 0 ..< 20) - checkRemoveSubrange(rope, ref, range: 80 ..< 100) - checkRemoveSubrange(rope, ref, range: 10 ..< 30) - checkRemoveSubrange(rope, ref, range: 50 ..< 70) // Crosses nodes! + checkRemoveSubrange(_rope, ref, range: 0 ..< 20) + checkRemoveSubrange(_rope, ref, range: 80 ..< 100) + checkRemoveSubrange(_rope, ref, range: 10 ..< 30) + checkRemoveSubrange(_rope, ref, range: 50 ..< 70) // Crosses nodes! // Longer whole chunk sequences - checkRemoveSubrange(rope, ref, range: 0 ..< 30) - checkRemoveSubrange(rope, ref, range: 70 ..< 90) - checkRemoveSubrange(rope, ref, range: 0 ..< 60) // entire first node - checkRemoveSubrange(rope, ref, range: 60 ..< 100) // entire second node - checkRemoveSubrange(rope, ref, range: 40 ..< 70) // crosses into second node - checkRemoveSubrange(rope, ref, range: 10 ..< 90) // crosses into second node + checkRemoveSubrange(_rope, ref, range: 0 ..< 30) + checkRemoveSubrange(_rope, ref, range: 70 ..< 90) + checkRemoveSubrange(_rope, ref, range: 0 ..< 60) // entire first node + checkRemoveSubrange(_rope, ref, range: 60 ..< 100) // entire second node + checkRemoveSubrange(_rope, ref, range: 40 ..< 70) // crosses into second node + checkRemoveSubrange(_rope, ref, range: 10 ..< 90) // crosses into second node // Arbitrary cuts - checkRemoveSubrange(rope, ref, range: 0 ..< 69) - checkRemoveSubrange(rope, ref, range: 42 ..< 73) - checkRemoveSubrange(rope, ref, range: 21 ..< 89) - checkRemoveSubrange(rope, ref, range: 1 ..< 99) - checkRemoveSubrange(rope, ref, range: 1 ..< 59) - checkRemoveSubrange(rope, ref, range: 61 ..< 99) + checkRemoveSubrange(_rope, ref, range: 0 ..< 69) + checkRemoveSubrange(_rope, ref, range: 42 ..< 73) + checkRemoveSubrange(_rope, ref, range: 21 ..< 89) + checkRemoveSubrange(_rope, ref, range: 1 ..< 99) + checkRemoveSubrange(_rope, ref, range: 1 ..< 59) + checkRemoveSubrange(_rope, ref, range: 61 ..< 99) } func test_removeSubrange_larger() { - var rope = _Rope() + var _rope = _Rope() for i in 0 ..< 100 { - rope.append(Chunk(length: 10, value: i)) + _rope.append(Chunk(length: 10, value: i)) } let ref = (0 ..< 100).flatMap { Array(repeating: $0, count: 10) } - checkRemoveSubrange(rope, ref, range: 0 ..< 0) - checkRemoveSubrange(rope, ref, range: 0 ..< 1000) - checkRemoveSubrange(rope, ref, range: 0 ..< 100) - checkRemoveSubrange(rope, ref, range: 900 ..< 1000) - checkRemoveSubrange(rope, ref, range: 120 ..< 330) - checkRemoveSubrange(rope, ref, range: 734 ..< 894) - checkRemoveSubrange(rope, ref, range: 183 ..< 892) + checkRemoveSubrange(_rope, ref, range: 0 ..< 0) + checkRemoveSubrange(_rope, ref, range: 0 ..< 1000) + checkRemoveSubrange(_rope, ref, range: 0 ..< 100) + checkRemoveSubrange(_rope, ref, range: 900 ..< 1000) + checkRemoveSubrange(_rope, ref, range: 120 ..< 330) + checkRemoveSubrange(_rope, ref, range: 734 ..< 894) + checkRemoveSubrange(_rope, ref, range: 183 ..< 892) - checkRemoveSubrange(rope, ref, range: 181 ..< 479) - checkRemoveSubrange(rope, ref, range: 191 ..< 469) - checkRemoveSubrange(rope, ref, range: 2 ..< 722) - checkRemoveSubrange(rope, ref, range: 358 ..< 718) - checkRemoveSubrange(rope, ref, range: 12 ..< 732) - checkRemoveSubrange(rope, ref, range: 348 ..< 728) - checkRemoveSubrange(rope, ref, range: 63 ..< 783) - checkRemoveSubrange(rope, ref, range: 297 ..< 655) + checkRemoveSubrange(_rope, ref, range: 181 ..< 479) + checkRemoveSubrange(_rope, ref, range: 191 ..< 469) + checkRemoveSubrange(_rope, ref, range: 2 ..< 722) + checkRemoveSubrange(_rope, ref, range: 358 ..< 718) + checkRemoveSubrange(_rope, ref, range: 12 ..< 732) + checkRemoveSubrange(_rope, ref, range: 348 ..< 728) + checkRemoveSubrange(_rope, ref, range: 63 ..< 783) + checkRemoveSubrange(_rope, ref, range: 297 ..< 655) } func test_removeSubrange_random() { for iteration in 0 ..< 20 { var rng = RepeatableRandomNumberGenerator(seed: iteration) let c = 1000 - var rope = _Rope() + var _rope = _Rope() for i in 0 ..< c { - rope.append(Chunk(length: 2, value: i)) + _rope.append(Chunk(length: 2, value: i)) } var ref = (0 ..< c).flatMap { Array(repeating: $0, count: 2) } @@ -533,9 +533,9 @@ class TestRope: XCTestCase { print(ref.count) let i = (0 ..< ref.count).randomElement(using: &rng)! let j = (i + 1 ... ref.count).randomElement(using: &rng)! - rope.removeSubrange(i ..< j, in: Chunk.Metric()) + _rope.removeSubrange(i ..< j, in: Chunk.Metric()) ref.removeSubrange(i ..< j) - checkEqual(rope, ref) + checkEqual(_rope, ref) } } } From 51ef8613c2058c7a35e7da7c27a1c4d48e6ab8b2 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 22:27:32 -0700 Subject: [PATCH 072/113] Underscore more internals --- .../BigString/Basics/BigString+Builder.swift | 18 +- .../BigString/Basics/BigString+Contents.swift | 212 +++++++++--------- .../BigString/Basics/BigString+Index.swift | 4 +- .../BigString/Basics/BigString+Ingester.swift | 38 ++-- .../BigString/Basics/BigString+Metrics.swift | 40 ++-- .../BigString/Basics/BigString+Summary.swift | 2 +- .../BigString/Basics/BigString.swift | 2 +- .../BigString+Chunk+Append and Insert.swift | 16 +- .../Chunk/BigString+Chunk+Breaks.swift | 4 +- .../Chunk/BigString+Chunk+Counts.swift | 10 +- .../Chunk/BigString+Chunk+Description.swift | 2 +- ...gString+Chunk+Indexing by Characters.swift | 2 +- .../BigString+Chunk+Indexing by UTF16.swift | 2 +- .../Chunk/BigString+Chunk+RopeElement.swift | 8 +- .../Chunk/BigString+Chunk+Splitting.swift | 2 +- .../BigString/Chunk/BigString+Chunk.swift | 12 +- .../BigString+BidirectionalCollection.swift | 20 +- .../Conformances/BigString+Equatable.swift | 8 +- .../Operations/BigString+Append.swift | 8 +- .../Operations/BigString+Initializers.swift | 16 +- .../Operations/BigString+Insert.swift | 2 +- .../BigString+Managing Breaks.swift | 4 +- .../Operations/BigString+RemoveSubrange.swift | 4 +- .../BigString+ReplaceSubrange.swift | 4 +- .../Operations/BigString+Split.swift | 4 +- .../BigString/Views/BigString+UTF16View.swift | 20 +- .../BigString/Views/BigString+UTF8View.swift | 20 +- .../Views/BigString+UnicodeScalarView.swift | 20 +- .../Views/BigSubstring+UTF16View.swift | 20 +- .../Views/BigSubstring+UTF8View.swift | 20 +- .../BigSubstring+UnicodeScalarView.swift | 34 +-- .../BigString/Views/BigSubstring.swift | 32 +-- .../Utilities/_CharacterRecognizer.swift | 2 +- 33 files changed, 307 insertions(+), 305 deletions(-) diff --git a/Sources/RopeModule/BigString/Basics/BigString+Builder.swift b/Sources/RopeModule/BigString/Basics/BigString+Builder.swift index e810573a..a68bafb9 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Builder.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Builder.swift @@ -14,8 +14,8 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { struct Builder { - typealias Chunk = BigString.Chunk - typealias Ingester = BigString.Ingester + typealias _Chunk = BigString._Chunk + typealias _Ingester = BigString._Ingester typealias _Storage = BigString._Storage var base: _Storage.Builder @@ -41,11 +41,11 @@ extension BigString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _Rope.Builder { - func breakState() -> _CharacterRecognizer { +extension _Rope.Builder { + internal func _breakState() -> _CharacterRecognizer { let chars = self.prefixSummary.characters assert(self.isPrefixEmpty || chars > 0) - let metric = BigString.CharacterMetric() + let metric = BigString._CharacterMetric() var state = _CharacterRecognizer() _ = self.forEachElementInPrefix(from: chars - 1, in: metric) { chunk, i in if let i { @@ -71,7 +71,7 @@ extension BigString.Builder { mutating func append(_ str: __owned Substring) { guard !str.isEmpty else { return } - var ingester = Ingester(str, startState: self.prefixEndState) + var ingester = _Ingester(str, startState: self.prefixEndState) if var prefix = base.prefix._take() { if let slice = ingester.nextSlice(maxUTF8Count: prefix.value.availableSpace) { prefix.value._append(slice) @@ -84,12 +84,12 @@ extension BigString.Builder { self.prefixEndState = ingester.state } - mutating func append(_ newChunk: __owned Chunk) { + mutating func append(_ newChunk: __owned _Chunk) { var state = _CharacterRecognizer() append(newChunk, state: &state) } - mutating func append(_ newChunk: __owned Chunk, state: inout _CharacterRecognizer) { + mutating func append(_ newChunk: __owned _Chunk, state: inout _CharacterRecognizer) { var newChunk = newChunk newChunk.resyncBreaksFromStartToEnd(old: &state, new: &self.prefixEndState) self.base.append(newChunk) @@ -112,7 +112,7 @@ extension BigString.Builder { self.base.append(other._rope) } - mutating func append(from ingester: inout Ingester) { + mutating func append(from ingester: inout _Ingester) { //assert(ingester.state._isKnownEqual(to: self.prefixEndState)) if var prefix = base.prefix._take() { if let first = ingester.nextSlice(maxUTF8Count: prefix.value.availableSpace) { diff --git a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift index 6d06d862..068186b8 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift @@ -18,7 +18,7 @@ extension BigString { /// of the deepest tree where every node is the minimum possible size. public static var _minimumCapacity: Int { let c = _Storage.minimumCapacity - let (r, overflow) = Chunk.minUTF8Count.multipliedReportingOverflow(by: c) + let (r, overflow) = _Chunk.minUTF8Count.multipliedReportingOverflow(by: c) guard !overflow else { return Int.max } return r } @@ -27,7 +27,7 @@ extension BigString { /// possible case, when every node in the underlying tree is fully filled with data. public static var _maximumCapacity: Int { let c = _Storage.maximumCapacity - let (r, overflow) = Chunk.maxUTF8Count.multipliedReportingOverflow(by: c) + let (r, overflow) = _Chunk.maxUTF8Count.multipliedReportingOverflow(by: c) guard !overflow else { return Int.max } return r } @@ -35,15 +35,15 @@ extension BigString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - var characterCount: Int { _rope.summary.characters } - var unicodeScalarCount: Int { _rope.summary.unicodeScalars } - var utf16Count: Int { _rope.summary.utf16 } - var utf8Count: Int { _rope.summary.utf8 } + var _characterCount: Int { _rope.summary.characters } + var _unicodeScalarCount: Int { _rope.summary.unicodeScalars } + var _utf16Count: Int { _rope.summary.utf16 } + var _utf8Count: Int { _rope.summary.utf8 } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - func distance( + func _distance( from start: Index, to end: Index, in metric: some _StringMetric @@ -72,19 +72,19 @@ extension BigString { return start <= end ? d : -d } - func characterDistance(from start: Index, to end: Index) -> Int { - distance(from: start, to: end, in: CharacterMetric()) + func _characterDistance(from start: Index, to end: Index) -> Int { + _distance(from: start, to: end, in: _CharacterMetric()) } - func unicodeScalarDistance(from start: Index, to end: Index) -> Int { - distance(from: start, to: end, in: UnicodeScalarMetric()) + func _unicodeScalarDistance(from start: Index, to end: Index) -> Int { + _distance(from: start, to: end, in: _UnicodeScalarMetric()) } - func utf16Distance(from start: Index, to end: Index) -> Int { - distance(from: start, to: end, in: UTF16Metric()) + func _utf16Distance(from start: Index, to end: Index) -> Int { + _distance(from: start, to: end, in: _UTF16Metric()) } - func utf8Distance(from start: Index, to end: Index) -> Int { + func _utf8Distance(from start: Index, to end: Index) -> Int { end.utf8Offset - start.utf8Offset } } @@ -93,20 +93,20 @@ extension BigString { extension BigString { // FIXME: See if we need direct implementations for these. - func characterOffset(of index: Index) -> Int { - characterDistance(from: startIndex, to: index) + func _characterOffset(of index: Index) -> Int { + _characterDistance(from: startIndex, to: index) } - func unicodeScalarOffset(of index: Index) -> Int { - unicodeScalarDistance(from: startIndex, to: index) + func _unicodeScalarOffset(of index: Index) -> Int { + _unicodeScalarDistance(from: startIndex, to: index) } - func utf16Offset(of index: Index) -> Int { - utf16Distance(from: startIndex, to: index) + func _utf16Offset(of index: Index) -> Int { + _utf16Distance(from: startIndex, to: index) } - func utf8Offset(of index: Index) -> Int { - utf8Distance(from: startIndex, to: index) + func _utf8Offset(of index: Index) -> Int { + _utf8Distance(from: startIndex, to: index) } } @@ -114,26 +114,26 @@ extension BigString { extension BigString { // FIXME: See if we need direct implementations for these. - func characterIndex(at offset: Int) -> Index { - characterIndex(startIndex, offsetBy: offset) + func _characterIndex(at offset: Int) -> Index { + _characterIndex(startIndex, offsetBy: offset) } - func unicodeScalarIndex(at offset: Int) -> Index { - unicodeScalarIndex(startIndex, offsetBy: offset) + func _unicodeScalarIndex(at offset: Int) -> Index { + _unicodeScalarIndex(startIndex, offsetBy: offset) } - func utf16Index(at offset: Int) -> Index { - utf16Index(startIndex, offsetBy: offset) + func _utf16Index(at offset: Int) -> Index { + _utf16Index(startIndex, offsetBy: offset) } - func utf8Index(at offset: Int) -> Index { - utf8Index(startIndex, offsetBy: offset) + func _utf8Index(at offset: Int) -> Index { + _utf8Index(startIndex, offsetBy: offset) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - func index( + func _index( _ i: Index, offsetBy distance: Int, in metric: some _StringMetric @@ -165,7 +165,7 @@ extension BigString { } chunk = _rope[ri] ci = metric.index(at: d, in: chunk) - let base = i._utf8BaseOffset + _rope.distance(from: start, to: ri, in: UTF8Metric()) + let base = i._utf8BaseOffset + _rope.distance(from: start, to: ri, in: _UTF8Metric()) return Index(baseUTF8Offset: base, _rope: ri, chunk: ci) } @@ -175,30 +175,30 @@ extension BigString { _rope.formIndex(&ri, offsetBy: &d, in: metric, preferEnd: false) chunk = _rope[ri] ci = metric.index(at: d, in: chunk) - let base = i._utf8BaseOffset + _rope.distance(from: start, to: ri, in: UTF8Metric()) + let base = i._utf8BaseOffset + _rope.distance(from: start, to: ri, in: _UTF8Metric()) return Index(baseUTF8Offset: base, _rope: ri, chunk: ci) } - func characterIndex(_ i: Index, offsetBy distance: Int) -> Index { - index(i, offsetBy: distance, in: CharacterMetric())._knownCharacterAligned() + func _characterIndex(_ i: Index, offsetBy distance: Int) -> Index { + _index(i, offsetBy: distance, in: _CharacterMetric())._knownCharacterAligned() } - func unicodeScalarIndex(_ i: Index, offsetBy distance: Int) -> Index { - index(i, offsetBy: distance, in: UnicodeScalarMetric())._knownScalarAligned() + func _unicodeScalarIndex(_ i: Index, offsetBy distance: Int) -> Index { + _index(i, offsetBy: distance, in: _UnicodeScalarMetric())._knownScalarAligned() } - func utf16Index(_ i: Index, offsetBy distance: Int) -> Index { - index(i, offsetBy: distance, in: UTF16Metric()) + func _utf16Index(_ i: Index, offsetBy distance: Int) -> Index { + _index(i, offsetBy: distance, in: _UTF16Metric()) } - func utf8Index(_ i: Index, offsetBy distance: Int) -> Index { - index(i, offsetBy: distance, in: UTF8Metric()) + func _utf8Index(_ i: Index, offsetBy distance: Int) -> Index { + _index(i, offsetBy: distance, in: _UTF8Metric()) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - func index( + func _index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index, @@ -207,56 +207,56 @@ extension BigString { // FIXME: Do we need a direct implementation? if distance >= 0 { if limit >= i { - let d = self.distance(from: i, to: limit, in: metric) + let d = self._distance(from: i, to: limit, in: metric) if d < distance { return nil } } } else { if limit <= i { - let d = self.distance(from: i, to: limit, in: metric) + let d = self._distance(from: i, to: limit, in: metric) if d > distance { return nil } } } - return self.index(i, offsetBy: distance, in: metric) + return self._index(i, offsetBy: distance, in: metric) } - func characterIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - guard let j = index(i, offsetBy: distance, limitedBy: limit, in: CharacterMetric()) else { + func _characterIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + guard let j = _index(i, offsetBy: distance, limitedBy: limit, in: _CharacterMetric()) else { return nil } return j._knownCharacterAligned() } - func unicodeScalarIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - guard let j = index(i, offsetBy: distance, limitedBy: limit, in: UnicodeScalarMetric()) else { + func _unicodeScalarIndex(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + guard let j = _index(i, offsetBy: distance, limitedBy: limit, in: _UnicodeScalarMetric()) else { return nil } return j._knownScalarAligned() } - func utf16Index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - index(i, offsetBy: distance, limitedBy: limit, in: UTF16Metric()) + func _utf16Index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _index(i, offsetBy: distance, limitedBy: limit, in: _UTF16Metric()) } - func utf8Index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - index(i, offsetBy: distance, limitedBy: limit, in: UTF8Metric()) + func _utf8Index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _index(i, offsetBy: distance, limitedBy: limit, in: _UTF8Metric()) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - func characterIndex(after i: Index) -> Index { - index(i, offsetBy: 1, in: CharacterMetric())._knownCharacterAligned() + func _characterIndex(after i: Index) -> Index { + _index(i, offsetBy: 1, in: _CharacterMetric())._knownCharacterAligned() } - func unicodeScalarIndex(after i: Index) -> Index { - index(i, offsetBy: 1, in: UnicodeScalarMetric())._knownScalarAligned() + func _unicodeScalarIndex(after i: Index) -> Index { + _index(i, offsetBy: 1, in: _UnicodeScalarMetric())._knownScalarAligned() } - func utf16Index(after i: Index) -> Index { - index(i, offsetBy: 1, in: UTF16Metric()) + func _utf16Index(after i: Index) -> Index { + _index(i, offsetBy: 1, in: _UTF16Metric()) } - func utf8Index(after i: Index) -> Index { + func _utf8Index(after i: Index) -> Index { precondition(i < endIndex, "Can't advance above end index") let i = resolve(i, preferEnd: false) let ri = i._rope! @@ -275,19 +275,19 @@ extension BigString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - func characterIndex(before i: Index) -> Index { - index(i, offsetBy: -1, in: CharacterMetric())._knownCharacterAligned() + func _characterIndex(before i: Index) -> Index { + _index(i, offsetBy: -1, in: _CharacterMetric())._knownCharacterAligned() } - func unicodeScalarIndex(before i: Index) -> Index { - index(i, offsetBy: -1, in: UnicodeScalarMetric())._knownScalarAligned() + func _unicodeScalarIndex(before i: Index) -> Index { + _index(i, offsetBy: -1, in: _UnicodeScalarMetric())._knownScalarAligned() } - func utf16Index(before i: Index) -> Index { - index(i, offsetBy: -1, in: UTF16Metric()) + func _utf16Index(before i: Index) -> Index { + _index(i, offsetBy: -1, in: _UTF16Metric()) } - func utf8Index(before i: Index) -> Index { + func _utf8Index(before i: Index) -> Index { precondition(i > startIndex, "Can't advance below start index") let i = resolve(i, preferEnd: true) var ri = i._rope! @@ -309,11 +309,11 @@ extension BigString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - func characterIndex(roundingDown i: Index) -> Index { + func _characterIndex(roundingDown i: Index) -> Index { let offset = i.utf8Offset - precondition(offset >= 0 && offset <= utf8Count, "Index out of bounds") + precondition(offset >= 0 && offset <= _utf8Count, "Index out of bounds") guard offset > 0 else { return resolve(i, preferEnd: false)._knownCharacterAligned() } - guard offset < utf8Count else { return resolve(i, preferEnd: true)._knownCharacterAligned() } + guard offset < _utf8Count else { return resolve(i, preferEnd: true)._knownCharacterAligned() } let i = resolve(i, preferEnd: false) guard !i._isKnownCharacterAligned else { return resolve(i, preferEnd: false) } @@ -348,7 +348,7 @@ extension BigString { )._knownCharacterAligned() } - func unicodeScalarIndex(roundingDown i: Index) -> Index { + func _unicodeScalarIndex(roundingDown i: Index) -> Index { precondition(i <= endIndex, "Index out of bounds") guard i > startIndex else { return resolve(i, preferEnd: false)._knownCharacterAligned() } guard i < endIndex else { return resolve(i, preferEnd: true)._knownCharacterAligned() } @@ -361,7 +361,7 @@ extension BigString { return Index(baseUTF8Offset: start._utf8BaseOffset, _rope: ri, chunk: ci)._knownScalarAligned() } - func utf8Index(roundingDown i: Index) -> Index { + func _utf8Index(roundingDown i: Index) -> Index { precondition(i <= endIndex, "Index out of bounds") guard i < endIndex else { return endIndex } var r = i @@ -371,52 +371,52 @@ extension BigString { return resolve(r, preferEnd: false) } - func utf16Index(roundingDown i: Index) -> Index { + func _utf16Index(roundingDown i: Index) -> Index { if i._isUTF16TrailingSurrogate { precondition(i < endIndex, "Index out of bounds") // (We know i can't be the endIndex -- it addresses a trailing surrogate.) return self.resolve(i, preferEnd: false) } - return unicodeScalarIndex(roundingDown: i) + return _unicodeScalarIndex(roundingDown: i) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - func characterIndex(roundingUp i: Index) -> Index { - let j = characterIndex(roundingDown: i) + func _characterIndex(roundingUp i: Index) -> Index { + let j = _characterIndex(roundingDown: i) if i == j { return j } - return characterIndex(after: j) + return _characterIndex(after: j) } - func unicodeScalarIndex(roundingUp i: Index) -> Index { - let j = unicodeScalarIndex(roundingDown: i) + func _unicodeScalarIndex(roundingUp i: Index) -> Index { + let j = _unicodeScalarIndex(roundingDown: i) if i == j { return j } - return unicodeScalarIndex(after: j) + return _unicodeScalarIndex(after: j) } - func utf8Index(roundingUp i: Index) -> Index { + func _utf8Index(roundingUp i: Index) -> Index { // Note: this orders UTF-16 trailing surrogate indices in between the first and second byte // of the UTF-8 encoding. - let j = utf8Index(roundingDown: i) + let j = _utf8Index(roundingDown: i) if i == j { return j } - return utf8Index(after: j) + return _utf8Index(after: j) } - func utf16Index(roundingUp i: Index) -> Index { + func _utf16Index(roundingUp i: Index) -> Index { // Note: if `i` addresses some byte in the middle of a non-BMP scalar then the result will // point to the trailing surrogate. - let j = utf16Index(roundingDown: i) + let j = _utf16Index(roundingDown: i) if i == j { return j } - return utf16Index(after: j) + return _utf16Index(after: j) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { func _character(at start: Index) -> (character: Character, end: Index) { - let start = characterIndex(roundingDown: start) - precondition(start.utf8Offset < utf8Count, "Index out of bounds") + let start = _characterIndex(roundingDown: start) + precondition(start.utf8Offset < _utf8Count, "Index out of bounds") var ri = start._rope! var ci = start._chunkIndex @@ -449,49 +449,49 @@ extension BigString { return (Character(s), Index(baseUTF8Offset: base, _rope: ri, chunk: ci)._knownCharacterAligned()) } - subscript(utf8 index: Index) -> UInt8 { + subscript(_utf8 index: Index) -> UInt8 { precondition(index < endIndex, "Index out of bounds") let index = resolve(index, preferEnd: false) return _rope[index._rope!].string.utf8[index._chunkIndex] } - subscript(utf8 offset: Int) -> UInt8 { - precondition(offset >= 0 && offset < utf8Count, "Offset out of bounds") - let index = utf8Index(at: offset) - return self[utf8: index] + subscript(_utf8 offset: Int) -> UInt8 { + precondition(offset >= 0 && offset < _utf8Count, "Offset out of bounds") + let index = _utf8Index(at: offset) + return self[_utf8: index] } - subscript(utf16 index: Index) -> UInt16 { + subscript(_utf16 index: Index) -> UInt16 { precondition(index < endIndex, "Index out of bounds") let index = resolve(index, preferEnd: false) return _rope[index._rope!].string.utf16[index._chunkIndex] } - subscript(utf16 offset: Int) -> UInt16 { - precondition(offset >= 0 && offset < utf16Count, "Offset out of bounds") - let index = utf16Index(at: offset) - return self[utf16: index] + subscript(_utf16 offset: Int) -> UInt16 { + precondition(offset >= 0 && offset < _utf16Count, "Offset out of bounds") + let index = _utf16Index(at: offset) + return self[_utf16: index] } - subscript(character index: Index) -> Character { + subscript(_character index: Index) -> Character { _character(at: index).character } - subscript(character offset: Int) -> Character { - precondition(offset >= 0 && offset < utf8Count, "Offset out of bounds") + subscript(_character offset: Int) -> Character { + precondition(offset >= 0 && offset < _utf8Count, "Offset out of bounds") return _character(at: Index(_utf8Offset: offset)).character } - subscript(unicodeScalar index: Index) -> Unicode.Scalar { + subscript(_unicodeScalar index: Index) -> Unicode.Scalar { precondition(index < endIndex, "Index out of bounds") let index = resolve(index, preferEnd: false) return _rope[index._rope!].string.unicodeScalars[index._chunkIndex] } - subscript(unicodeScalar offset: Int) -> Unicode.Scalar { - precondition(offset >= 0 && offset < unicodeScalarCount, "Offset out of bounds") - let index = unicodeScalarIndex(at: offset) - return self[unicodeScalar: index] + subscript(_unicodeScalar offset: Int) -> Unicode.Scalar { + precondition(offset >= 0 && offset < _unicodeScalarCount, "Offset out of bounds") + let index = _unicodeScalarIndex(at: offset) + return self[_unicodeScalar: index] } } diff --git a/Sources/RopeModule/BigString/Basics/BigString+Index.swift b/Sources/RopeModule/BigString/Basics/BigString+Index.swift index 44174eb8..302f2236 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Index.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Index.swift @@ -220,7 +220,7 @@ extension BigString { j._flags = i._flags return j } - guard i.utf8Offset < utf8Count, i._utf8ChunkOffset == _rope[ri].utf8Count else { + guard i.utf8Offset < _utf8Count, i._utf8ChunkOffset == _rope[ri].utf8Count else { return i } _rope.formIndex(after: &ri) @@ -231,7 +231,7 @@ extension BigString { } let (ri, chunkOffset) = _rope.find( - at: i.utf8Offset, in: UTF8Metric(), preferEnd: preferEnd) + at: i.utf8Offset, in: _UTF8Metric(), preferEnd: preferEnd) let ci = String.Index( _utf8Offset: chunkOffset, utf16TrailingSurrogate: i._isUTF16TrailingSurrogate) return Index(baseUTF8Offset: i.utf8Offset - ci._utf8Offset, _rope: ri, chunk: ci) diff --git a/Sources/RopeModule/BigString/Basics/BigString+Ingester.swift b/Sources/RopeModule/BigString/Basics/BigString+Ingester.swift index 458edf72..ecb50543 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Ingester.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Ingester.swift @@ -13,22 +13,22 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - func ingester( + func _ingester( forInserting input: __owned Substring, at index: Index, allowForwardPeek: Bool - ) -> Ingester { + ) -> _Ingester { let hint = allowForwardPeek ? input.unicodeScalars.first : nil let state = self._breakState(upTo: index, nextScalarHint: hint) - return Ingester(input, startState: state) + return _Ingester(input, startState: state) } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - struct Ingester { - typealias Chunk = BigString.Chunk - typealias Counts = BigString.Chunk.Counts + internal struct _Ingester { + typealias _Chunk = BigString._Chunk + typealias Counts = BigString._Chunk.Counts var input: Substring @@ -67,8 +67,8 @@ extension BigString { } mutating func nextSlice( - maxUTF8Count: Int = Chunk.maxUTF8Count - ) -> Chunk.Slice? { + maxUTF8Count: Int = _Chunk.maxUTF8Count + ) -> _Chunk.Slice? { guard let range = input.base._nextSlice( after: start, limit: input.endIndex, maxUTF8Count: maxUTF8Count) else { @@ -110,29 +110,29 @@ extension BigString { suffix: suffixCount) } - mutating func nextChunk(maxUTF8Count: Int = Chunk.maxUTF8Count) -> Chunk? { + mutating func nextChunk(maxUTF8Count: Int = _Chunk.maxUTF8Count) -> _Chunk? { guard let slice = nextSlice(maxUTF8Count: maxUTF8Count) else { return nil } - return Chunk(slice) + return _Chunk(slice) } static func desiredNextChunkSize(remaining: Int) -> Int { - if remaining <= Chunk.maxUTF8Count { + if remaining <= _Chunk.maxUTF8Count { return remaining } - if remaining >= Chunk.maxUTF8Count + Chunk.minUTF8Count { - return Chunk.maxUTF8Count + if remaining >= _Chunk.maxUTF8Count + _Chunk.minUTF8Count { + return _Chunk.maxUTF8Count } - return remaining - Chunk.minUTF8Count + return remaining - _Chunk.minUTF8Count } - mutating func nextWellSizedSlice(suffix: Int = 0) -> Chunk.Slice? { + mutating func nextWellSizedSlice(suffix: Int = 0) -> _Chunk.Slice? { let desired = Self.desiredNextChunkSize(remaining: remainingUTF8 + suffix) return nextSlice(maxUTF8Count: desired) } - mutating func nextWellSizedChunk(suffix: Int = 0) -> Chunk? { + mutating func nextWellSizedChunk(suffix: Int = 0) -> _Chunk? { guard let slice = nextWellSizedSlice(suffix: suffix) else { return nil } - return Chunk(slice) + return _Chunk(slice) } } } @@ -154,11 +154,11 @@ extension String { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { init(_ string: String) { guard !string.isEmpty else { self.init(); return } assert(string.utf8.count <= Self.maxUTF8Count) - var ingester = BigString.Ingester(string) + var ingester = BigString._Ingester(string) self = ingester.nextChunk()! assert(ingester.isAtEnd) } diff --git a/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift index b39258b5..0d680120 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift @@ -12,24 +12,24 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -internal protocol _StringMetric: _RopeMetric where Element == BigString.Chunk { +internal protocol _StringMetric: _RopeMetric where Element == BigString._Chunk { func distance( from start: String.Index, to end: String.Index, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> Int func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> (found: Bool, forward: Bool) } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - internal struct CharacterMetric: _StringMetric { - typealias Element = BigString.Chunk + internal struct _CharacterMetric: _StringMetric { + typealias Element = BigString._Chunk typealias Summary = BigString.Summary @inline(__always) @@ -40,7 +40,7 @@ extension BigString { func distance( from start: String.Index, to end: String.Index, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> Int { chunk.characterDistance(from: start, to: end) } @@ -48,18 +48,18 @@ extension BigString { func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> (found: Bool, forward: Bool) { chunk.formCharacterIndex(&i, offsetBy: &distance) } - func index(at offset: Int, in chunk: BigString.Chunk) -> String.Index { + func index(at offset: Int, in chunk: BigString._Chunk) -> String.Index { precondition(offset < chunk.characterCount) return chunk.wholeCharacters._index(at: offset) } } - internal struct UnicodeScalarMetric: _StringMetric { + internal struct _UnicodeScalarMetric: _StringMetric { @inline(__always) func size(of summary: Summary) -> Int { summary.unicodeScalars @@ -68,7 +68,7 @@ extension BigString { func distance( from start: String.Index, to end: String.Index, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> Int { chunk.string.unicodeScalars.distance(from: start, to: end) } @@ -76,7 +76,7 @@ extension BigString { func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> (found: Bool, forward: Bool) { guard distance != 0 else { i = chunk.string.unicodeScalars._index(roundingDown: i) @@ -98,12 +98,12 @@ extension BigString { return (distance == 0, false) } - func index(at offset: Int, in chunk: BigString.Chunk) -> String.Index { + func index(at offset: Int, in chunk: BigString._Chunk) -> String.Index { chunk.string.unicodeScalars.index(chunk.string.startIndex, offsetBy: offset) } } - internal struct UTF8Metric: _StringMetric { + internal struct _UTF8Metric: _StringMetric { @inline(__always) func size(of summary: Summary) -> Int { summary.utf8 @@ -112,7 +112,7 @@ extension BigString { func distance( from start: String.Index, to end: String.Index, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> Int { chunk.string.utf8.distance(from: start, to: end) } @@ -120,7 +120,7 @@ extension BigString { func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> (found: Bool, forward: Bool) { // Here we make use of the fact that the UTF-8 view of native Swift strings // have O(1) index distance & offset calculations. @@ -147,12 +147,12 @@ extension BigString { return (true, false) } - func index(at offset: Int, in chunk: BigString.Chunk) -> String.Index { + func index(at offset: Int, in chunk: BigString._Chunk) -> String.Index { chunk.string.utf8.index(chunk.string.startIndex, offsetBy: offset) } } - internal struct UTF16Metric: _StringMetric { + internal struct _UTF16Metric: _StringMetric { @inline(__always) func size(of summary: Summary) -> Int { summary.utf16 @@ -161,7 +161,7 @@ extension BigString { func distance( from start: String.Index, to end: String.Index, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> Int { chunk.string.utf16.distance(from: start, to: end) } @@ -169,7 +169,7 @@ extension BigString { func formIndex( _ i: inout String.Index, offsetBy distance: inout Int, - in chunk: BigString.Chunk + in chunk: BigString._Chunk ) -> (found: Bool, forward: Bool) { if distance >= 0 { if @@ -200,7 +200,7 @@ extension BigString { return (false, false) } - func index(at offset: Int, in chunk: BigString.Chunk) -> String.Index { + func index(at offset: Int, in chunk: BigString._Chunk) -> String.Index { chunk.string.utf16.index(chunk.string.startIndex, offsetBy: offset) } } diff --git a/Sources/RopeModule/BigString/Basics/BigString+Summary.swift b/Sources/RopeModule/BigString/Basics/BigString+Summary.swift index d4e72347..64f87dc9 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Summary.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Summary.swift @@ -28,7 +28,7 @@ extension BigString { utf8 = 0 } - init(_ chunk: BigString.Chunk) { + init(_ chunk: BigString._Chunk) { self.utf8 = chunk.utf8Count self.utf16 = Int(chunk.counts.utf16) self.unicodeScalars = Int(chunk.counts.unicodeScalars) diff --git a/Sources/RopeModule/BigString/Basics/BigString.swift b/Sources/RopeModule/BigString/Basics/BigString.swift index a32584a0..9a38da44 100644 --- a/Sources/RopeModule/BigString/Basics/BigString.swift +++ b/Sources/RopeModule/BigString/Basics/BigString.swift @@ -14,7 +14,7 @@ /// The core of a B-tree based String implementation. @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) public struct BigString: Sendable { - typealias _Storage = _Rope + typealias _Storage = _Rope<_Chunk> var _rope: _Storage diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift index 51af9b03..a4d4b8e0 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift @@ -12,13 +12,13 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { mutating func append(_ other: __owned Self) { self._append(other.string[...], other.counts) } - mutating func append(from ingester: inout BigString.Ingester) -> Self? { - let desired = BigString.Ingester.desiredNextChunkSize( + mutating func append(from ingester: inout BigString._Ingester) -> Self? { + let desired = BigString._Ingester.desiredNextChunkSize( remaining: self.utf8Count + ingester.remainingUTF8) if desired == self.utf8Count { return nil @@ -67,7 +67,7 @@ extension BigString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { mutating func _insert( _ slice: Slice, at index: String.Index, @@ -92,7 +92,7 @@ extension BigString.Chunk { typealias States = (increment: Int, old: _CharacterRecognizer, new: _CharacterRecognizer) mutating func insertAll( - from ingester: inout BigString.Ingester, + from ingester: inout BigString._Ingester, at index: String.Index ) -> States? { let remaining = ingester.remainingUTF8 @@ -110,12 +110,12 @@ extension BigString.Chunk { enum InsertResult { case inline(States?) - case split(spawn: BigString.Chunk, endStates: States?) + case split(spawn: BigString._Chunk, endStates: States?) case large } mutating func insert( - from ingester: inout BigString.Ingester, + from ingester: inout BigString._Ingester, at index: String.Index ) -> InsertResult { let origCount = self.utf8Count @@ -129,7 +129,7 @@ extension BigString.Chunk { return .inline(r) } - let desired = BigString.Ingester.desiredNextChunkSize(remaining: sum) + let desired = BigString._Ingester.desiredNextChunkSize(remaining: sum) guard sum - desired + Self.maxSlicingError <= Self.maxUTF8Count else { return .large } if desired <= offset { diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Breaks.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Breaks.swift index abaa74b1..f49b3fed 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Breaks.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Breaks.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { @inline(__always) var hasBreaks: Bool { counts.hasBreaks } @@ -41,7 +41,7 @@ extension BigString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { var immediateLastBreakState: _CharacterRecognizer? { guard hasBreaks else { return nil } return _CharacterRecognizer(partialCharacter: string[lastBreak...]) diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Counts.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Counts.swift index da4a4357..43313d94 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Counts.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Counts.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { struct Counts: Equatable { /// The number of UTF-8 code units within this chunk. var utf8: UInt8 @@ -87,7 +87,7 @@ extension BigString.Chunk { init(_ slice: Slice) { let c = slice.string.utf8.count - precondition(c <= BigString.Chunk.maxUTF8Count) + precondition(c <= BigString._Chunk.maxUTF8Count) self.init( utf8: slice.string.utf8.count, utf16: slice.string.utf16.count, @@ -100,7 +100,7 @@ extension BigString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk.Counts { +extension BigString._Chunk.Counts { var characters: Int { get { Int(_characters) } set { _characters = UInt8(newValue) } @@ -121,12 +121,12 @@ extension BigString.Chunk.Counts { } func hasSpaceToMerge(_ other: Self) -> Bool { - Int(utf8) + Int(other.utf8) <= BigString.Chunk.maxUTF8Count + Int(utf8) + Int(other.utf8) <= BigString._Chunk.maxUTF8Count } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk.Counts { +extension BigString._Chunk.Counts { mutating func append(_ other: Self) { assert(hasSpaceToMerge(other)) diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Description.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Description.swift index 75b9d164..8b7964c1 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Description.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Description.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk: CustomStringConvertible { +extension BigString._Chunk: CustomStringConvertible { var description: String { let counts = """ ❨\(utf8Count)⋅\(utf16Count)⋅\(unicodeScalarCount)⋅\(characterCount)❩ diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift index f4877cd9..199195a0 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by Characters.swift @@ -19,7 +19,7 @@ extension UInt8 { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { func characterDistance(from start: String.Index, to end: String.Index) -> Int { let firstBreak = self.firstBreak let (start, a) = start < firstBreak ? (firstBreak, 1) : (start, 0) diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by UTF16.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by UTF16.swift index e17349a0..e10d8f01 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by UTF16.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Indexing by UTF16.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { /// UTF-16 index lookup. func index(at utf8Offset: Int, utf16TrailingSurrogate: Bool) -> String.Index { var index = string._utf8Index(at: utf8Offset) diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift index 7dcfc286..ea62fb5c 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk: _RopeElement { +extension BigString._Chunk: _RopeElement { typealias Summary = BigString.Summary typealias Index = String.Index @@ -65,7 +65,7 @@ extension BigString.Chunk: _RopeElement { guard !right.isEmpty else { return true } guard self.isUndersized || right.isUndersized else { return false } let sum = self.utf8Count + right.utf8Count - let desired = BigString.Ingester.desiredNextChunkSize(remaining: sum) + let desired = BigString._Ingester.desiredNextChunkSize(remaining: sum) precondition(desired != self.utf8Count) if desired < self.utf8Count { @@ -89,7 +89,7 @@ extension BigString.Chunk: _RopeElement { guard !left.isEmpty else { return true } guard left.isUndersized || self.isUndersized else { return false } let sum = left.utf8Count + self.utf8Count - let desired = BigString.Ingester.desiredNextChunkSize(remaining: sum) + let desired = BigString._Ingester.desiredNextChunkSize(remaining: sum) precondition(desired != self.utf8Count) if desired < self.utf8Count { @@ -117,7 +117,7 @@ extension BigString.Chunk: _RopeElement { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { static func _redistributeData( _ left: inout Self, _ right: inout Self, diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Splitting.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Splitting.swift index dcff9e3f..ca48a9c7 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Splitting.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Splitting.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { func splitCounts(at i: String.Index) -> (left: Counts, right: Counts) { precondition(i <= string.endIndex) guard i < string.endIndex else { diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift index ac9a5111..530966e1 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - struct Chunk { + internal struct _Chunk { typealias Slice = (string: Substring, characters: Int, prefix: Int, suffix: Int) var string: String @@ -47,7 +47,7 @@ extension BigString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { @inline(__always) static var maxUTF8Count: Int { 255 } @@ -59,7 +59,7 @@ extension BigString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { @inline(__always) mutating func take() -> Self { let r = self @@ -76,7 +76,7 @@ extension BigString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { @inline(__always) var characterCount: Int { counts.characters } @@ -100,7 +100,7 @@ extension BigString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { var availableSpace: Int { Swift.max(0, Self.maxUTF8Count - utf8Count) } mutating func clear() { @@ -110,7 +110,7 @@ extension BigString.Chunk { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { func hasSpaceToMerge(_ other: some StringProtocol) -> Bool { utf8Count + other.utf8.count <= Self.maxUTF8Count } diff --git a/Sources/RopeModule/BigString/Conformances/BigString+BidirectionalCollection.swift b/Sources/RopeModule/BigString/Conformances/BigString+BidirectionalCollection.swift index 22acb9d4..af7d64a4 100644 --- a/Sources/RopeModule/BigString/Conformances/BigString+BidirectionalCollection.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+BidirectionalCollection.swift @@ -24,36 +24,36 @@ extension BigString: BidirectionalCollection { } public var endIndex: Index { - Index(_utf8Offset: utf8Count)._knownCharacterAligned() + Index(_utf8Offset: _utf8Count)._knownCharacterAligned() } - public var count: Int { characterCount } + public var count: Int { _characterCount } @inline(__always) public func index(after i: Index) -> Index { - characterIndex(after: i) + _characterIndex(after: i) } @inline(__always) public func index(before i: Index) -> Index { - characterIndex(before: i) + _characterIndex(before: i) } @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { - characterIndex(i, offsetBy: distance) + _characterIndex(i, offsetBy: distance) } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - characterIndex(i, offsetBy: distance, limitedBy: limit) + _characterIndex(i, offsetBy: distance, limitedBy: limit) } public func distance(from start: Index, to end: Index) -> Int { - characterDistance(from: start, to: end) + _characterDistance(from: start, to: end) } public subscript(position: Index) -> Character { - self[character: position] + self[_character: position] } public subscript(bounds: Range) -> BigSubstring { @@ -64,11 +64,11 @@ extension BigString: BidirectionalCollection { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public func index(roundingDown i: Index) -> Index { - characterIndex(roundingDown: i) + _characterIndex(roundingDown: i) } public func index(roundingUp i: Index) -> Index { - characterIndex(roundingUp: i) + _characterIndex(roundingUp: i) } } diff --git a/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift b/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift index 2d650646..87f8cc70 100644 --- a/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift @@ -27,7 +27,7 @@ extension BigString: Equatable { // norm(a + c) == norm(a) + norm(b) in this case. // To do this properly, we'll probably need to expose new stdlib entry points. :-/ if left.isIdentical(to: right) { return true } - guard left.characterCount == right.characterCount else { return false } + guard left._characterCount == right._characterCount else { return false } // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees. var it1 = left.makeIterator() var it2 = right.makeIterator() @@ -57,7 +57,7 @@ extension BigString { var it1 = left.utf8.makeIterator() var it2 = right.utf8.makeIterator() - var remaining = left.utf8Count + var remaining = left._utf8Count while remaining > 0 { let consumed = it1.next(maximumCount: remaining) { b1 in @@ -79,8 +79,8 @@ extension BigString { to right: Self, in rightRange: Range ) -> Bool { - let leftUTF8Count = left.utf8Distance(from: leftRange.lowerBound, to: leftRange.upperBound) - let rightUTF8Count = right.utf8Distance(from: rightRange.lowerBound, to: rightRange.upperBound) + let leftUTF8Count = left._utf8Distance(from: leftRange.lowerBound, to: leftRange.upperBound) + let rightUTF8Count = right._utf8Distance(from: rightRange.lowerBound, to: rightRange.upperBound) guard leftUTF8Count == rightUTF8Count else { return false } var remaining = leftUTF8Count diff --git a/Sources/RopeModule/BigString/Operations/BigString+Append.swift b/Sources/RopeModule/BigString/Operations/BigString+Append.swift index ec2d23ef..e9789692 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Append.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Append.swift @@ -19,7 +19,7 @@ extension BigString { self = Self(other) return } - var ingester = ingester(forInserting: other, at: endIndex, allowForwardPeek: true) + var ingester = _ingester(forInserting: other, at: endIndex, allowForwardPeek: true) let last = _rope.index(before: _rope.endIndex) if let final = _rope[last].append(from: &ingester) { @@ -109,14 +109,14 @@ extension BigString { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { var isUndersized: Bool { - utf8Count < Chunk.minUTF8Count + _utf8Count < _Chunk.minUTF8Count } } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { /// Note: This assumes `other` already has the correct break positions. - mutating func _append(_ other: __owned Chunk) { + mutating func _append(_ other: __owned _Chunk) { assert(!other.isEmpty) guard !self.isEmpty else { self._rope.append(other) @@ -135,7 +135,7 @@ extension BigString { } /// Note: This assumes `self` and `other` already have the correct break positions. - mutating func _prepend(_ other: __owned Chunk) { + mutating func _prepend(_ other: __owned _Chunk) { assert(!other.isEmpty) guard !self.isEmpty else { self._rope.prepend(other) diff --git a/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift index a04495dc..07a56b55 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift @@ -15,7 +15,7 @@ extension BigString { internal init(_from input: some StringProtocol) { var builder = _Storage.Builder() - var ingester = Ingester(input) + var ingester = _Ingester(input) while let chunk = ingester.nextWellSizedChunk() { builder.append(chunk) } @@ -27,7 +27,7 @@ extension BigString { var piece = "" for character in input { piece.append(character) - if piece.utf8.count >= Chunk.minUTF8Count { + if piece.utf8.count >= _Chunk.minUTF8Count { builder.append(piece) piece = "" } @@ -41,7 +41,7 @@ extension BigString { var piece = "" for scalar in input { piece.unicodeScalars.append(scalar) - if piece.utf8.count >= Chunk.minUTF8Count { + if piece.utf8.count >= _Chunk.minUTF8Count { builder.append(piece) piece = "" } @@ -65,7 +65,7 @@ extension BigString { self._rope = other._rope.extract( from: range.lowerBound.utf8Offset, to: range.upperBound.utf8Offset, - in: UTF8Metric()) + in: _UTF8Metric()) var old = other._breakState(upTo: range.lowerBound) var new = _CharacterRecognizer() _ = self._rope.resyncBreaks(old: &old, new: &new) @@ -79,7 +79,7 @@ extension BigString { self._rope = other._rope.extract( from: range.lowerBound.utf8Offset, to: range.upperBound.utf8Offset, - in: UTF8Metric()) + in: _UTF8Metric()) var old = other._breakState(upTo: range.lowerBound) var new = state self._rope.resyncBreaksToEnd(old: &old, new: &new) @@ -98,7 +98,7 @@ extension String { return } self.init() - self.reserveCapacity(big.utf8Count) + self.reserveCapacity(big._utf8Count) for chunk in big._rope { self.append(chunk.string) } @@ -107,10 +107,10 @@ extension String { internal init(_from big: BigString, in range: Range) { self.init() - var start = big.unicodeScalarIndex(roundingDown: range.lowerBound) + var start = big._unicodeScalarIndex(roundingDown: range.lowerBound) start = big.resolve(start, preferEnd: false) - var end = big.unicodeScalarIndex(roundingDown: range.upperBound) + var end = big._unicodeScalarIndex(roundingDown: range.upperBound) end = big.resolve(end, preferEnd: true) let utf8Capacity = end.utf8Offset - start.utf8Offset diff --git a/Sources/RopeModule/BigString/Operations/BigString+Insert.swift b/Sources/RopeModule/BigString/Operations/BigString+Insert.swift index 941cf3a8..92c383e2 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Insert.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Insert.swift @@ -28,7 +28,7 @@ extension BigString { // full grapheme breaking state of the ingester at the start of the insertion. // (We'll use it to resync grapheme breaks in the parts that follow the insertion.) let index = self.resolve(index, preferEnd: true) - var ingester = ingester(forInserting: other, at: index, allowForwardPeek: false) + var ingester = _ingester(forInserting: other, at: index, allowForwardPeek: false) var ri = index._rope! var ci = index._chunkIndex let r = _rope.update(at: &ri) { $0.insert(from: &ingester, at: ci) } diff --git a/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift b/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift index c662559b..bbd54e33 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift @@ -17,7 +17,7 @@ extension BigString { upTo index: Index, nextScalarHint: Unicode.Scalar? = nil ) -> _CharacterRecognizer { - assert(index == unicodeScalarIndex(roundingDown: index)) + assert(index == _unicodeScalarIndex(roundingDown: index)) guard index > startIndex else { return _CharacterRecognizer() } @@ -158,7 +158,7 @@ extension BigString._Storage { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Chunk { +extension BigString._Chunk { /// Resyncronize chunk metadata with the (possibly) reshuffled grapheme /// breaks after an insertion that ended at `index`. /// diff --git a/Sources/RopeModule/BigString/Operations/BigString+RemoveSubrange.swift b/Sources/RopeModule/BigString/Operations/BigString+RemoveSubrange.swift index 32d1ba68..0104f9e7 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+RemoveSubrange.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+RemoveSubrange.swift @@ -18,7 +18,7 @@ extension BigString { if bounds.isEmpty { return } let lower = bounds.lowerBound.utf8Offset let upper = bounds.upperBound.utf8Offset - _rope.removeSubrange(lower ..< upper, in: UTF8Metric()) + _rope.removeSubrange(lower ..< upper, in: _UTF8Metric()) } } @@ -33,7 +33,7 @@ extension BigString { mutating func removeUnicodeScalar(at i: Index) -> Unicode.Scalar { precondition(i < endIndex, "Index out of bounds") - let start = unicodeScalarIndex(roundingDown: i) + let start = _unicodeScalarIndex(roundingDown: i) let ropeIndex = start._rope! let chunkIndex = start._chunkIndex let chunk = _rope[ropeIndex] diff --git a/Sources/RopeModule/BigString/Operations/BigString+ReplaceSubrange.swift b/Sources/RopeModule/BigString/Operations/BigString+ReplaceSubrange.swift index 93d6f823..c48e814f 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+ReplaceSubrange.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+ReplaceSubrange.swift @@ -20,7 +20,7 @@ extension BigString { return } var builder = _split(removing: range) - var ingester = Ingester(Substring(newElements), startState: builder.prefixEndState) + var ingester = _Ingester(Substring(newElements), startState: builder.prefixEndState) builder.append(from: &ingester) self = builder.finalize() } @@ -74,7 +74,7 @@ extension BigString { let startState = _breakState(upTo: range.lowerBound) let endState = _breakState(upTo: range.upperBound) - let b = _rope.builder(removing: lower ..< upper, in: UTF8Metric()) + let b = _rope.builder(removing: lower ..< upper, in: _UTF8Metric()) return Builder(base: b, prefixEndState: startState, suffixStartState: endState) } } diff --git a/Sources/RopeModule/BigString/Operations/BigString+Split.swift b/Sources/RopeModule/BigString/Operations/BigString+Split.swift index e3ec13ae..968be01e 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Split.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Split.swift @@ -17,7 +17,7 @@ extension BigString { at index: Index ) -> Builder { let b = _ropeBuilder(at: index) - let state = b.breakState() + let state = b._breakState() let builder = Builder(base: b, prefixEndState: state, suffixStartState: state) return builder } @@ -35,7 +35,7 @@ extension BigString { if let ri = index._rope, _rope.isValid(ri) { return _rope.split(at: ri, index._chunkIndex) } - return _rope.builder(splittingAt: index.utf8Offset, in: UTF8Metric()) + return _rope.builder(splittingAt: index.utf8Offset, in: _UTF8Metric()) } } diff --git a/Sources/RopeModule/BigString/Views/BigString+UTF16View.swift b/Sources/RopeModule/BigString/Views/BigString+UTF16View.swift index e3c7e3d9..dab8a40f 100644 --- a/Sources/RopeModule/BigString/Views/BigString+UTF16View.swift +++ b/Sources/RopeModule/BigString/Views/BigString+UTF16View.swift @@ -60,7 +60,7 @@ extension BigString.UTF16View: Sequence { internal init(_base: BigString, from start: BigString.Index) { self._base = _base - self._index = _base.utf16Index(roundingDown: start) + self._index = _base._utf16Index(roundingDown: start) } } @@ -104,33 +104,33 @@ extension BigString.UTF16View: BidirectionalCollection { @inline(__always) public var endIndex: Index { _base.endIndex } - public var count: Int { _base.utf16Count } + public var count: Int { _base._utf16Count } @inline(__always) public func index(after i: Index) -> Index { - _base.utf16Index(after: i) + _base._utf16Index(after: i) } @inline(__always) public func index(before i: Index) -> Index { - _base.utf16Index(before: i) + _base._utf16Index(before: i) } @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { - _base.utf16Index(i, offsetBy: distance) + _base._utf16Index(i, offsetBy: distance) } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _base.utf16Index(i, offsetBy: distance, limitedBy: limit) + _base._utf16Index(i, offsetBy: distance, limitedBy: limit) } public func distance(from start: Index, to end: Index) -> Int { - _base.utf16Distance(from: start, to: end) + _base._utf16Distance(from: start, to: end) } public subscript(position: Index) -> UInt16 { - _base[utf16: position] + _base[_utf16: position] } public subscript(bounds: Range) -> BigSubstring.UTF16View { @@ -141,11 +141,11 @@ extension BigString.UTF16View: BidirectionalCollection { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF16View { public func index(roundingDown i: Index) -> Index { - _base.utf16Index(roundingDown: i) + _base._utf16Index(roundingDown: i) } public func index(roundingUp i: Index) -> Index { - _base.utf16Index(roundingUp: i) + _base._utf16Index(roundingUp: i) } } diff --git a/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift b/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift index 9428ae6c..f4c8b74e 100644 --- a/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift +++ b/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift @@ -60,7 +60,7 @@ extension BigString.UTF8View: Sequence { internal init(_base: BigString, from start: BigString.Index) { self._base = _base - self._index = _base.utf8Index(roundingDown: start) + self._index = _base._utf8Index(roundingDown: start) } } @@ -140,33 +140,33 @@ extension BigString.UTF8View: BidirectionalCollection { @inline(__always) public var endIndex: Index { _base.endIndex } - public var count: Int { _base.utf8Count } + public var count: Int { _base._utf8Count } @inline(__always) public func index(after i: Index) -> Index { - _base.utf8Index(after: i) + _base._utf8Index(after: i) } @inline(__always) public func index(before i: Index) -> Index { - _base.utf8Index(before: i) + _base._utf8Index(before: i) } @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { - _base.utf8Index(i, offsetBy: distance) + _base._utf8Index(i, offsetBy: distance) } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _base.utf8Index(i, offsetBy: distance, limitedBy: limit) + _base._utf8Index(i, offsetBy: distance, limitedBy: limit) } public func distance(from start: Index, to end: Index) -> Int { - _base.utf8Distance(from: start, to: end) + _base._utf8Distance(from: start, to: end) } public subscript(position: Index) -> UInt8 { - _base[utf8: position] + _base[_utf8: position] } public subscript(bounds: Range) -> BigSubstring.UTF8View { @@ -177,11 +177,11 @@ extension BigString.UTF8View: BidirectionalCollection { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UTF8View { public func index(roundingDown i: Index) -> Index { - _base.utf8Index(roundingDown: i) + _base._utf8Index(roundingDown: i) } public func index(roundingUp i: Index) -> Index { - _base.utf8Index(roundingUp: i) + _base._utf8Index(roundingUp: i) } } diff --git a/Sources/RopeModule/BigString/Views/BigString+UnicodeScalarView.swift b/Sources/RopeModule/BigString/Views/BigString+UnicodeScalarView.swift index 18aea1ac..1c62d0ad 100644 --- a/Sources/RopeModule/BigString/Views/BigString+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/Views/BigString+UnicodeScalarView.swift @@ -94,7 +94,7 @@ extension BigString.UnicodeScalarView: Sequence { internal init(_base: BigString, from start: BigString.Index) { self._base = _base - self._index = _base.unicodeScalarIndex(roundingDown: start) + self._index = _base._unicodeScalarIndex(roundingDown: start) } } @@ -138,33 +138,33 @@ extension BigString.UnicodeScalarView: BidirectionalCollection { @inline(__always) public var endIndex: Index { _base.endIndex } - public var count: Int { _base.unicodeScalarCount } + public var count: Int { _base._unicodeScalarCount } @inline(__always) public func index(after i: Index) -> Index { - _base.unicodeScalarIndex(after: i) + _base._unicodeScalarIndex(after: i) } @inline(__always) public func index(before i: Index) -> Index { - _base.unicodeScalarIndex(before: i) + _base._unicodeScalarIndex(before: i) } @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { - _base.unicodeScalarIndex(i, offsetBy: distance) + _base._unicodeScalarIndex(i, offsetBy: distance) } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - _base.unicodeScalarIndex(i, offsetBy: distance, limitedBy: limit) + _base._unicodeScalarIndex(i, offsetBy: distance, limitedBy: limit) } public func distance(from start: Index, to end: Index) -> Int { - _base.unicodeScalarDistance(from: start, to: end) + _base._unicodeScalarDistance(from: start, to: end) } public subscript(position: Index) -> UnicodeScalar { - _base[unicodeScalar: position] + _base[_unicodeScalar: position] } public subscript(bounds: Range) -> BigSubstring.UnicodeScalarView { @@ -175,11 +175,11 @@ extension BigString.UnicodeScalarView: BidirectionalCollection { @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString.UnicodeScalarView { public func index(roundingDown i: Index) -> Index { - _base.unicodeScalarIndex(roundingDown: i) + _base._unicodeScalarIndex(roundingDown: i) } public func index(roundingUp i: Index) -> Index { - _base.unicodeScalarIndex(roundingUp: i) + _base._unicodeScalarIndex(roundingUp: i) } } diff --git a/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift index 7e13196f..3ce2150f 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift @@ -24,8 +24,8 @@ extension BigSubstring { public init(_ base: BigString, in bounds: Range) { self._base = base - let lower = base.utf16Index(roundingDown: bounds.lowerBound) - let upper = base.utf16Index(roundingDown: bounds.upperBound) + let lower = base._utf16Index(roundingDown: bounds.lowerBound) + let upper = base._utf16Index(roundingDown: bounds.upperBound) self._bounds = Range(uncheckedBounds: (lower, upper)) } @@ -144,26 +144,26 @@ extension BigSubstring.UTF16View: BidirectionalCollection { @inline(__always) public func index(after i: Index) -> Index { precondition(i < endIndex, "Can't advance above end index") - return _base.utf16Index(after: i) + return _base._utf16Index(after: i) } @inline(__always) public func index(before i: Index) -> Index { precondition(i > startIndex, "Can't advance below start index") - return _base.utf16Index(before: i) + return _base._utf16Index(before: i) } @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - let j = _base.utf16Index(i, offsetBy: distance) + let j = _base._utf16Index(i, offsetBy: distance) precondition(j >= startIndex && j <= endIndex, "Index out of bounds") return j } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - guard let j = _base.utf16Index(i, offsetBy: distance, limitedBy: limit) else { return nil } + guard let j = _base._utf16Index(i, offsetBy: distance, limitedBy: limit) else { return nil } precondition(j >= startIndex && j <= endIndex, "Index out of bounds") return j } @@ -171,12 +171,12 @@ extension BigSubstring.UTF16View: BidirectionalCollection { public 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.utf16Distance(from: start, to: end) + return _base._utf16Distance(from: start, to: end) } public subscript(position: Index) -> UInt16 { precondition(position >= startIndex && position < endIndex, "Index out of bounds") - return _base[utf16: position] + return _base[_utf16: position] } public subscript(bounds: Range) -> Self { @@ -191,12 +191,12 @@ extension BigSubstring.UTF16View: BidirectionalCollection { extension BigSubstring.UTF16View { public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - return _base.utf16Index(roundingDown: i) + return _base._utf16Index(roundingDown: i) } public func index(roundingUp i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - return _base.utf16Index(roundingUp: i) + return _base._utf16Index(roundingUp: i) } } diff --git a/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift index b2ce342d..4d0c2a74 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift @@ -24,8 +24,8 @@ extension BigSubstring { public init(_ base: BigString, in bounds: Range) { self._base = base - let lower = base.utf8Index(roundingDown: bounds.lowerBound) - let upper = base.utf8Index(roundingDown: bounds.upperBound) + let lower = base._utf8Index(roundingDown: bounds.lowerBound) + let upper = base._utf8Index(roundingDown: bounds.upperBound) self._bounds = Range(uncheckedBounds: (lower, upper)) } @@ -118,26 +118,26 @@ extension BigSubstring.UTF8View: BidirectionalCollection { @inline(__always) public func index(after i: Index) -> Index { precondition(i < endIndex, "Can't advance above end index") - return _base.utf8Index(after: i) + return _base._utf8Index(after: i) } @inline(__always) public func index(before i: Index) -> Index { precondition(i > startIndex, "Can't advance below start index") - return _base.utf8Index(before: i) + return _base._utf8Index(before: i) } @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - let j = _base.utf8Index(i, offsetBy: distance) + let j = _base._utf8Index(i, offsetBy: distance) precondition(j >= startIndex && j <= endIndex, "Index out of bounds") return j } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - guard let j = _base.utf8Index(i, offsetBy: distance, limitedBy: limit) else { return nil } + guard let j = _base._utf8Index(i, offsetBy: distance, limitedBy: limit) else { return nil } precondition(j >= startIndex && j <= endIndex, "Index out of bounds") return j } @@ -145,12 +145,12 @@ extension BigSubstring.UTF8View: BidirectionalCollection { public 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.utf8Distance(from: start, to: end) + return _base._utf8Distance(from: start, to: end) } public subscript(position: Index) -> UInt8 { precondition(position >= startIndex && position < endIndex, "Index out of bounds") - return _base[utf8: position] + return _base[_utf8: position] } public subscript(bounds: Range) -> Self { @@ -165,12 +165,12 @@ extension BigSubstring.UTF8View: BidirectionalCollection { extension BigSubstring.UTF8View { public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - return _base.utf8Index(roundingDown: i) + return _base._utf8Index(roundingDown: i) } public func index(roundingUp i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - return _base.utf8Index(roundingUp: i) + return _base._utf8Index(roundingUp: i) } } diff --git a/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift index 3b4d8dc0..9891a192 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift @@ -18,16 +18,16 @@ extension BigSubstring { internal var _bounds: Range public init(_unchecked base: BigString, in bounds: Range) { - assert(bounds.lowerBound == base.unicodeScalarIndex(roundingDown: bounds.lowerBound)) - assert(bounds.upperBound == base.unicodeScalarIndex(roundingDown: bounds.upperBound)) + assert(bounds.lowerBound == base._unicodeScalarIndex(roundingDown: bounds.lowerBound)) + assert(bounds.upperBound == base._unicodeScalarIndex(roundingDown: bounds.upperBound)) self._base = base self._bounds = bounds } public init(_ base: BigString, in bounds: Range) { self._base = base - let lower = base.unicodeScalarIndex(roundingDown: bounds.lowerBound) - let upper = base.unicodeScalarIndex(roundingDown: bounds.upperBound) + let lower = base._unicodeScalarIndex(roundingDown: bounds.lowerBound) + let upper = base._unicodeScalarIndex(roundingDown: bounds.upperBound) self._bounds = Range(uncheckedBounds: (lower, upper)) } @@ -148,26 +148,28 @@ extension BigSubstring.UnicodeScalarView: BidirectionalCollection { @inline(__always) public func index(after i: Index) -> Index { precondition(i < endIndex, "Can't advance above end index") - return _base.unicodeScalarIndex(after: i) + return _base._unicodeScalarIndex(after: i) } @inline(__always) public func index(before i: Index) -> Index { precondition(i > startIndex, "Can't advance below start index") - return _base.unicodeScalarIndex(before: i) + return _base._unicodeScalarIndex(before: i) } @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - let j = _base.unicodeScalarIndex(i, offsetBy: distance) + let j = _base._unicodeScalarIndex(i, offsetBy: distance) precondition(j >= startIndex && j <= endIndex, "Index out of bounds") return j } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - guard let j = _base.unicodeScalarIndex(i, offsetBy: distance, limitedBy: limit) else { return nil } + guard let j = _base._unicodeScalarIndex(i, offsetBy: distance, limitedBy: limit) else { + return nil + } precondition(j >= startIndex && j <= endIndex, "Index out of bounds") return j } @@ -175,12 +177,12 @@ extension BigSubstring.UnicodeScalarView: BidirectionalCollection { public 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.unicodeScalarDistance(from: start, to: end) + return _base._unicodeScalarDistance(from: start, to: end) } public subscript(position: Index) -> UnicodeScalar { precondition(position >= startIndex && position < endIndex, "Index out of bounds") - return _base[unicodeScalar: position] + return _base[_unicodeScalar: position] } public subscript(bounds: Range) -> Self { @@ -195,12 +197,12 @@ extension BigSubstring.UnicodeScalarView: BidirectionalCollection { extension BigSubstring.UnicodeScalarView { public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - return _base.unicodeScalarIndex(roundingDown: i) + return _base._unicodeScalarIndex(roundingDown: i) } public func index(roundingUp i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - return _base.unicodeScalarIndex(roundingUp: i) + return _base._unicodeScalarIndex(roundingUp: i) } } @@ -219,7 +221,7 @@ extension BigSubstring.UnicodeScalarView { let startOffset = self.startIndex.utf8Offset let endOffset = self.endIndex.utf8Offset - let oldCount = self._base.utf8Count + let oldCount = self._base._utf8Count var view = BigString.UnicodeScalarView(_base: self._base) self._base = BigString() @@ -228,9 +230,9 @@ extension BigSubstring.UnicodeScalarView { // 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() + 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) diff --git a/Sources/RopeModule/BigString/Views/BigSubstring.swift b/Sources/RopeModule/BigString/Views/BigSubstring.swift index 1b067a78..38c0072b 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring.swift @@ -17,8 +17,8 @@ public struct BigSubstring: Sendable { var _bounds: Range public init(_unchecked base: BigString, in bounds: Range) { - assert(bounds.lowerBound == base.characterIndex(roundingDown: bounds.lowerBound)) - assert(bounds.upperBound == base.characterIndex(roundingDown: bounds.upperBound)) + assert(bounds.lowerBound == base.index(roundingDown: bounds.lowerBound)) + assert(bounds.upperBound == base.index(roundingDown: bounds.upperBound)) self._base = base self._bounds = bounds } @@ -28,8 +28,8 @@ public struct BigSubstring: Sendable { // Sub-character slicing could change character boundaries in the tree, requiring // resyncing metadata. This would not be acceptable to do during slicing, so let's // round substring bounds down to the nearest character. - let start = base.characterIndex(roundingDown: bounds.lowerBound) - let end = base.characterIndex(roundingDown: bounds.upperBound) + let start = base.index(roundingDown: bounds.lowerBound) + let end = base.index(roundingDown: bounds.upperBound) self._bounds = Range(uncheckedBounds: (start, end)) } } @@ -184,26 +184,26 @@ extension BigSubstring: BidirectionalCollection { @inline(__always) public func index(after i: Index) -> Index { precondition(i < endIndex, "Can't advance above end index") - return _base.characterIndex(after: i) + return _base.index(after: i) } @inline(__always) public func index(before i: Index) -> Index { precondition(i > startIndex, "Can't advance below start index") - return _base.characterIndex(before: i) + return _base.index(before: i) } @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - let j = _base.characterIndex(i, offsetBy: distance) + let j = _base.index(i, offsetBy: distance) precondition(j >= startIndex && j <= endIndex, "Index out of bounds") return j } public 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 } + guard let j = _base.index(i, offsetBy: distance, limitedBy: limit) else { return nil } precondition(j >= startIndex && j <= endIndex, "Index out of bounds") return j } @@ -211,12 +211,12 @@ extension BigSubstring: BidirectionalCollection { public 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) + return _base.distance(from: start, to: end) } public subscript(position: Index) -> Character { precondition(position >= startIndex && position < endIndex, "Index out of bounds") - return _base[character: position] + return _base[position] } public subscript(bounds: Range) -> Self { @@ -231,12 +231,12 @@ extension BigSubstring: BidirectionalCollection { extension BigSubstring { public func index(roundingDown i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - return _base.characterIndex(roundingDown: i) + return _base.index(roundingDown: i) } public func index(roundingUp i: Index) -> Index { precondition(i >= startIndex && i <= endIndex, "Index out of bounds") - return _base.characterIndex(roundingUp: i) + return _base.index(roundingUp: i) } } @@ -257,7 +257,7 @@ extension BigSubstring { let startOffset = self.startIndex.utf8Offset let endOffset = self.endIndex.utf8Offset - let oldCount = self._base.utf8Count + let oldCount = self._base._utf8Count defer { // Substring mutations may change grapheme boundaries across the bounds of the original @@ -266,9 +266,9 @@ extension BigSubstring { // 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)) + let delta = self._base._utf8Count - oldCount + let start = _base.index(roundingDown: Index(_utf8Offset: startOffset)) + let end = _base.index(roundingDown: Index(_utf8Offset: endOffset + delta)) self._bounds = start ..< end } return body(&self._base) diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift index 4423387c..6da6fead 100644 --- a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -146,7 +146,7 @@ extension _CharacterRecognizer { } mutating func consume( - _ chunk: BigString.Chunk, upTo index: String.Index + _ chunk: BigString._Chunk, upTo index: String.Index ) -> (firstBreak: String.Index, prevBreak: String.Index)? { let index = chunk.string.unicodeScalars._index(roundingDown: index) let first = chunk.firstBreak From 6f3f19d1c50cfa32970a3e5ec897ceb866564b32 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 20 Mar 2023 23:48:07 -0700 Subject: [PATCH 073/113] =?UTF-8?q?=5FRope=20=E2=86=92=20Rope?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BigString/Basics/BigString+Builder.swift | 26 +- .../BigString/Basics/BigString+Contents.swift | 4 +- .../Basics/BigString+Debugging.swift | 2 +- .../BigString/Basics/BigString+Index.swift | 10 +- .../Basics/BigString+Invariants.swift | 2 +- .../Basics/BigString+Iterators.swift | 4 +- .../BigString/Basics/BigString+Metrics.swift | 2 +- .../BigString/Basics/BigString+Summary.swift | 2 +- .../BigString/Basics/BigString.swift | 8 +- .../Chunk/BigString+Chunk+RopeElement.swift | 2 +- ...BigString+RangeReplaceableCollection.swift | 2 +- .../Conformances/BigString+Sequence.swift | 4 +- .../Operations/BigString+Append.swift | 12 +- .../Operations/BigString+Initializers.swift | 2 +- .../BigString+Managing Breaks.swift | 4 +- .../Operations/BigString+Split.swift | 2 +- .../RopeModule/Rope/Basics/Rope+Builder.swift | 443 ++++++++++++++++++ ...e+Debugging.swift => Rope+Debugging.swift} | 18 +- ...Invariants.swift => Rope+Invariants.swift} | 6 +- .../{_Rope+Node.swift => Rope+_Node.swift} | 142 +++--- ...Rope+Storage.swift => Rope+_Storage.swift} | 10 +- ...edLeaf.swift => Rope+_UnmanagedLeaf.swift} | 22 +- ...eHandle.swift => Rope+_UnsafeHandle.swift} | 20 +- .../Rope/Basics/{_Rope.swift => Rope.swift} | 24 +- .../{_RopeElement.swift => RopeElement.swift} | 6 +- .../{_RopeMetric.swift => RopeMetric.swift} | 6 +- .../{_RopeSummary.swift => RopeSummary.swift} | 6 +- .../Rope/Basics/_Rope+Builder.swift | 438 ----------------- .../RopeModule/Rope/Basics/_RopeItem.swift | 25 +- .../RopeModule/Rope/Basics/_RopePath.swift | 6 +- ...Collection.swift => Rope+Collection.swift} | 110 ++--- .../{_Rope+Index.swift => Rope+Index.swift} | 34 +- ...ope+Sequence.swift => Rope+Sequence.swift} | 8 +- .../{_Rope+Append.swift => Rope+Append.swift} | 12 +- ..._Rope+Extract.swift => Rope+Extract.swift} | 20 +- .../{_Rope+Find.swift => Rope+Find.swift} | 12 +- ...achWhile.swift => Rope+ForEachWhile.swift} | 8 +- .../{_Rope+Insert.swift => Rope+Insert.swift} | 40 +- .../{_Rope+Join.swift => Rope+Join.swift} | 16 +- ...rEach.swift => Rope+MutatingForEach.swift} | 6 +- .../{_Rope+Remove.swift => Rope+Remove.swift} | 24 +- ...brange.swift => Rope+RemoveSubrange.swift} | 78 +-- .../{_Rope+Split.swift => Rope+Split.swift} | 48 +- Tests/RopeModuleTests/TestRope.swift | 238 +++++----- 44 files changed, 963 insertions(+), 951 deletions(-) create mode 100644 Sources/RopeModule/Rope/Basics/Rope+Builder.swift rename Sources/RopeModule/Rope/Basics/{_Rope+Debugging.swift => Rope+Debugging.swift} (89%) rename Sources/RopeModule/Rope/Basics/{_Rope+Invariants.swift => Rope+Invariants.swift} (96%) rename Sources/RopeModule/Rope/Basics/{_Rope+Node.swift => Rope+_Node.swift} (79%) rename Sources/RopeModule/Rope/Basics/{_Rope+Storage.swift => Rope+_Storage.swift} (79%) rename Sources/RopeModule/Rope/Basics/{_Rope+UnmanagedLeaf.swift => Rope+_UnmanagedLeaf.swift} (64%) rename Sources/RopeModule/Rope/Basics/{_Rope+UnsafeHandle.swift => Rope+_UnsafeHandle.swift} (91%) rename Sources/RopeModule/Rope/Basics/{_Rope.swift => Rope.swift} (76%) rename Sources/RopeModule/Rope/Basics/{_RopeElement.swift => RopeElement.swift} (92%) rename Sources/RopeModule/Rope/Basics/{_RopeMetric.swift => RopeMetric.swift} (86%) rename Sources/RopeModule/Rope/Basics/{_RopeSummary.swift => RopeSummary.swift} (94%) delete mode 100644 Sources/RopeModule/Rope/Basics/_Rope+Builder.swift rename Sources/RopeModule/Rope/Conformances/{_Rope+Collection.swift => Rope+Collection.swift} (83%) rename Sources/RopeModule/Rope/Conformances/{_Rope+Index.swift => Rope+Index.swift} (69%) rename Sources/RopeModule/Rope/Conformances/{_Rope+Sequence.swift => Rope+Sequence.swift} (88%) rename Sources/RopeModule/Rope/Operations/{_Rope+Append.swift => Rope+Append.swift} (90%) rename Sources/RopeModule/Rope/Operations/{_Rope+Extract.swift => Rope+Extract.swift} (89%) rename Sources/RopeModule/Rope/Operations/{_Rope+Find.swift => Rope+Find.swift} (92%) rename Sources/RopeModule/Rope/Operations/{_Rope+ForEachWhile.swift => Rope+ForEachWhile.swift} (94%) rename Sources/RopeModule/Rope/Operations/{_Rope+Insert.swift => Rope+Insert.swift} (87%) rename Sources/RopeModule/Rope/Operations/{_Rope+Join.swift => Rope+Join.swift} (91%) rename Sources/RopeModule/Rope/Operations/{_Rope+MutatingForEach.swift => Rope+MutatingForEach.swift} (97%) rename Sources/RopeModule/Rope/Operations/{_Rope+Remove.swift => Rope+Remove.swift} (90%) rename Sources/RopeModule/Rope/Operations/{_Rope+RemoveSubrange.swift => Rope+RemoveSubrange.swift} (85%) rename Sources/RopeModule/Rope/Operations/{_Rope+Split.swift => Rope+Split.swift} (76%) diff --git a/Sources/RopeModule/BigString/Basics/BigString+Builder.swift b/Sources/RopeModule/BigString/Basics/BigString+Builder.swift index a68bafb9..25c04360 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Builder.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Builder.swift @@ -16,14 +16,14 @@ extension BigString { struct Builder { typealias _Chunk = BigString._Chunk typealias _Ingester = BigString._Ingester - typealias _Storage = BigString._Storage + typealias _Rope = BigString._Rope - var base: _Storage.Builder + var base: _Rope.Builder var suffixStartState: _CharacterRecognizer var prefixEndState: _CharacterRecognizer init( - base: _Storage.Builder, + base: _Rope.Builder, prefixEndState: _CharacterRecognizer, suffixStartState: _CharacterRecognizer ) { @@ -33,7 +33,7 @@ extension BigString { } init() { - self.base = _Storage.Builder() + self.base = _Rope.Builder() self.suffixStartState = _CharacterRecognizer() self.prefixEndState = _CharacterRecognizer() } @@ -41,7 +41,7 @@ extension BigString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension _Rope.Builder { +extension Rope.Builder { internal func _breakState() -> _CharacterRecognizer { let chars = self.prefixSummary.characters assert(self.isPrefixEmpty || chars > 0) @@ -72,11 +72,11 @@ extension BigString.Builder { mutating func append(_ str: __owned Substring) { guard !str.isEmpty else { return } var ingester = _Ingester(str, startState: self.prefixEndState) - if var prefix = base.prefix._take() { + if var prefix = base._prefix._take() { if let slice = ingester.nextSlice(maxUTF8Count: prefix.value.availableSpace) { prefix.value._append(slice) } - self.base.prefix = prefix + self.base._prefix = prefix } while let next = ingester.nextChunk() { base.append(next) @@ -105,7 +105,7 @@ extension BigString.Builder { self.base.append(extract._rope) } - mutating func append(_ other: __owned _Storage, state: inout _CharacterRecognizer) { + mutating func append(_ other: __owned _Rope, state: inout _CharacterRecognizer) { guard !other.isEmpty else { return } var other = BigString(_rope: other) other._rope.resyncBreaksToEnd(old: &state, new: &self.prefixEndState) @@ -114,14 +114,14 @@ extension BigString.Builder { mutating func append(from ingester: inout _Ingester) { //assert(ingester.state._isKnownEqual(to: self.prefixEndState)) - if var prefix = base.prefix._take() { + if var prefix = base._prefix._take() { if let first = ingester.nextSlice(maxUTF8Count: prefix.value.availableSpace) { prefix.value._append(first) } - base.prefix = prefix + base._prefix = prefix } - let suffixCount = base.suffix?.value.utf8Count ?? 0 + let suffixCount = base._suffix?.value.utf8Count ?? 0 while let chunk = ingester.nextWellSizedChunk(suffix: suffixCount) { base.append(chunk) @@ -139,8 +139,8 @@ extension BigString.Builder { chunk.resyncBreaksFromStart(old: &suffixStartState, new: &prefixEndState) } // Roll it all up. - let _rope = self.base.finalize() - let string = BigString(_rope: _rope) + let rope = self.base.finalize() + let string = BigString(_rope: rope) string._invariantCheck() return string } diff --git a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift index 068186b8..8a82ba92 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift @@ -17,7 +17,7 @@ extension BigString { /// to hold without encountering an overflow in its operations. This corresponds to the capacity /// of the deepest tree where every node is the minimum possible size. public static var _minimumCapacity: Int { - let c = _Storage.minimumCapacity + let c = _Rope._minimumCapacity let (r, overflow) = _Chunk.minUTF8Count.multipliedReportingOverflow(by: c) guard !overflow else { return Int.max } return r @@ -26,7 +26,7 @@ extension BigString { /// The maximum number of UTF-8 code units that `BigString` may be able to store in the best /// possible case, when every node in the underlying tree is fully filled with data. public static var _maximumCapacity: Int { - let c = _Storage.maximumCapacity + let c = _Rope._maximumCapacity let (r, overflow) = _Chunk.maxUTF8Count.multipliedReportingOverflow(by: c) guard !overflow else { return Int.max } return r diff --git a/Sources/RopeModule/BigString/Basics/BigString+Debugging.swift b/Sources/RopeModule/BigString/Basics/BigString+Debugging.swift index 4db842d7..b92126ff 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Debugging.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Debugging.swift @@ -14,7 +14,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public func dump(heightLimit: Int = .max) { - _rope.dump(heightLimit: heightLimit) + _rope._dump(heightLimit: heightLimit) } } diff --git a/Sources/RopeModule/BigString/Basics/BigString+Index.swift b/Sources/RopeModule/BigString/Basics/BigString+Index.swift index 302f2236..fd169a41 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Index.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Index.swift @@ -14,7 +14,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public struct Index: Sendable { - typealias _Storage = BigString._Storage + typealias _Rope = BigString._Rope // ┌───────────────────────────────┬───┬───────────┬────────────────────┐ // │ b63:b11 │b10│ b9:b8 │ b7:b0 │ @@ -31,9 +31,9 @@ extension BigString { var _rawBits: UInt64 /// A (possibly invalid) rope index. - var _rope: _Storage.Index? + var _rope: _Rope.Index? - internal init(_raw: UInt64, _rope: _Storage.Index?) { + internal init(_raw: UInt64, _rope: _Rope.Index?) { self._rawBits = _raw self._rope = _rope } @@ -157,7 +157,7 @@ extension BigString.Index { } internal init( - _utf8Offset: Int, utf16TrailingSurrogate: Bool = false, _rope: _Storage.Index, chunkOffset: Int + _utf8Offset: Int, utf16TrailingSurrogate: Bool = false, _rope: _Rope.Index, chunkOffset: Int ) { _rawBits = Self._bitsForUTF8Offset(_utf8Offset) if utf16TrailingSurrogate { @@ -168,7 +168,7 @@ extension BigString.Index { self._rope = _rope } - internal init(baseUTF8Offset: Int, _rope: _Storage.Index, chunk: String.Index) { + internal init(baseUTF8Offset: Int, _rope: _Rope.Index, chunk: String.Index) { let chunkUTF8Offset = chunk._utf8Offset self.init( _utf8Offset: baseUTF8Offset + chunkUTF8Offset, diff --git a/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift b/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift index a4538f52..864e5d34 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift @@ -15,7 +15,7 @@ extension BigString { public func _invariantCheck() { #if DEBUG - _rope.invariantCheck() + _rope._invariantCheck() let allowUndersize = _rope.isSingleton var state = _CharacterRecognizer() diff --git a/Sources/RopeModule/BigString/Basics/BigString+Iterators.swift b/Sources/RopeModule/BigString/Basics/BigString+Iterators.swift index 96709598..bfe8ddb9 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Iterators.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Iterators.swift @@ -14,9 +14,9 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { struct ChunkIterator { - var base: _Storage.Iterator + var base: _Rope.Iterator - init(base: _Storage.Iterator) { + init(base: _Rope.Iterator) { self.base = base } } diff --git a/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift index 0d680120..3b2c7f2c 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Metrics.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -internal protocol _StringMetric: _RopeMetric where Element == BigString._Chunk { +internal protocol _StringMetric: RopeMetric where Element == BigString._Chunk { func distance( from start: String.Index, to end: String.Index, diff --git a/Sources/RopeModule/BigString/Basics/BigString+Summary.swift b/Sources/RopeModule/BigString/Basics/BigString+Summary.swift index 64f87dc9..eed08698 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Summary.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Summary.swift @@ -45,7 +45,7 @@ extension BigString.Summary: CustomStringConvertible { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString.Summary: _RopeSummary { +extension BigString.Summary: RopeSummary { @inline(__always) static var maxNodeSize: Int { #if DEBUG diff --git a/Sources/RopeModule/BigString/Basics/BigString.swift b/Sources/RopeModule/BigString/Basics/BigString.swift index 9a38da44..c98f1b8c 100644 --- a/Sources/RopeModule/BigString/Basics/BigString.swift +++ b/Sources/RopeModule/BigString/Basics/BigString.swift @@ -14,11 +14,11 @@ /// The core of a B-tree based String implementation. @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) public struct BigString: Sendable { - typealias _Storage = _Rope<_Chunk> + typealias _Rope = Rope<_Chunk> + + var _rope: _Rope - var _rope: _Storage - - internal init(_rope: _Storage) { + internal init(_rope: _Rope) { self._rope = _rope } } diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift index ea62fb5c..9f17f8e3 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift @@ -12,7 +12,7 @@ #if swift(>=5.8) @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString._Chunk: _RopeElement { +extension BigString._Chunk: RopeElement { typealias Summary = BigString.Summary typealias Index = String.Index diff --git a/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift b/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift index 53b14d37..8a63558f 100644 --- a/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+RangeReplaceableCollection.swift @@ -14,7 +14,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString: RangeReplaceableCollection { public init() { - self.init(_rope: _Storage()) + self.init(_rope: _Rope()) } public mutating func reserveCapacity(_ n: Int) { diff --git a/Sources/RopeModule/BigString/Conformances/BigString+Sequence.swift b/Sources/RopeModule/BigString/Conformances/BigString+Sequence.swift index ff2afcfb..4987e502 100644 --- a/Sources/RopeModule/BigString/Conformances/BigString+Sequence.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+Sequence.swift @@ -25,14 +25,14 @@ extension BigString { public struct Iterator { internal let _base: BigString internal var _utf8BaseOffset: Int - internal var _ropeIndex: _Storage.Index + internal var _ropeIndex: _Rope.Index internal var _chunkIndex: String.Index internal var _next: String.Index internal init(_ string: BigString) { self._base = string self._ropeIndex = string._rope.startIndex - string._rope.ensureLeaf(in: &_ropeIndex) + string._rope.grease(&_ropeIndex) self._utf8BaseOffset = 0 guard _ropeIndex < string._rope.endIndex else { diff --git a/Sources/RopeModule/BigString/Operations/BigString+Append.swift b/Sources/RopeModule/BigString/Operations/BigString+Append.swift index e9789692..e82390a9 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Append.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Append.swift @@ -30,13 +30,13 @@ extension BigString { // Make a temp rope out of the rest of the chunks and then join the two trees together. if !ingester.isAtEnd { - var builder = _Storage.Builder() + var builder = _Rope.Builder() while let chunk = ingester.nextWellSizedChunk() { precondition(!chunk.isUndersized) builder.append(chunk) } precondition(ingester.isAtEnd) - _rope = _Storage.join(_rope, builder.finalize()) + _rope = _Rope.join(_rope, builder.finalize()) } } } @@ -153,7 +153,7 @@ extension BigString { } /// Note: This assumes `other` already has the correct break positions. - mutating func _append(_ other: __owned _Storage) { + mutating func _append(_ other: __owned _Rope) { guard !other.isEmpty else { return } guard !self._rope.isEmpty else { self._rope = other @@ -170,11 +170,11 @@ extension BigString { self._prepend(chunk) return } - self._rope = _Storage.join(self._rope, other) + self._rope = _Rope.join(self._rope, other) } /// Note: This assumes `self` and `other` already have the correct break positions. - mutating func _prepend(_ other: __owned _Storage) { + mutating func _prepend(_ other: __owned _Rope) { guard !other.isEmpty else { return } guard !self.isEmpty else { self._rope = other @@ -191,7 +191,7 @@ extension BigString { self._append(chunk) return } - self._rope = _Storage.join(other, self._rope) + self._rope = _Rope.join(other, self._rope) } } diff --git a/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift index 07a56b55..74b40529 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift @@ -14,7 +14,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { internal init(_from input: some StringProtocol) { - var builder = _Storage.Builder() + var builder = _Rope.Builder() var ingester = _Ingester(input) while let chunk = ingester.nextWellSizedChunk() { builder.append(chunk) diff --git a/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift b/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift index bbd54e33..44d70a10 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Managing Breaks.swift @@ -70,7 +70,7 @@ extension BigString { startingAt index: Index, old: inout _CharacterRecognizer, new: inout _CharacterRecognizer - ) -> (ropeIndex: _Storage.Index, chunkIndex: String.Index)? { + ) -> (ropeIndex: _Rope.Index, chunkIndex: String.Index)? { guard index < endIndex else { return nil } let i = resolve(index, preferEnd: false) var ropeIndex = i._rope! @@ -100,7 +100,7 @@ extension BigString { } @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -extension BigString._Storage { +extension BigString._Rope { mutating func resyncBreaks( old: inout _CharacterRecognizer, new: inout _CharacterRecognizer diff --git a/Sources/RopeModule/BigString/Operations/BigString+Split.swift b/Sources/RopeModule/BigString/Operations/BigString+Split.swift index 968be01e..13ddab00 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Split.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Split.swift @@ -31,7 +31,7 @@ extension BigString { return builder } - mutating func _ropeBuilder(at index: Index) -> _Storage.Builder { + mutating func _ropeBuilder(at index: Index) -> _Rope.Builder { if let ri = index._rope, _rope.isValid(ri) { return _rope.split(at: ri, index._chunkIndex) } diff --git a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift new file mode 100644 index 00000000..414adba8 --- /dev/null +++ b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift @@ -0,0 +1,443 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension Rope { + @inlinable + public init(_ items: some Sequence) { + if let items = items as? Self { + self = items + return + } + var builder = Builder() + for item in items { + builder.append(item) + } + self = builder.finalize() + } +} + +extension Rope { + public struct Builder { + // ║ ║ + // ║ ║ ║ ║ + // ║ ║ ║ ║ ║ ║ + // ║ ║ ║ ║ ║ ║ ║ ║ + // ──╨─╨─╨─╨──╨──╨──╨─╨─╨─╨── + // →prefixTrees→ ↑ ↑ ←suffixTrees← + // prefix suffix + + private var _prefixTrees: [Rope] = [] + private var _prefixLeaf: Rope._Node? + var _prefix: Rope._Item? + + var _suffix: Rope._Item? + var _suffixTrees: [Rope] = [] + + public init() {} + + public var isPrefixEmpty: Bool { + if _prefix != nil { return false } + if let leaf = self._prefixLeaf, !leaf.isEmpty { return false } + return _prefixTrees.isEmpty + } + + public var isSuffixEmpty: Bool { + if _suffix != nil { return false } + return _suffixTrees.isEmpty + } + + public var prefixSummary: Summary { + var sum = Summary.zero + for sapling in _prefixTrees { + sum.add(sapling.summary) + } + if let leaf = _prefixLeaf { sum.add(leaf.summary) } + if let item = _prefix { sum.add(item.summary) } + return sum + } + + public var suffixSummary: Summary { + var sum = Summary.zero + if let item = _suffix { sum.add(item.summary) } + for rope in _suffixTrees { + sum.add(rope.summary) + } + return sum + } + + var _lastPrefixItem: Rope._Item { + get { + assert(!isPrefixEmpty) + if let item = self._prefix { return item } + if let leaf = self._prefixLeaf { return leaf.lastItem } + return _prefixTrees.last!.root.lastItem + } + _modify { + assert(!isPrefixEmpty) + if _prefix != nil { + yield &_prefix! + } else if _prefixLeaf?.isEmpty == false { + yield &_prefixLeaf!.lastItem + } else { + yield &_prefixTrees[_prefixTrees.count - 1].root.lastItem + } + } + } + + var _firstSuffixItem: Rope._Item { + get { + assert(!isSuffixEmpty) + if let _suffix { return _suffix } + return _suffixTrees[_suffixTrees.count - 1].root.firstItem + } + _modify { + assert(!isSuffixEmpty) + if _suffix != nil { + yield &_suffix! + } else { + yield &_suffixTrees[_suffixTrees.count - 1].root.firstItem + } + } + } + + public func forEachElementInPrefix( + from position: Int, + in metric: some RopeMetric, + _ body: (Element, Element.Index?) -> Bool + ) -> Bool { + var position = position + var i = 0 + while i < _prefixTrees.count { + let size = metric.size(of: _prefixTrees[i].summary) + if position < size { break } + position -= size + i += 1 + } + if i < _prefixTrees.count { + guard _prefixTrees[i].forEachWhile(from: position, in: metric, body) else { return false } + i += 1 + while i < _prefixTrees.count { + guard _prefixTrees[i].forEachWhile({ body($0, nil) }) else { return false } + i += 1 + } + if let leaf = self._prefixLeaf { + guard leaf.forEachWhile({ body($0, nil) }) else { return false } + } + if let item = self._prefix { + guard body(item.value, nil) else { return false } + } + return true + } + + if let leaf = self._prefixLeaf { + let size = metric.size(of: leaf.summary) + if position < size { + guard leaf.forEachWhile(from: position, in: metric, body) else { return false } + if let item = self._prefix { + guard body(item.value, nil) else { return false } + } + return true + } + position -= size + } + if let item = self._prefix { + let i = metric.index(at: position, in: item.value) + guard body(item.value, i) else { return false} + } + return true + } + + public mutating func mutatingForEachSuffix( + _ body: (inout Element) -> R? + ) -> R? { + if self._suffix != nil, + let r = body(&self._suffix!.value) { + return r + } + for i in stride(from: _suffixTrees.count - 1, through: 0, by: -1) { + if let r = self._suffixTrees[i].mutatingForEach(body) { + return r + } + } + return nil + } + + public mutating func append(_ item: __owned Element) { + _append(Rope._Item(item)) + } + + mutating func _append(_ item: __owned Rope._Item) { + guard !item.isEmpty else { return } + guard var prefix = self._prefix._take() else { + self._prefix = item + return + } + var item = item + if prefix.rebalance(nextNeighbor: &item) { + self._prefix = prefix + return + } + _appendNow(prefix) + self._prefix = item + } + + mutating func _appendNow(_ item: __owned Rope._Item) { + assert(self._prefix == nil) + assert(!item.isUndersized) + var leaf = self._prefixLeaf._take() ?? .createLeaf() + leaf._appendItem(item) + if leaf.isFull { + self._appendNow(leaf) + } else { + self._prefixLeaf = leaf + } + _invariantCheck() + } + + public mutating func append(_ rope: __owned Rope) { + guard rope._root != nil else { return } + _append(rope.root) + } + + mutating func _append(_ node: __owned Rope._Node) { + defer { _invariantCheck() } + var node = node + if node.height == 0 { + if node.childCount == 1 { + _append(node.firstItem) + return + } + if let item = self._prefix._take() { + if let spawn = node.prepend(item) { + _append(node) + _append(spawn) + return + } + } + if var leaf = self._prefixLeaf._take() { + if leaf.rebalance(nextNeighbor: &node), !leaf.isFull { + self._prefixLeaf = leaf + return + } + self._appendNow(leaf) + } + + if node.isFull { + self._appendNow(node) + } else { + self._prefixLeaf = node + } + return + } + + if var prefix = self._prefix._take() { + if !prefix.isUndersized || !node.firstItem.rebalance(prevNeighbor: &prefix) { + self._appendNow(prefix) + } + } + if let leaf = self._prefixLeaf._take() { + _appendNow(leaf) + } + _appendNow(node) + } + + mutating func _appendNow(_ rope: __owned Rope._Node) { + assert(self._prefix == nil && self._prefixLeaf == nil) + var new = rope + while !_prefixTrees.isEmpty { + // Join previous saplings together until they grow at least as deep as the new one. + var previous = _prefixTrees.removeLast() + while previous._height < new.height { + if _prefixTrees.isEmpty { + previous._append(new) + _prefixTrees.append(previous) + return + } + previous.prepend(_prefixTrees.removeLast()) + } + + if previous._height == new.height { + if previous.root.rebalance(nextNeighbor: &new) { + new = previous.root + } else { + new = .createInner(children: previous.root, new) + } + continue + } + + if new.isFull, !previous.root.isFull, previous._height == new.height + 1 { + // Graft node under the last sapling, as a new child branch. + previous.root._appendNode(new) + new = previous.root + continue + } + + // The new seedling can be appended to the line and we're done. + _prefixTrees.append(previous) + break + } + _prefixTrees.append(Rope(root: new)) + } + + public mutating func prependSuffix(_ item: __owned Element) { + _prependSuffix(_Item(item)) + } + + mutating func _prependSuffix(_ item: __owned _Item) { + guard !item.isEmpty else { return } + if var suffixItem = self._suffix._take() { + var item = item + if !(suffixItem.isUndersized && item.rebalance(nextNeighbor: &suffixItem)) { + if _suffixTrees.isEmpty { + _suffixTrees.append(Rope(root: .createLeaf(suffixItem))) + } else { + _suffixTrees[_suffixTrees.count - 1].prepend(suffixItem.value) + } + } + } + self._suffix = item + } + + public mutating func prependSuffix(_ rope: __owned Rope) { + assert(_suffix == nil) + assert(_suffixTrees.isEmpty || rope._height <= _suffixTrees.last!._height) + _suffixTrees.append(rope) + } + + mutating func _prependSuffix(_ rope: __owned Rope._Node) { + prependSuffix(Rope(root: rope)) + } + + mutating func _append(slots: Range, in node: __owned Rope._Node) { + assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) + let c = slots.count + guard c > 0 else { return } + if c == 1 { + if node.isLeaf { + let item = node.readLeaf { $0.children[slots.lowerBound] } + _append(item) + } else { + let child = node.readInner { $0.children[slots.lowerBound] } + _append(child) + } + return + } + let copy = node.copy(slots: slots) + _append(copy) + } + + mutating func _prependSuffix(slots: Range, in node: __owned Rope._Node) { + assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) + let c = slots.count + guard c > 0 else { return } + if c == 1 { + if node.isLeaf { + let item = node.readLeaf { $0.children[slots.lowerBound] } + _prependSuffix(item) + } else { + let child = node.readInner { $0.children[slots.lowerBound] } + _prependSuffix(child) + } + return + } + let copy = node.copy(slots: slots) + _prependSuffix(copy) + } + + public mutating func finalize() -> Rope { + // Integrate prefix & suffix chunks. + if let suffixItem = self._suffix._take() { + _append(suffixItem) + } + if var prefix = self._prefix._take() { + if !prefix.isUndersized { + _appendNow(prefix) + } else if !self.isPrefixEmpty { + if !self._lastPrefixItem.rebalance(nextNeighbor: &prefix) { + _appendNow(prefix) + } + } else if !self.isSuffixEmpty { + if !self._firstSuffixItem.rebalance(prevNeighbor: &prefix) { + _appendNow(prefix) + } + } else { + // We only have the seed; allow undersized chunk + return Rope(root: .createLeaf(prefix)) + } + } + assert(self._prefix == nil && self._suffix == nil) + while let tree = _suffixTrees.popLast() { + append(tree) + } + // Merge all saplings, the seedling and the seed into a single rope. + if let item = self._prefix._take() { + _appendNow(item) + } + var rope = Rope(root: _prefixLeaf._take()) + while let tree = _prefixTrees.popLast() { + rope.prepend(tree) + } + assert(_prefixLeaf == nil && _prefixTrees.isEmpty && _suffixTrees.isEmpty) + rope._invariantCheck() + return rope + } + + public func _invariantCheck() { +#if DEBUG + var h = UInt8.max + for sapling in _prefixTrees { + precondition(sapling._height <= h) + sapling._invariantCheck() + h = sapling._height + } + if let leaf = self._prefixLeaf { + precondition(leaf.height == 0) + precondition(!leaf.isFull) + leaf.invariantCheck(depth: 0, height: 0) + } + h = 0 + for tree in _suffixTrees.reversed() { + precondition(tree._height >= h) + tree._invariantCheck() + h = tree._height + } +#endif + + } + + public func _dump(heightLimit: Int = Int.max) { + for i in self._prefixTrees.indices { + print("Sapling \(i):") + self._prefixTrees[i]._dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") + } + if let leaf = self._prefixLeaf { + print("Seedling:") + leaf.dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") + } + if let item = self._prefix { + print("Seed:") + print(" \(item)") + } + print("---") + var i = 0 + if let item = self._suffix { + print("Suffix \(i):") + i += 1 + print(" \(item)") + } + for tree in self._suffixTrees.reversed() { + print("Suffix \(i)") + i += 1 + tree._dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") + } + } + } +} diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift b/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift similarity index 89% rename from Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift rename to Sources/RopeModule/Rope/Basics/Rope+Debugging.swift index d2350fde..2e69c780 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Debugging.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift @@ -22,25 +22,27 @@ private func _addressString(for object: Unmanaged) -> String { _addressString(for: object.toOpaque()) } -extension _Rope.UnmanagedLeaf: CustomStringConvertible { +extension Rope._UnmanagedLeaf: CustomStringConvertible { var description: String { _addressString(for: _ref.toOpaque()) } } -extension _Rope { - var nodeCount: Int { _root?.nodeCount ?? 0 } +extension Rope { + public var _nodeCount: Int { + _root?.nodeCount ?? 0 + } } -extension _Rope.Node { +extension Rope._Node { var nodeCount: Int { guard !isLeaf else { return 1 } return readInner { $0.children.reduce(into: 1) { $0 += $1.nodeCount } } } } -extension _Rope { - public func dump( +extension Rope { + public func _dump( heightLimit: Int = .max, firstPrefix: String = "", restPrefix: String = "" @@ -53,7 +55,7 @@ extension _Rope { } } -extension _Rope.Node: CustomStringConvertible { +extension Rope._Node: CustomStringConvertible { var description: String { """ \(height > 0 ? "Inner@\(height)" : "Leaf")(\ @@ -64,7 +66,7 @@ extension _Rope.Node: CustomStringConvertible { } } -extension _Rope.Node { +extension Rope._Node { internal func dump( heightLimit: Int = .max, firstPrefix: String = "", diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift b/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift similarity index 96% rename from Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift rename to Sources/RopeModule/Rope/Basics/Rope+Invariants.swift index 0c2cf328..b26942c0 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Invariants.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift @@ -9,15 +9,15 @@ // //===----------------------------------------------------------------------===// -extension _Rope { - public func invariantCheck() { +extension Rope { + public func _invariantCheck() { #if DEBUG _root?.invariantCheck(depth: 0, height: root.height, recursive: true) #endif } } -extension _Rope.Node { +extension Rope._Node { func invariantCheck(depth: UInt8, height: UInt8, recursive: Bool = true) { #if DEBUG precondition(height == self.height, "Mismatching rope height") diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Node.swift b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift similarity index 79% rename from Sources/RopeModule/Rope/Basics/_Rope+Node.swift rename to Sources/RopeModule/Rope/Basics/Rope+_Node.swift index f55f3480..3da01fab 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Node.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift @@ -13,21 +13,21 @@ import _CollectionsUtilities // for 5.8 polyfills #endif -extension _Rope { - struct Node: _RopeItem { - typealias Element = _Rope.Element - typealias Summary = _Rope.Summary - typealias Index = _Rope.Index - typealias Item = _Rope.Item - typealias Storage = _Rope.Storage - typealias UnsafeHandle = _Rope.UnsafeHandle - typealias Path = _Rope.Path - typealias UnmanagedLeaf = _Rope.UnmanagedLeaf +extension Rope { + struct _Node: _RopeItem { + typealias Element = Rope.Element + typealias Summary = Rope.Summary + typealias Index = Rope.Index + typealias _Item = Rope._Item + typealias _Storage = Rope._Storage + typealias _UnsafeHandle = Rope._UnsafeHandle + typealias _Path = Rope._Path + typealias _UnmanagedLeaf = Rope._UnmanagedLeaf var object: AnyObject var summary: Summary - init(leaf: Storage, summary: Summary? = nil) { + init(leaf: _Storage<_Item>, summary: Summary? = nil) { self.object = leaf self.summary = .zero self.summary = readLeaf { handle in @@ -35,7 +35,7 @@ extension _Rope { } } - init(inner: Storage, summary: Summary? = nil) { + init(inner: _Storage<_Node>, summary: Summary? = nil) { assert(inner.header.height > 0) self.object = inner self.summary = .zero @@ -46,7 +46,7 @@ extension _Rope { } } -extension _Rope.Node { +extension Rope._Node { var _headerPtr: UnsafePointer<_RopeStorageHeader> { let p = _getUnsafePointerToStoredProperties(object) .assumingMemoryBound(to: _RopeStorageHeader.self) @@ -64,15 +64,15 @@ extension _Rope.Node { var isLeaf: Bool { height == 0 } @inline(__always) - var asLeaf: Storage { + var asLeaf: _Storage<_Item> { assert(height == 0) - return unsafeDowncast(object, to: Storage.self) + return unsafeDowncast(object, to: _Storage<_Item>.self) } @inline(__always) - var asInner: Storage { + var asInner: _Storage { assert(height > 0) - return unsafeDowncast(object, to: Storage.self) + return unsafeDowncast(object, to: _Storage.self) } @inline(__always) @@ -84,12 +84,12 @@ extension _Rope.Node { var isFull: Bool { childCount == Summary.maxNodeSize } } -extension _Rope.Node { +extension Rope._Node { static func createLeaf() -> Self { Self(leaf: .create(height: 0), summary: Summary.zero) } - static func createLeaf(_ item: __owned Item) -> Self { + static func createLeaf(_ item: __owned _Item) -> Self { var leaf = createLeaf() leaf._appendItem(item) return leaf @@ -112,7 +112,7 @@ extension _Rope.Node { } } -extension _Rope.Node { +extension Rope._Node { @inline(__always) mutating func isUnique() -> Bool { isKnownUniquelyReferenced(&object) @@ -143,47 +143,47 @@ extension _Rope.Node { @inline(__always) func readLeaf( - _ body: (UnsafeHandle) -> R + _ body: (_UnsafeHandle<_Item>) -> R ) -> R { asLeaf.withUnsafeMutablePointers { h, p in - let handle = UnsafeHandle(isMutable: false, header: h, start: p) + let handle = _UnsafeHandle(isMutable: false, header: h, start: p) return body(handle) } } @inline(__always) mutating func updateLeaf( - _ body: (UnsafeHandle) -> R + _ body: (_UnsafeHandle<_Item>) -> R ) -> R { asLeaf.withUnsafeMutablePointers { h, p in - let handle = UnsafeHandle(isMutable: true, header: h, start: p) + let handle = _UnsafeHandle(isMutable: true, header: h, start: p) return body(handle) } } @inline(__always) func readInner( - _ body: (UnsafeHandle) -> R + _ body: (_UnsafeHandle) -> R ) -> R { asInner.withUnsafeMutablePointers { h, p in - let handle = UnsafeHandle(isMutable: false, header: h, start: p) + let handle = _UnsafeHandle(isMutable: false, header: h, start: p) return body(handle) } } @inline(__always) mutating func updateInner( - _ body: (UnsafeHandle) -> R + _ body: (_UnsafeHandle) -> R ) -> R { asInner.withUnsafeMutablePointers { h, p in - let handle = UnsafeHandle(isMutable: true, header: h, start: p) + let handle = _UnsafeHandle(isMutable: true, header: h, start: p) return body(handle) } } } -extension _Rope.Node { - mutating func _insertItem(_ item: __owned Item, at slot: Int) { +extension Rope._Node { + mutating func _insertItem(_ item: __owned _Item, at slot: Int) { assert(isLeaf) ensureUnique() self.summary.add(item.summary) @@ -199,8 +199,8 @@ extension _Rope.Node { } } -extension _Rope.Node { - mutating func _appendItem(_ item: __owned Item) { +extension Rope._Node { + mutating func _appendItem(_ item: __owned _Item) { assert(isLeaf) ensureUnique() self.summary.add(item.summary) @@ -215,8 +215,8 @@ extension _Rope.Node { } } -extension _Rope.Node { - mutating func _removeItem(at slot: Int) -> (removed: Item, delta: Summary) { +extension Rope._Node { + mutating func _removeItem(at slot: Int) -> (removed: _Item, delta: Summary) { assert(isLeaf) ensureUnique() let item = updateLeaf { $0._removeChild(at: slot) } @@ -234,7 +234,7 @@ extension _Rope.Node { } } -extension _Rope.Node { +extension Rope._Node { mutating func split(keeping desiredCount: Int) -> Self { assert(desiredCount >= 0 && desiredCount <= childCount) var new = isLeaf ? Self.createLeaf() : Self.createInner(height: height) @@ -250,8 +250,8 @@ extension _Rope.Node { } } -extension _Rope.Node { - mutating func rebalance(nextNeighbor right: inout _Rope.Node) -> Bool { +extension Rope._Node { + mutating func rebalance(nextNeighbor right: inout Rope._Node) -> Bool { assert(self.height == right.height) if self.isEmpty { swap(&self, &right) @@ -340,27 +340,27 @@ extension _Rope.Node { } } -extension _Rope.Node { - var startPath: Path { - Path(height: self.height) +extension Rope._Node { + var _startPath: _Path { + _Path(height: self.height) } - var lastPath: Path { - var path = Path(height: self.height) + var lastPath: _Path { + var path = _Path(height: self.height) _ = descendToLastItem(under: &path) return path } - func isAtEnd(_ path: Path) -> Bool { + func isAtEnd(_ path: _Path) -> Bool { path[self.height] == childCount } - func descendToFirstItem(under path: inout Path) -> UnmanagedLeaf { + func descendToFirstItem(under path: inout _Path) -> _UnmanagedLeaf { path.clear(below: self.height + 1) return unmanagedLeaf(at: path) } - func descendToLastItem(under path: inout Path) -> UnmanagedLeaf { + func descendToLastItem(under path: inout _Path) -> _UnmanagedLeaf { let h = self.height let slot = self.childCount - 1 path[h] = slot @@ -371,21 +371,21 @@ extension _Rope.Node { } } -extension _Rope { - func _unmanagedLeaf(at path: Path) -> UnmanagedLeaf? { - assert(path.height == self.height) - guard path < endPath else { return nil } +extension Rope { + func _unmanagedLeaf(at path: _Path) -> _UnmanagedLeaf? { + assert(path.height == self._height) + guard path < _endPath else { return nil } return root.unmanagedLeaf(at: path) } } -extension _Rope.Node { - var asUnmanagedLeaf: UnmanagedLeaf { +extension Rope._Node { + var asUnmanagedLeaf: _UnmanagedLeaf { assert(height == 0) - return UnmanagedLeaf(unsafeDowncast(self.object, to: Storage.self)) + return _UnmanagedLeaf(unsafeDowncast(self.object, to: _Storage<_Item>.self)) } - func unmanagedLeaf(at path: Path) -> UnmanagedLeaf { + func unmanagedLeaf(at path: _Path) -> _UnmanagedLeaf { if height == 0 { return asUnmanagedLeaf } @@ -394,7 +394,7 @@ extension _Rope.Node { } } -extension _Rope.Node { +extension Rope._Node { func formSuccessor(of i: inout Index) -> Bool { let h = self.height var slot = i._path[h] @@ -449,8 +449,8 @@ extension _Rope.Node { } } -extension _Rope.Node { - var lastItem: Item { +extension Rope._Node { + var lastItem: _Item { get { self[lastPath] } @@ -464,16 +464,16 @@ extension _Rope.Node { } } - var firstItem: Item { + var firstItem: _Item { get { - self[startPath] + self[_startPath] } _modify { - yield &self[startPath] + yield &self[_startPath] } } - subscript(path: Path) -> Item { + subscript(path: _Path) -> _Item { get { let h = height let slot = path[h] @@ -493,13 +493,13 @@ extension _Rope.Node { } } - struct ModifyState { - var path: Path - var item: Item + struct _ModifyState { + var path: _Path + var item: _Item var summary: Summary } - mutating func _prepareModify(at path: Path) -> ModifyState { + mutating func _prepareModify(at path: _Path) -> _ModifyState { ensureUnique() let h = height let slot = path[h] @@ -508,15 +508,15 @@ extension _Rope.Node { return updateInner { $0.mutableChildren[slot]._prepareModify(at: path) } } let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) } - return ModifyState(path: path, item: item, summary: item.summary) + return _ModifyState(path: path, item: item, summary: item.summary) } - mutating func _prepareModifyLast() -> ModifyState { - var path = Path(height: height) + mutating func _prepareModifyLast() -> _ModifyState { + var path = _Path(height: height) return _prepareModifyLast(&path) } - mutating func _prepareModifyLast(_ path: inout Path) -> ModifyState { + mutating func _prepareModifyLast(_ path: inout _Path) -> _ModifyState { ensureUnique() let h = height let slot = self.childCount - 1 @@ -525,12 +525,12 @@ extension _Rope.Node { return updateInner { $0.mutableChildren[slot]._prepareModifyLast(&path) } } let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) } - return ModifyState(path: path, item: item, summary: item.summary) + return _ModifyState(path: path, item: item, summary: item.summary) } mutating func _finalizeModify( - _ state: inout ModifyState - ) -> (delta: Summary, leaf: UnmanagedLeaf) { + _ state: inout _ModifyState + ) -> (delta: Summary, leaf: _UnmanagedLeaf) { assert(isUnique()) let h = height let slot = state.path[h] diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Storage.swift b/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift similarity index 79% rename from Sources/RopeModule/Rope/Basics/_Rope+Storage.swift rename to Sources/RopeModule/Rope/Basics/Rope+_Storage.swift index 39d5b76c..c5642ebb 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+Storage.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift @@ -28,14 +28,14 @@ internal struct _RopeStorageHeader { } } -extension _Rope { - final class Storage>: ManagedBuffer<_RopeStorageHeader, Child> { +extension Rope { + final class _Storage>: ManagedBuffer<_RopeStorageHeader, Child> { typealias Summary = Element.Summary - typealias UnsafeHandle = _Rope.UnsafeHandle + typealias _UnsafeHandle = Rope._UnsafeHandle - static func create(height: UInt8) -> Storage { + static func create(height: UInt8) -> _Storage { let object = create(minimumCapacity: Summary.maxNodeSize) { _ in .init(height: height) } - return unsafeDowncast(object, to: Storage.self) + return unsafeDowncast(object, to: _Storage.self) } deinit { diff --git a/Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift b/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift similarity index 64% rename from Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift rename to Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift index 8ab0f9db..ec393fa2 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+UnmanagedLeaf.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift @@ -9,33 +9,33 @@ // //===----------------------------------------------------------------------===// -extension _Rope { - internal struct UnmanagedLeaf { - typealias Item = _Rope.Item - typealias Leaf = Storage - typealias UnsafeHandle = _Rope.UnsafeHandle +extension Rope { + internal struct _UnmanagedLeaf { + typealias _Item = Rope._Item + typealias _Leaf = _Storage<_Item> + typealias _UnsafeHandle = Rope._UnsafeHandle - var _ref: Unmanaged + var _ref: Unmanaged<_Leaf> - init(_ leaf: __shared Leaf) { + init(_ leaf: __shared _Leaf) { _ref = .passUnretained(leaf) } } } -extension _Rope.UnmanagedLeaf: Equatable { +extension Rope._UnmanagedLeaf: Equatable { static func ==(left: Self, right: Self) -> Bool { left._ref.toOpaque() == right._ref.toOpaque() } } -extension _Rope.UnmanagedLeaf { +extension Rope._UnmanagedLeaf { func read( - body: (UnsafeHandle) -> R + body: (_UnsafeHandle<_Item>) -> R ) -> R { _ref._withUnsafeGuaranteedRef { leaf in leaf.withUnsafeMutablePointers { h, p in - let handle = UnsafeHandle(isMutable: false, header: h, start: p) + let handle = _UnsafeHandle(isMutable: false, header: h, start: p) return body(handle) } } diff --git a/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift b/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift similarity index 91% rename from Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift rename to Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift index 6b27a180..0d6c7293 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope+UnsafeHandle.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift @@ -9,10 +9,10 @@ // //===----------------------------------------------------------------------===// -extension _Rope { - internal struct UnsafeHandle> { - typealias Summary = _Rope.Summary - typealias Element = _Rope.Element +extension Rope { + internal struct _UnsafeHandle> { + typealias Summary = Rope.Summary + typealias Element = Rope.Element let _header: UnsafeMutablePointer<_RopeStorageHeader> let _start: UnsafeMutablePointer @@ -41,7 +41,7 @@ extension _Rope { } } -extension _Rope.UnsafeHandle { +extension Rope._UnsafeHandle { @inline(__always) var capacity: Int { Summary.maxNodeSize } @@ -82,8 +82,8 @@ extension _Rope.UnsafeHandle { return UnsafeMutableBufferPointer(start: _start, count: capacity) } - func copy() -> _Rope.Storage { - let new = _Rope.Storage.create(height: self.height) + func copy() -> Rope._Storage { + let new = Rope._Storage.create(height: self.height) let c = self.childCount new.header.childCount = c new.withUnsafeMutablePointerToElements { target in @@ -92,9 +92,9 @@ extension _Rope.UnsafeHandle { return new } - func copy(slots: Range) -> (object: _Rope.Storage, summary: Summary) { + func copy(slots: Range) -> (object: Rope._Storage, summary: Summary) { assert(slots.lowerBound >= 0 && slots.upperBound <= childCount) - let object = _Rope.Storage.create(height: self.height) + let object = Rope._Storage.create(height: self.height) let c = slots.count let summary = object.withUnsafeMutablePointers { h, p in h.pointee.childCount = c @@ -186,7 +186,7 @@ extension _Rope.UnsafeHandle { return children.prefix(count)._sum() } - func distance(from start: Int, to end: Int, in metric: some _RopeMetric) -> Int { + func distance(from start: Int, to end: Int, in metric: some RopeMetric) -> Int { if start <= end { return children[start ..< end].reduce(into: 0) { $0 += metric._nonnegativeSize(of: $1.summary) diff --git a/Sources/RopeModule/Rope/Basics/_Rope.swift b/Sources/RopeModule/Rope/Basics/Rope.swift similarity index 76% rename from Sources/RopeModule/Rope/Basics/_Rope.swift rename to Sources/RopeModule/Rope/Basics/Rope.swift index fb0fa470..43d631e3 100644 --- a/Sources/RopeModule/Rope/Basics/_Rope.swift +++ b/Sources/RopeModule/Rope/Basics/Rope.swift @@ -12,8 +12,8 @@ /// An ordered data structure of `Element` values that organizes itself into a tree. /// The rope is augmented by the commutative group specified by `Element.Summary`, enabling /// quick lookup operations. -public struct _Rope { - var _root: Node? +public struct Rope { + var _root: _Node? var _version: _RopeVersion public init() { @@ -21,40 +21,40 @@ public struct _Rope { self._version = _RopeVersion() } - init(root: Node?) { + init(root: _Node?) { self._root = root self._version = _RopeVersion() } - var root: Node { + var root: _Node { get { _root.unsafelyUnwrapped } @inline(__always) _modify { yield &_root! } } public init(_ value: Element) { - self._root = .createLeaf(Item(value)) + self._root = .createLeaf(_Item(value)) self._version = _RopeVersion() } } -extension _Rope: Sendable where Element: Sendable {} +extension Rope: Sendable where Element: Sendable {} -extension _Rope { - mutating func ensureUnique() { +extension Rope { + mutating func _ensureUnique() { guard _root != nil else { return } root.ensureUnique() } } -extension _Rope { - var isSingleton: Bool { +extension Rope { + public var isSingleton: Bool { guard _root != nil else { return false } return root.isSingleton } } -extension _Rope { - func isIdentical(to other: Self) -> Bool { +extension Rope { + public func isIdentical(to other: Self) -> Bool { self._root?.object === other._root?.object } } diff --git a/Sources/RopeModule/Rope/Basics/_RopeElement.swift b/Sources/RopeModule/Rope/Basics/RopeElement.swift similarity index 92% rename from Sources/RopeModule/Rope/Basics/_RopeElement.swift rename to Sources/RopeModule/Rope/Basics/RopeElement.swift index 8f5c7889..de4bf99a 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeElement.swift +++ b/Sources/RopeModule/Rope/Basics/RopeElement.swift @@ -10,9 +10,9 @@ //===----------------------------------------------------------------------===// /// The element type of an augmented tree. -public protocol _RopeElement { +public protocol RopeElement { /// The commutative group that is used to augment the tree. - associatedtype Summary: _RopeSummary + associatedtype Summary: RopeSummary associatedtype Index: Comparable /// Returns the summary of `self`. @@ -29,7 +29,7 @@ public protocol _RopeElement { mutating func split(at index: Index) -> Self } -extension _RopeElement { +extension RopeElement { @inlinable public mutating func rebalance(prevNeighbor left: inout Self) -> Bool { guard left.rebalance(nextNeighbor: &self) else { return false } diff --git a/Sources/RopeModule/Rope/Basics/_RopeMetric.swift b/Sources/RopeModule/Rope/Basics/RopeMetric.swift similarity index 86% rename from Sources/RopeModule/Rope/Basics/_RopeMetric.swift rename to Sources/RopeModule/Rope/Basics/RopeMetric.swift index a88d7fb4..ad6d4f63 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeMetric.swift +++ b/Sources/RopeModule/Rope/Basics/RopeMetric.swift @@ -9,14 +9,14 @@ // //===----------------------------------------------------------------------===// -public protocol _RopeMetric: Sendable { - associatedtype Element: _RopeElement +public protocol RopeMetric: Sendable { + associatedtype Element: RopeElement func size(of summary: Element.Summary) -> Int func index(at offset: Int, in element: Element) -> Element.Index } -extension _RopeMetric { +extension RopeMetric { @inline(__always) internal func _nonnegativeSize(of summary: Element.Summary) -> Int { let r = size(of: summary) diff --git a/Sources/RopeModule/Rope/Basics/_RopeSummary.swift b/Sources/RopeModule/Rope/Basics/RopeSummary.swift similarity index 94% rename from Sources/RopeModule/Rope/Basics/_RopeSummary.swift rename to Sources/RopeModule/Rope/Basics/RopeSummary.swift index bc1b404b..8afabccb 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeSummary.swift +++ b/Sources/RopeModule/Rope/Basics/RopeSummary.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// /// A commutative group that is used to augment a tree, enabling quick lookup operations. -public protocol _RopeSummary: Equatable, Sendable { +public protocol RopeSummary: Equatable, Sendable { static var maxNodeSize: Int { get } static var nodeSizeBitWidth: Int { get } @@ -35,12 +35,12 @@ public protocol _RopeSummary: Equatable, Sendable { mutating func subtract(_ other: Self) } -extension _RopeSummary { +extension RopeSummary { @inlinable @inline(__always) public static var minNodeSize: Int { (maxNodeSize + 1) / 2 } } -extension _RopeSummary { +extension RopeSummary { @inlinable public func adding(_ other: Self) -> Self { var c = self diff --git a/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift deleted file mode 100644 index b6b8fe8c..00000000 --- a/Sources/RopeModule/Rope/Basics/_Rope+Builder.swift +++ /dev/null @@ -1,438 +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 -// -//===----------------------------------------------------------------------===// - -extension _Rope { - public init(_ items: some Sequence) { - if let items = items as? Self { - self = items - return - } - var builder = Builder() - for item in items { - builder.append(item) - } - self = builder.finalize() - } -} - -extension _Rope { - public struct Builder { - public typealias Rope = _Rope - - // ║ ║ - // ║ ║ ║ ║ - // ║ ║ ║ ║ ║ ║ - // ║ ║ ║ ║ ║ ║ ║ ║ - // ──╨─╨─╨─╨──╨──╨──╨─╨─╨─╨── - // →prefixTrees→ ↑ ↑ ←suffixTrees← - // prefix suffix - - private var prefixTrees: [_Rope] = [] - private var prefixLeaf: _Rope.Node? - var prefix: _Rope.Item? - - var suffix: _Rope.Item? - var suffixTrees: [_Rope] = [] - - var isPrefixEmpty: Bool { - if prefix != nil { return false } - if let leaf = self.prefixLeaf, !leaf.isEmpty { return false } - return prefixTrees.isEmpty - } - - var isSuffixEmpty: Bool { - if suffix != nil { return false } - return suffixTrees.isEmpty - } - - var prefixSummary: Summary { - var sum = Summary.zero - for sapling in prefixTrees { - sum.add(sapling.summary) - } - if let leaf = prefixLeaf { sum.add(leaf.summary) } - if let item = prefix { sum.add(item.summary) } - return sum - } - - var suffixSummary: Summary { - var sum = Summary.zero - if let item = suffix { sum.add(item.summary) } - for rope in suffixTrees { - sum.add(rope.summary) - } - return sum - } - - var lastPrefixItem: _Rope.Item { - get { - assert(!isPrefixEmpty) - if let item = self.prefix { return item } - if let leaf = self.prefixLeaf { return leaf.lastItem } - return prefixTrees.last!.root.lastItem - } - _modify { - assert(!isPrefixEmpty) - if prefix != nil { - yield &prefix! - } else if prefixLeaf?.isEmpty == false { - yield &prefixLeaf!.lastItem - } else { - yield &prefixTrees[prefixTrees.count - 1].root.lastItem - } - } - } - - var firstSuffixItem: _Rope.Item { - get { - assert(!isSuffixEmpty) - if let suffix { return suffix } - return suffixTrees[suffixTrees.count - 1].root.firstItem - } - _modify { - assert(!isSuffixEmpty) - if suffix != nil { - yield &suffix! - } else { - yield &suffixTrees[suffixTrees.count - 1].root.firstItem - } - } - } - - func forEachElementInPrefix( - from position: Int, - in metric: some _RopeMetric, - _ body: (Element, Element.Index?) -> Bool - ) -> Bool { - var position = position - var i = 0 - while i < prefixTrees.count { - let size = metric.size(of: prefixTrees[i].summary) - if position < size { break } - position -= size - i += 1 - } - if i < prefixTrees.count { - guard prefixTrees[i].forEachWhile(from: position, in: metric, body) else { return false } - i += 1 - while i < prefixTrees.count { - guard prefixTrees[i].forEachWhile({ body($0, nil) }) else { return false } - i += 1 - } - if let leaf = self.prefixLeaf { - guard leaf.forEachWhile({ body($0, nil) }) else { return false } - } - if let item = self.prefix { - guard body(item.value, nil) else { return false } - } - return true - } - - if let leaf = self.prefixLeaf { - let size = metric.size(of: leaf.summary) - if position < size { - guard leaf.forEachWhile(from: position, in: metric, body) else { return false } - if let item = self.prefix { - guard body(item.value, nil) else { return false } - } - return true - } - position -= size - } - if let item = self.prefix { - let i = metric.index(at: position, in: item.value) - guard body(item.value, i) else { return false} - } - return true - } - - mutating func mutatingForEachSuffix( - _ body: (inout Element) -> R? - ) -> R? { - if self.suffix != nil, - let r = body(&self.suffix!.value) { - return r - } - for i in stride(from: suffixTrees.count - 1, through: 0, by: -1) { - if let r = self.suffixTrees[i].mutatingForEach(body) { - return r - } - } - return nil - } - - public mutating func append(_ item: __owned Element) { - append(_Rope.Item(item)) - } - - mutating func append(_ item: __owned _Rope.Item) { - guard !item.isEmpty else { return } - guard var prefix = self.prefix._take() else { - self.prefix = item - return - } - var item = item - if prefix.rebalance(nextNeighbor: &item) { - self.prefix = prefix - return - } - _append(prefix) - self.prefix = item - } - - mutating func _append(_ item: __owned _Rope.Item) { - assert(self.prefix == nil) - assert(!item.isUndersized) - var leaf = self.prefixLeaf._take() ?? .createLeaf() - leaf._appendItem(item) - if leaf.isFull { - self._append(leaf) - } else { - self.prefixLeaf = leaf - } - invariantCheck() - } - - public mutating func append(_ rope: __owned Rope) { - guard rope._root != nil else { return } - append(rope.root) - } - - mutating func append(_ node: __owned Rope.Node) { - defer { invariantCheck() } - var node = node - if node.height == 0 { - if node.childCount == 1 { - append(node.firstItem) - return - } - if let item = self.prefix._take() { - if let spawn = node.prepend(item) { - append(node) - append(spawn) - return - } - } - if var leaf = self.prefixLeaf._take() { - if leaf.rebalance(nextNeighbor: &node), !leaf.isFull { - self.prefixLeaf = leaf - return - } - self._append(leaf) - } - - if node.isFull { - self._append(node) - } else { - self.prefixLeaf = node - } - return - } - - if var prefix = self.prefix._take() { - if !prefix.isUndersized || !node.firstItem.rebalance(prevNeighbor: &prefix) { - self._append(prefix) - } - } - if let leaf = self.prefixLeaf._take() { - _append(leaf) - } - _append(node) - } - - mutating func _append(_ rope: __owned Rope.Node) { - assert(self.prefix == nil && self.prefixLeaf == nil) - var new = rope - while !prefixTrees.isEmpty { - // Join previous saplings together until they grow at least as deep as the new one. - var previous = prefixTrees.removeLast() - while previous.height < new.height { - if prefixTrees.isEmpty { - previous.append(new) - prefixTrees.append(previous) - return - } - previous.prepend(prefixTrees.removeLast()) - } - - if previous.height == new.height { - if previous.root.rebalance(nextNeighbor: &new) { - new = previous.root - } else { - new = .createInner(children: previous.root, new) - } - continue - } - - if new.isFull, !previous.root.isFull, previous.height == new.height + 1 { - // Graft node under the last sapling, as a new child branch. - previous.root._appendNode(new) - new = previous.root - continue - } - - // The new seedling can be appended to the line and we're done. - prefixTrees.append(previous) - break - } - prefixTrees.append(Rope(root: new)) - } - - mutating func prependSuffix(_ item: __owned Item) { - guard !item.isEmpty else { return } - if var suffixItem = self.suffix._take() { - var item = item - if !(suffixItem.isUndersized && item.rebalance(nextNeighbor: &suffixItem)) { - if suffixTrees.isEmpty { - suffixTrees.append(Rope(root: .createLeaf(suffixItem))) - } else { - suffixTrees[suffixTrees.count - 1].prepend(suffixItem.value) - } - } - } - self.suffix = item - } - - public mutating func prependSuffix(_ rope: __owned Rope) { - assert(suffix == nil) - assert(suffixTrees.isEmpty || rope.height <= suffixTrees.last!.height) - suffixTrees.append(rope) - } - - mutating func prependSuffix(_ rope: __owned Rope.Node) { - prependSuffix(_Rope(root: rope)) - } - - mutating func append(slots: Range, in node: __owned Rope.Node) { - assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) - let c = slots.count - guard c > 0 else { return } - if c == 1 { - if node.isLeaf { - let item = node.readLeaf { $0.children[slots.lowerBound] } - append(item) - } else { - let child = node.readInner { $0.children[slots.lowerBound] } - append(child) - } - return - } - let copy = node.copy(slots: slots) - append(copy) - } - - mutating func prependSuffix(slots: Range, in node: __owned Rope.Node) { - assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) - let c = slots.count - guard c > 0 else { return } - if c == 1 { - if node.isLeaf { - let item = node.readLeaf { $0.children[slots.lowerBound] } - prependSuffix(item) - } else { - let child = node.readInner { $0.children[slots.lowerBound] } - prependSuffix(child) - } - return - } - let copy = node.copy(slots: slots) - prependSuffix(copy) - } - - public mutating func finalize() -> Rope { - // Integrate prefix & suffix chunks. - if let suffixItem = self.suffix._take() { - append(suffixItem) - } - if var prefix = self.prefix._take() { - if !prefix.isUndersized { - _append(prefix) - } else if !self.isPrefixEmpty { - if !self.lastPrefixItem.rebalance(nextNeighbor: &prefix) { - _append(prefix) - } - } else if !self.isSuffixEmpty { - if !self.firstSuffixItem.rebalance(prevNeighbor: &prefix) { - _append(prefix) - } - } else { - // We only have the seed; allow undersized chunk - return Rope(root: .createLeaf(prefix)) - } - } - assert(self.prefix == nil && self.suffix == nil) - while let tree = suffixTrees.popLast() { - append(tree) - } - // Merge all saplings, the seedling and the seed into a single rope. - if let item = self.prefix._take() { - _append(item) - } - var rope = Rope(root: prefixLeaf._take()) - while let tree = prefixTrees.popLast() { - rope.prepend(tree) - } - assert(prefixLeaf == nil && prefixTrees.isEmpty && suffixTrees.isEmpty) - rope.invariantCheck() - return rope - } - - public func invariantCheck() { -#if DEBUG - var h = UInt8.max - for sapling in prefixTrees { - precondition(sapling.height <= h) - sapling.invariantCheck() - h = sapling.height - } - if let leaf = self.prefixLeaf { - precondition(leaf.height == 0) - precondition(!leaf.isFull) - leaf.invariantCheck(depth: 0, height: 0) - } - h = 0 - for tree in suffixTrees.reversed() { - precondition(tree.height >= h) - tree.invariantCheck() - h = tree.height - } -#endif - - } - - public func dump(heightLimit: Int = Int.max) { - for i in self.prefixTrees.indices { - print("Sapling \(i):") - self.prefixTrees[i].dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") - } - if let leaf = self.prefixLeaf { - print("Seedling:") - leaf.dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") - } - if let item = self.prefix { - print("Seed:") - print(" \(item)") - } - print("---") - var i = 0 - if let item = self.suffix { - print("Suffix \(i):") - i += 1 - print(" \(item)") - } - for tree in self.suffixTrees.reversed() { - print("Suffix \(i)") - i += 1 - tree.dump(heightLimit: heightLimit, firstPrefix: " ", restPrefix: " ") - } - } - } -} diff --git a/Sources/RopeModule/Rope/Basics/_RopeItem.swift b/Sources/RopeModule/Rope/Basics/_RopeItem.swift index 5fcfc469..61724d8a 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeItem.swift +++ b/Sources/RopeModule/Rope/Basics/_RopeItem.swift @@ -9,13 +9,13 @@ // //===----------------------------------------------------------------------===// -/// An internal protocol describing a summarizable entity that isn't a full `_RopeElement`. +/// An internal protocol describing a summarizable entity that isn't a full `RopeElement`. /// /// Used as an implementation detail to increase code reuse across internal nodes and leaf nodes. -/// (Ideally `_Rope.Node` would just conform to the full `_RopeElement` protocol on its own, but +/// (Ideally `Rope._Node` would just conform to the full `RopeElement` protocol on its own, but /// while that's an obvious refactoring idea, it hasn't happened yet.) internal protocol _RopeItem { - associatedtype Summary: _RopeSummary + associatedtype Summary: RopeSummary var summary: Summary { get } } @@ -26,35 +26,36 @@ extension Sequence where Element: _RopeItem { } } -extension _Rope: _RopeItem { - typealias Summary = Element.Summary - var summary: Summary { +extension Rope: _RopeItem { + public typealias Summary = Element.Summary + + public var summary: Summary { guard _root != nil else { return .zero } return root.summary } } -extension _Rope { +extension Rope { /// A trivial wrapper around a rope's Element type, giving it `_RopeItem` conformance without /// having to make the protocol public. - internal struct Item { + internal struct _Item { var value: Element init(_ value: Element) { self.value = value } } } -extension _Rope.Item: _RopeItem { - typealias Summary = _Rope.Summary +extension Rope._Item: _RopeItem { + typealias Summary = Rope.Summary var summary: Summary { value.summary } } -extension _Rope.Item: CustomStringConvertible { +extension Rope._Item: CustomStringConvertible { var description: String { "\(value)" } } -extension _Rope.Item { +extension Rope._Item { var isEmpty: Bool { value.isEmpty } var isUndersized: Bool { value.isUndersized } mutating func rebalance(nextNeighbor right: inout Self) -> Bool { diff --git a/Sources/RopeModule/Rope/Basics/_RopePath.swift b/Sources/RopeModule/Rope/Basics/_RopePath.swift index eee790a5..c7278eea 100644 --- a/Sources/RopeModule/Rope/Basics/_RopePath.swift +++ b/Sources/RopeModule/Rope/Basics/_RopePath.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -internal struct _RopePath { +internal struct _RopePath { // ┌──────────────────────────────────┬────────┐ // │ b63:b8 │ b7:b0 │ // ├──────────────────────────────────┼────────┤ @@ -30,8 +30,8 @@ internal struct _RopePath { } } -extension _Rope { - typealias Path = _RopePath +extension Rope { + typealias _Path = _RopePath } extension _RopePath: Equatable { diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift similarity index 83% rename from Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift rename to Sources/RopeModule/Rope/Conformances/Rope+Collection.swift index 8cc04df8..ebf22f34 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { public func isValid(_ index: Index) -> Bool { index._version == _version } @@ -18,45 +18,49 @@ extension _Rope { precondition(isValid(index), "Invalid index") } - mutating func invalidateIndices() { + mutating func _invalidateIndices() { _version.bump() } - func ensureLeaf(in index: inout Index) { + /// Validate `index` and fill out all cached information in it, + /// to speed up subsequent lookups. + public func grease(_ index: inout Index) { validate(index) guard index._leaf == nil else { return } index._leaf = _unmanagedLeaf(at: index._path) } } -extension _Rope: BidirectionalCollection { - var height: UInt8 { +extension Rope { + public var _height: UInt8 { _root?.height ?? 0 } + var _startPath: _Path { + _Path(height: _height) + } + + var _endPath: _Path { + guard let root = _root else { return _startPath } + var path = _Path(height: _height) + path[_height] = root.childCount + return path + } +} + +extension Rope: BidirectionalCollection { public var isEmpty: Bool { guard _root != nil else { return true } return root.childCount == 0 } - var startPath: Path { - Path(height: height) - } - - var endPath: Path { - guard let root = _root else { return startPath } - var path = Path(height: height) - path[height] = root.childCount - return path - } - public var startIndex: Index { // Note: `leaf` is intentionally not set here, to speed up accessing this property. - return Index(version: _version, path: startPath, leaf: nil) + return Index(version: _version, path: _startPath, leaf: nil) } public var endIndex: Index { - Index(version: _version, path: endPath, leaf: nil) + Index(version: _version, path: _endPath, leaf: nil) } public func index(after i: Index) -> Index { @@ -117,13 +121,13 @@ extension _Rope: BidirectionalCollection { @inline(__always) _modify { validate(i) // Note: we must not use _leaf -- it may not be on a unique path. - defer { invalidateIndices() } + defer { _invalidateIndices() } yield &root[i._path].value } } } -extension _Rope { +extension Rope { /// Update the element at the given index, while keeping the index valid. public mutating func update( at index: inout Index, @@ -138,9 +142,9 @@ extension _Rope { } } -extension _Rope { - public static var maxHeight: Int { - Path._pathBitWidth / Summary.nodeSizeBitWidth +extension Rope { + public static var _maxHeight: Int { + _Path._pathBitWidth / Summary.nodeSizeBitWidth } /// The estimated maximum number of items that can fit in this rope in the worst possible case, @@ -149,9 +153,9 @@ extension _Rope { /// representation used in the `Index` type.) /// /// This is one less than the minimum possible size for a rope whose size exceeds the maximum. - public static var minimumCapacity: Int { + public static var _minimumCapacity: Int { var c = 2 - for _ in 0 ..< maxHeight { + for _ in 0 ..< _maxHeight { let (r, overflow) = c.multipliedReportingOverflow(by: Summary.minNodeSize) if overflow { return .max } c = r @@ -163,9 +167,9 @@ extension _Rope { /// the tree consists of maximum-sized nodes. (The data structure itself has no inherent limit, /// but this implementation of it is limited by the fixed 56-bit path representation used in /// the `Index` type.) - public static var maximumCapacity: Int { + public static var _maximumCapacity: Int { var c = 1 - for _ in 0 ... maxHeight { + for _ in 0 ... _maxHeight { let (r, overflow) = c.multipliedReportingOverflow(by: Summary.maxNodeSize) if overflow { return .max } c = r @@ -174,21 +178,21 @@ extension _Rope { } } -extension _Rope { - public func count(in metric: some _RopeMetric) -> Int { +extension Rope { + public func count(in metric: some RopeMetric) -> Int { guard _root != nil else { return 0 } return root.count(in: metric) } } -extension _Rope.Node { - public func count(in metric: some _RopeMetric) -> Int { +extension Rope._Node { + public func count(in metric: some RopeMetric) -> Int { metric._nonnegativeSize(of: self.summary) } } -extension _Rope { - public func distance(from start: Index, to end: Index, in metric: some _RopeMetric) -> Int { +extension Rope { + public func distance(from start: Index, to end: Index, in metric: some RopeMetric) -> Int { validate(start) validate(end) if start == end { return 0 } @@ -208,19 +212,19 @@ extension _Rope { return -root.distance(from: end, to: start, in: metric) } - func offset(of index: Index, in metric: some _RopeMetric) -> Int { + func offset(of index: Index, in metric: some RopeMetric) -> Int { validate(index) if _root == nil { return 0 } return root.distanceFromStart(to: index, in: metric) } } -extension _Rope.Node { - func distanceFromStart(to index: Index, in metric: some _RopeMetric) -> Int { +extension Rope._Node { + func distanceFromStart(to index: Index, in metric: some RopeMetric) -> Int { let slot = index._path[height] precondition(slot <= childCount, "Invalid index") if slot == childCount { - precondition(index.isEmpty(below: height), "Invalid index") + precondition(index._isEmpty(below: height), "Invalid index") return metric._nonnegativeSize(of: self.summary) } if height == 0 { @@ -233,13 +237,13 @@ extension _Rope.Node { } } - func distanceToEnd(from index: Index, in metric: some _RopeMetric) -> Int { + func distanceToEnd(from index: Index, in metric: some RopeMetric) -> Int { let d = metric._nonnegativeSize(of: self.summary) - self.distanceFromStart(to: index, in: metric) assert(d >= 0) return d } - func distance(from start: Index, to end: Index, in metric: some _RopeMetric) -> Int { + func distance(from start: Index, to end: Index, in metric: some RopeMetric) -> Int { assert(start < end) let a = start._path[height] let b = end._path[height] @@ -247,7 +251,7 @@ extension _Rope.Node { precondition(b <= childCount, "Invalid index") assert(a <= b) if b == childCount { - precondition(end.isEmpty(below: height), "Invalid index") + precondition(end._isEmpty(below: height), "Invalid index") return distanceToEnd(from: start, in: metric) } if height == 0 { @@ -267,11 +271,11 @@ extension _Rope.Node { } } -extension _Rope { +extension Rope { public func formIndex( _ i: inout Index, offsetBy distance: inout Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, preferEnd: Bool ) { validate(i) @@ -303,7 +307,7 @@ extension _Rope { public func index( _ i: Index, offsetBy distance: Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, preferEnd: Bool ) -> (index: Index, remainder: Int) { var i = i @@ -313,11 +317,11 @@ extension _Rope { } } -extension _Rope.UnsafeHandle { +extension Rope._UnsafeHandle { func _seekForwardInLeaf( - from path: inout _Rope.Path, + from path: inout Rope._Path, by distance: inout Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, preferEnd: Bool ) -> Bool { assert(distance >= 0) @@ -337,9 +341,9 @@ extension _Rope.UnsafeHandle { } func _seekBackwardInLeaf( - from path: inout _Rope.Path, + from path: inout Rope._Path, by distance: inout Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, preferEnd: Bool ) -> Bool { assert(distance >= 0) @@ -360,11 +364,11 @@ extension _Rope.UnsafeHandle { } } -extension _Rope.Node { +extension Rope._Node { func seekForward( from i: inout Index, by distance: inout Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, preferEnd: Bool ) -> Bool { assert(distance >= 0) @@ -391,7 +395,7 @@ extension _Rope.Node { let d = metric.size(of: c[slot].summary) if preferEnd ? d >= distance : d > distance { i._path[$0.height] = slot - i.clear(below: $0.height) + i._clear(below: $0.height) let success = c[slot].seekForward( from: &i, by: &distance, in: metric, preferEnd: preferEnd) precondition(success) @@ -407,7 +411,7 @@ extension _Rope.Node { func seekBackward( from i: inout Index, by distance: inout Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, preferEnd: Bool ) -> Bool { assert(distance >= 0) @@ -431,7 +435,7 @@ extension _Rope.Node { let d = metric.size(of: c[slot].summary) if preferEnd ? d > distance : d >= distance { i._path[$0.height] = slot - i.clear(below: $0.height) + i._clear(below: $0.height) distance = d - distance let success = c[slot].seekForward( from: &i, by: &distance, in: metric, preferEnd: preferEnd) diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift b/Sources/RopeModule/Rope/Conformances/Rope+Index.swift similarity index 69% rename from Sources/RopeModule/Rope/Conformances/_Rope+Index.swift rename to Sources/RopeModule/Rope/Conformances/Rope+Index.swift index 12364871..e90f3e36 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Index.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Index.swift @@ -9,19 +9,19 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { public struct Index: @unchecked Sendable { - typealias Path = _Rope.Path - typealias Summary = _Rope.Summary + typealias Summary = Rope.Summary + typealias _Path = Rope._Path var _version: _RopeVersion - var _path: Path + var _path: _Path /// A direct reference to the leaf node addressed by this index. /// This must only be dereferenced while we own a tree with a matching /// version. - var _leaf: UnmanagedLeaf? + var _leaf: _UnmanagedLeaf? - init(version: _RopeVersion, path: Path, leaf: __shared UnmanagedLeaf?) { + init(version: _RopeVersion, path: _Path, leaf: __shared _UnmanagedLeaf?) { self._version = version self._path = path self._leaf = leaf @@ -29,49 +29,49 @@ extension _Rope { } } -extension _Rope.Index { - static var invalid: Self { +extension Rope.Index { + static var _invalid: Self { Self(version: _RopeVersion(0), path: _RopePath(_value: .max), leaf: nil) } - var isValid: Bool { + var _isValid: Bool { _path._value != .max } } -extension _Rope.Index: Equatable { +extension Rope.Index: Equatable { public static func ==(left: Self, right: Self) -> Bool { left._path == right._path } } -extension _Rope.Index: Hashable { +extension Rope.Index: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(_path) } } -extension _Rope.Index: Comparable { +extension Rope.Index: Comparable { public static func <(left: Self, right: Self) -> Bool { left._path < right._path } } -extension _Rope.Index: CustomStringConvertible { +extension Rope.Index: CustomStringConvertible { public var description: String { "\(_path)" } } -extension _Rope.Index { - var height: UInt8 { +extension Rope.Index { + var _height: UInt8 { _path.height } - func isEmpty(below height: UInt8) -> Bool { + func _isEmpty(below height: UInt8) -> Bool { _path.isEmpty(below: height) } - mutating func clear(below height: UInt8) { + mutating func _clear(below height: UInt8) { _path.clear(below: height) } } diff --git a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift similarity index 88% rename from Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift rename to Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift index fff7f55c..8c9a90b9 100644 --- a/Sources/RopeModule/Rope/Conformances/_Rope+Sequence.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -extension _Rope: Sequence { +extension Rope: Sequence { public func makeIterator() -> Iterator { Iterator(self, from: self.startIndex) } @@ -19,14 +19,14 @@ extension _Rope: Sequence { } public struct Iterator: IteratorProtocol { - let rope: _Rope + let rope: Rope private(set) var index: Index - init(_ rope: _Rope, from start: Index) { + init(_ rope: Rope, from start: Index) { rope.validate(start) self.rope = rope self.index = start - self.rope.ensureLeaf(in: &index) + self.rope.grease(&index) } public mutating func next() -> Element? { diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Append.swift b/Sources/RopeModule/Rope/Operations/Rope+Append.swift similarity index 90% rename from Sources/RopeModule/Rope/Operations/_Rope+Append.swift rename to Sources/RopeModule/Rope/Operations/Rope+Append.swift index 9d00b0bb..cada001c 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Append.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Append.swift @@ -9,21 +9,21 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { public mutating func append(_ item: __owned Element) { - invalidateIndices() + _invalidateIndices() if _root == nil { - _root = .createLeaf(Item(item)) + _root = .createLeaf(_Item(item)) return } - if let spawn = root.append(Item(item)) { + if let spawn = root.append(_Item(item)) { _root = .createInner(children: root, spawn) } } } -extension _Rope.Node { - mutating func append(_ item: __owned Item) -> Self? { +extension Rope._Node { + mutating func append(_ item: __owned _Item) -> Self? { var item = item if item.isUndersized, !self.isEmpty, self.lastItem.rebalance(nextNeighbor: &item) { return nil diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Extract.swift b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift similarity index 89% rename from Sources/RopeModule/Rope/Operations/_Rope+Extract.swift rename to Sources/RopeModule/Rope/Operations/Rope+Extract.swift index 752291fe..414586f1 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Extract.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift @@ -9,8 +9,8 @@ // //===----------------------------------------------------------------------===// -extension _Rope { - public func extract(from start: Int, to end: Int, in metric: some _RopeMetric) -> Self { +extension Rope { + public func extract(from start: Int, to end: Int, in metric: some RopeMetric) -> Self { if _root == nil { precondition(start == 0 && end == 0, "Invalid range") return Self() @@ -21,12 +21,12 @@ extension _Rope { } } -extension _Rope.Node { +extension Rope._Node { func extract( from start: Int, to end: Int, - in metric: some _RopeMetric, - into builder: inout _Rope.Builder + in metric: some RopeMetric, + into builder: inout Rope.Builder ) { let size = metric.size(of: summary) precondition(start >= 0 && start <= end && end <= size, "Range out of bounds") @@ -46,19 +46,19 @@ extension _Rope.Node { at: u.remaining - metric._nonnegativeSize(of: item.summary), in: item2.value) _ = item2.split(at: j) - builder.append(item2) + builder._append(item2) return } assert(l.slot < u.slot) var left = c[l.slot] left = left.split(at: metric.index(at: l.remaining, in: left.value)) - builder.append(left) + builder._append(left) for i in l.slot + 1 ..< u.slot { - builder.append(c[i]) + builder._append(c[i]) } var right = c[u.slot] _ = right.split(at: metric.index(at: u.remaining, in: right.value)) - builder.append(right) + builder._append(right) } return } @@ -76,7 +76,7 @@ extension _Rope.Node { let lsize = metric._nonnegativeSize(of: c[l.slot].summary) c[l.slot].extract(from: l.remaining, to: lsize, in: metric, into: &builder) for i in l.slot + 1 ..< u.slot { - builder.append(c[i]) + builder._append(c[i]) } c[u.slot].extract(from: 0, to: u.remaining, in: metric, into: &builder) } diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift b/Sources/RopeModule/Rope/Operations/Rope+Find.swift similarity index 92% rename from Sources/RopeModule/Rope/Operations/_Rope+Find.swift rename to Sources/RopeModule/Rope/Operations/Rope+Find.swift index e763b2ee..6f97709e 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Find.swift @@ -9,10 +9,10 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { public func find( at position: Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, preferEnd: Bool ) -> (index: Index, remaining: Int) { let wholeSize = _root == nil ? 0 : metric.size(of: root.summary) @@ -22,7 +22,7 @@ extension _Rope { } var position = position var node = root - var path = Path(height: node.height) + var path = _Path(height: node.height) while node.height > 0 { node = node.readInner { let r = $0.findSlot(at: position, in: metric, preferEnd: preferEnd) @@ -38,10 +38,10 @@ extension _Rope { } } -extension _Rope.UnsafeHandle { +extension Rope._UnsafeHandle { func findSlot( at position: Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, preferEnd: Bool = true ) -> (slot: Int, remaining: Int) { var remaining = position @@ -62,7 +62,7 @@ extension _Rope.UnsafeHandle { func findSlot( from p: (slot: Int, remaining: Int), offsetBy distance: Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, preferEnd: Bool = true ) -> (slot: Int, remaining: Int) { assert(p.slot >= 0 && p.slot < childCount) diff --git a/Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift b/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift similarity index 94% rename from Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift rename to Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift index f0742ffb..69d2611e 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+ForEachWhile.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { public func forEachWhile( _ body: (Element) -> Bool ) -> Bool { @@ -19,7 +19,7 @@ extension _Rope { public func forEachWhile( from position: Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, _ body: (Element, Element.Index?) -> Bool ) -> Bool { guard _root != nil else { @@ -30,7 +30,7 @@ extension _Rope { } } -extension _Rope.Node { +extension Rope._Node { func forEachWhile( _ body: (Element) -> Bool ) -> Bool { @@ -54,7 +54,7 @@ extension _Rope.Node { func forEachWhile( from position: Int, - in metric: some _RopeMetric, + in metric: some RopeMetric, _ body: (Element, Element.Index?) -> Bool ) -> Bool { if isLeaf { diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift b/Sources/RopeModule/Rope/Operations/Rope+Insert.swift similarity index 87% rename from Sources/RopeModule/Rope/Operations/_Rope+Insert.swift rename to Sources/RopeModule/Rope/Operations/Rope+Insert.swift index d22d1a11..2a317df8 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Insert.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Insert.swift @@ -9,9 +9,9 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { public mutating func prepend(_ item: __owned Element) { - invalidateIndices() + _invalidateIndices() insert(item, at: startIndex) } @@ -25,42 +25,42 @@ extension _Rope { mutating func insert( _ item: __owned Element, - at path: Path + at path: _Path ) { - if path == endPath { + if path == _endPath { append(item) return } - if let spawn = root.insert(Item(item), at: path) { + if let spawn = root.insert(_Item(item), at: path) { _root = .createInner(children: root, spawn) } - invalidateIndices() + _invalidateIndices() } public mutating func insert( _ item: __owned Element, at position: Int, - in metric: some _RopeMetric + in metric: some RopeMetric ) { if position == metric.size(of: summary) { append(item) return } - if let spawn = root.insert(Item(item), at: position, in: metric) { + if let spawn = root.insert(_Item(item), at: position, in: metric) { _root = .createInner(children: root, spawn) } - invalidateIndices() + _invalidateIndices() } } -extension _Rope.Node { - mutating func prepend(_ item: __owned Item) -> Self? { - insert(item, at: startPath) +extension Rope._Node { + mutating func prepend(_ item: __owned _Item) -> Self? { + insert(item, at: _startPath) } mutating func insert( - _ item: __owned Item, - at path: Path + _ item: __owned _Item, + at path: _Path ) -> Self? { ensureUnique() let h = height @@ -74,9 +74,9 @@ extension _Rope.Node { } mutating func insert( - _ item: __owned Item, + _ item: __owned _Item, at position: Int, - in metric: some _RopeMetric + in metric: some RopeMetric ) -> Self? { ensureUnique() if height > 0 { @@ -93,7 +93,7 @@ extension _Rope.Node { } } -extension _Rope.Node { +extension Rope._Node { mutating func _innerInsert( at slot: Int, with body: (inout Self) -> Self? @@ -159,8 +159,8 @@ extension _Rope.Node { } } -extension _Rope.Node { - mutating func _leafInsert(_ item: __owned Item, at slot: Int) -> Self? { +extension Rope._Node { + mutating func _leafInsert(_ item: __owned _Item, at slot: Int) -> Self? { assert(slot <= childCount) var item = item if item.isUndersized, childCount > 0, _rebalanceBeforeInsert(&item, at: slot) { @@ -180,7 +180,7 @@ extension _Rope.Node { return spawn } - mutating func _rebalanceBeforeInsert(_ item: inout Item, at slot: Int) -> Bool { + mutating func _rebalanceBeforeInsert(_ item: inout _Item, at slot: Int) -> Bool { assert(item.isUndersized) let r = updateLeaf { (h) -> (merged: Bool, delta: Summary) in if slot > 0 { diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Join.swift b/Sources/RopeModule/Rope/Operations/Rope+Join.swift similarity index 91% rename from Sources/RopeModule/Rope/Operations/_Rope+Join.swift rename to Sources/RopeModule/Rope/Operations/Rope+Join.swift index e5451cf1..c73a2cbf 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Join.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Join.swift @@ -9,20 +9,20 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { public mutating func append(_ other: __owned Self) { - self = _Rope.join(self, other) + self = Rope.join(self, other) } public mutating func prepend(_ other: __owned Self) { - self = _Rope.join(other, self) + self = Rope.join(other, self) } - mutating func append(_ other: __owned Node) { + mutating func _append(_ other: __owned _Node) { append(Self(root: other)) } - mutating func prepend(_ other: __owned Node) { + mutating func _prepend(_ other: __owned _Node) { prepend(Self(root: other)) } @@ -41,19 +41,19 @@ extension _Rope { let r = left._graftBack(&right) guard let remainder = r.remainder else { return Self(root: left) } assert(left.height == remainder.height) - let root = Node.createInner(children: left, remainder) + let root = _Node.createInner(children: left, remainder) return Self(root: root) } let r = right._graftFront(&left) guard let remainder = r.remainder else { return Self(root: right) } assert(right.height == remainder.height) - let root = Node.createInner(children: remainder, right) + let root = _Node.createInner(children: remainder, right) return Self(root: root) } } -extension _Rope.Node { +extension Rope._Node { mutating func _graftFront(_ scion: inout Self) -> (remainder: Self?, delta: Summary) { assert(self.height >= scion.height) guard self.height > scion.height else { diff --git a/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift b/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift similarity index 97% rename from Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift rename to Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift index 92c20cfb..bd1e5740 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+MutatingForEach.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { @inline(__always) @discardableResult public mutating func mutatingForEach( @@ -41,7 +41,7 @@ extension _Rope { validate(index) guard _root != nil else { return true } defer { - invalidateIndices() + _invalidateIndices() index._version = _version } let r = root.mutatingForEach(from: &index, body: body).continue @@ -49,7 +49,7 @@ extension _Rope { } } -extension _Rope.Node { +extension Rope._Node { mutating func mutatingForEach( from index: inout Index, body: (inout Element) -> Bool diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift similarity index 90% rename from Sources/RopeModule/Rope/Operations/_Rope+Remove.swift rename to Sources/RopeModule/Rope/Operations/Rope+Remove.swift index a2136c0b..f29aa6f8 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Remove.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { public mutating func remove(at index: Index) -> Element { validate(index) let old = root.remove(at: index._path).removed @@ -18,15 +18,15 @@ extension _Rope { } else if root.childCount == 1, root.height > 0 { root = root.readInner { $0.children.first! } } - invalidateIndices() + _invalidateIndices() return old.value } } -extension _Rope.Node { +extension Rope._Node { mutating func remove( - at path: Path - ) -> (removed: Item, delta: Summary, needsFixing: Bool) { + at path: _Path + ) -> (removed: _Item, delta: Summary, needsFixing: Bool) { ensureUnique() let slot = path[height] precondition(slot < childCount, "Invalid index") @@ -43,12 +43,12 @@ extension _Rope.Node { } } -extension _Rope { +extension Rope { mutating func remove( at position: Int, - in metric: some _RopeMetric + in metric: some RopeMetric ) -> Element { - invalidateIndices() + _invalidateIndices() let old = root.remove(at: position, in: metric).removed if root.isEmpty { _root = nil @@ -59,11 +59,11 @@ extension _Rope { } } -extension _Rope.Node { +extension Rope._Node { mutating func remove( at position: Int, - in metric: some _RopeMetric - ) -> (removed: Item, delta: Summary, needsFixing: Bool) { + in metric: some RopeMetric + ) -> (removed: _Item, delta: Summary, needsFixing: Bool) { ensureUnique() guard height > 0 else { let (slot, remaining) = readLeaf { @@ -85,7 +85,7 @@ extension _Rope.Node { } } -extension _Rope.Node { +extension Rope._Node { mutating func fixDeficiency(at slot: Int) { assert(isUnique()) updateInner { diff --git a/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift similarity index 85% rename from Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift rename to Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift index 4a86b18b..f80d0193 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+RemoveSubrange.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift @@ -9,12 +9,12 @@ // //===----------------------------------------------------------------------===// -extension _Rope { +extension Rope { public mutating func removeSubrange( _ bounds: Range, - in metric: some _RopeMetric + in metric: some RopeMetric ) { - invalidateIndices() + _invalidateIndices() precondition( bounds.lowerBound >= 0 && bounds.upperBound <= count(in: metric), "Position out of bounds") @@ -26,13 +26,13 @@ extension _Rope { public mutating func replaceSubrange( _ bounds: Range, - in metric: some _RopeMetric, + in metric: some RopeMetric, with newElements: __owned some Collection ) { // FIXME: Implement insert(contentsOf:at:in:) and dispatch to it when bounds.isEmpty. // FIXME: Add fast path for replacing tiny ranges with tiny data. // FIXME: Add special cases if newElements is itself a _Rope etc. - invalidateIndices() + _invalidateIndices() var builder = builder(removing: bounds, in: metric) for item in newElements { builder.append(item) @@ -40,11 +40,11 @@ extension _Rope { self = builder.finalize() } - mutating func builder( + public mutating func builder( removing bounds: Range, - in metric: some _RopeMetric + in metric: some RopeMetric ) -> Builder { - invalidateIndices() + _invalidateIndices() let size = metric.size(of: summary) precondition( bounds.lowerBound >= 0 && bounds.upperBound <= size, @@ -87,28 +87,28 @@ extension _Rope { assert(l.slot == u.slot) var item = node._leafSplit(at: l.slot, into: &builder) let i2 = metric.index(at: u.remaining, in: item.value) - builder.prependSuffix(Item(item.value.split(at: i2))) + builder._prependSuffix(item.split(at: i2)) let i1 = metric.index(at: l.remaining, in: item.value) _ = item.split(at: i1) - builder.append(item.value) + builder._append(item) return builder } } -extension _Rope.Node { +extension Rope._Node { __consuming func _removeSubrange( from start: (slot: Int, remaining: Int), to end: (slot: Int, remaining: Int), - in metric: some _RopeMetric, - into builder: inout _Rope.Builder + in metric: some RopeMetric, + into builder: inout Rope.Builder ) { assert(start.slot >= 0 && start.slot < end.slot && end.slot < childCount) assert(start.remaining >= 0) assert(end.remaining >= 0) - builder.append(slots: 0 ..< start.slot, in: self) + builder._append(slots: 0 ..< start.slot, in: self) if end.slot < childCount { - builder.prependSuffix(slots: end.slot + 1 ..< childCount, in: self) + builder._prependSuffix(slots: end.slot + 1 ..< childCount, in: self) } guard isLeaf else { @@ -126,14 +126,14 @@ extension _Rope.Node { let i1 = metric.index(at: start.remaining, in: lower.value) let i2 = metric.index(at: end.remaining, in: upper.value) _ = lower.split(at: i1) - builder.append(lower) - builder.prependSuffix(upper.split(at: i2)) + builder._append(lower) + builder._prependSuffix(upper.split(at: i2)) } __consuming func removeSuffix( from position: Int, - in metric: some _RopeMetric, - into builder: inout _Rope.Builder + in metric: some RopeMetric, + into builder: inout Rope.Builder ) { var node = self @@ -141,7 +141,7 @@ extension _Rope.Node { while true { guard position > 0 else { return } guard position < metric.size(of: node.summary) else { - builder.append(node) + builder._append(node) return } @@ -155,19 +155,19 @@ extension _Rope.Node { var item = node._leafRemoveSuffix(returning: r.slot, into: &builder) let i = metric.index(at: r.remaining, in: item.value) _ = item.split(at: i) - builder.append(item) + builder._append(item) } __consuming func removePrefix( upTo position: Int, - in metric: some _RopeMetric, - into builder: inout _Rope.Builder + in metric: some RopeMetric, + into builder: inout Rope.Builder ) { var node = self var position = position while true { guard position > 0 else { - builder.prependSuffix(node) + builder._prependSuffix(node) return } guard position < metric.size(of: node.summary) else { return } @@ -181,12 +181,12 @@ extension _Rope.Node { let r = node.readLeaf { $0.findSlot(at: position, in: metric) } var item = node._leafRemovePrefix(returning: r.slot, into: &builder) let i = metric.index(at: r.remaining, in: item.value) - builder.prependSuffix(item.split(at: i)) + builder._prependSuffix(item.split(at: i)) } mutating func _innerRemoveSuffix( descending slot: Int, - into builder: inout _Rope.Builder + into builder: inout Rope.Builder ) { assert(!self.isLeaf) assert(slot >= 0 && slot <= childCount) @@ -200,7 +200,7 @@ extension _Rope.Node { let c = $0.children return (c[0], c[1]) } - builder.append(remaining) + builder._append(remaining) self = new return } @@ -213,13 +213,13 @@ extension _Rope.Node { var n = _removeNode(at: slot) swap(&self, &n) assert(n.childCount > 1) - builder.append(n) + builder._append(n) } __consuming func _leafRemoveSuffix( returning slot: Int, - into builder: inout _Rope.Builder - ) -> Item { + into builder: inout Rope.Builder + ) -> _Item { assert(self.isLeaf) assert(slot >= 0 && slot < childCount) @@ -231,7 +231,7 @@ extension _Rope.Node { let c = $0.children return (c[0], c[1]) } - builder.append(remaining) + builder._append(remaining) return new } @@ -242,13 +242,13 @@ extension _Rope.Node { n.summary.subtract(delta) } let item = n._removeItem(at: slot).removed - builder.append(n) + builder._append(n) return item } mutating func _innerRemovePrefix( descending slot: Int, - into builder: inout _Rope.Builder + into builder: inout Rope.Builder ) { assert(!self.isLeaf) assert(slot >= 0 && slot < childCount) @@ -262,7 +262,7 @@ extension _Rope.Node { let c = $0.children return (c[$0.childCount - 2], c[$0.childCount - 1]) } - builder.prependSuffix(remaining) + builder._prependSuffix(remaining) self = new return } @@ -276,13 +276,13 @@ extension _Rope.Node { self.summary.subtract(delta) assert(self.childCount > 1) swap(&self, &n) - builder.prependSuffix(n) + builder._prependSuffix(n) } __consuming func _leafRemovePrefix( returning slot: Int, - into builder: inout _Rope.Builder - ) -> Item { + into builder: inout Rope.Builder + ) -> _Item { assert(self.isLeaf) assert(slot >= 0 && slot <= childCount) @@ -294,7 +294,7 @@ extension _Rope.Node { let c = $0.children return (c[$0.childCount - 2], c[$0.childCount - 1]) } - builder.prependSuffix(remaining) + builder._prependSuffix(remaining) return new } @@ -307,7 +307,7 @@ extension _Rope.Node { } n.summary.subtract(delta) assert(n.childCount > 1) - builder.prependSuffix(n) + builder._prependSuffix(n) return item } } diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Split.swift b/Sources/RopeModule/Rope/Operations/Rope+Split.swift similarity index 76% rename from Sources/RopeModule/Rope/Operations/_Rope+Split.swift rename to Sources/RopeModule/Rope/Operations/Rope+Split.swift index ae270c90..28deaa78 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Split.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Split.swift @@ -9,12 +9,12 @@ // //===----------------------------------------------------------------------===// -extension _Rope { - mutating func builder( +extension Rope { + public mutating func builder( splittingAt position: Int, - in metric: some _RopeMetric + in metric: some RopeMetric ) -> Builder { - invalidateIndices() + _invalidateIndices() var builder = Builder() var position = position @@ -30,12 +30,12 @@ extension _Rope { var item = node._leafSplit(at: r.slot, into: &builder) let index = metric.index(at: r.remaining, in: item.value) let suffix = item.split(at: index) - builder.prependSuffix(suffix) + builder._prependSuffix(suffix) builder.append(item.value) return builder } - mutating func split(at index: Index) -> (builder: Builder, item: Element) { + public mutating func split(at index: Index) -> (builder: Builder, item: Element) { validate(index) precondition(index < endIndex) var builder = Builder() @@ -51,15 +51,15 @@ extension _Rope { let slot = index._path[node.height] precondition(slot < node.childCount, "Index out of bounds") let item = node._leafSplit(at: slot, into: &builder) - invalidateIndices() + _invalidateIndices() return (builder, item.value) } - mutating func split(at ropeIndex: Index, _ itemIndex: Element.Index) -> Builder { + public mutating func split(at ropeIndex: Index, _ itemIndex: Element.Index) -> Builder { var (builder, item) = self.split(at: ropeIndex) let suffix = item.split(at: itemIndex) if !suffix.isEmpty { - builder.prependSuffix(_Rope.Item(suffix)) + builder.prependSuffix(suffix) } if !item.isEmpty { builder.append(item) @@ -68,10 +68,10 @@ extension _Rope { } } -extension _Rope.Node { +extension Rope._Node { mutating func _innerSplit( at slot: Int, - into builder: inout _Rope.Builder + into builder: inout Rope.Builder ) { assert(!self.isLeaf) assert(slot >= 0 && slot < childCount) @@ -79,10 +79,10 @@ extension _Rope.Node { var slot = slot if slot == childCount - 2 { - builder.prependSuffix(_removeNode(at: childCount - 1)) + builder._prependSuffix(_removeNode(at: childCount - 1)) } if slot == 1 { - builder.append(_removeNode(at: 0)) + builder._append(_removeNode(at: 0)) slot -= 1 } @@ -91,22 +91,22 @@ extension _Rope.Node { guard n.childCount > 0 else { return } if slot == 0 { - builder.prependSuffix(n) + builder._prependSuffix(n) return } if slot == n.childCount { - builder.append(n) + builder._append(n) return } let suffix = n.split(keeping: slot) - builder.append(n) - builder.prependSuffix(suffix) + builder._append(n) + builder._prependSuffix(suffix) } __consuming func _leafSplit( at slot: Int, - into builder: inout _Rope.Builder - ) -> Item { + into builder: inout Rope.Builder + ) -> _Item { var n = self n.ensureUnique() @@ -115,7 +115,7 @@ extension _Rope.Node { var slot = slot if slot == n.childCount - 2 { - builder.prependSuffix(n._removeItem(at: childCount - 1).removed) + builder._prependSuffix(n._removeItem(at: childCount - 1).removed) } if slot == 1 { builder.append(n._removeItem(at: 0).removed.value) @@ -126,13 +126,13 @@ extension _Rope.Node { guard n.childCount > 0 else { return item } if slot == 0 { - builder.prependSuffix(n) + builder._prependSuffix(n) } else if slot == n.childCount { - builder.append(n) + builder._append(n) } else { let suffix = n.split(keeping: slot) - builder.append(n) - builder.prependSuffix(suffix) + builder._append(n) + builder._prependSuffix(suffix) } return item } diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index d3ffbfc5..16ce8d25 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -13,11 +13,11 @@ @testable import _RopeModule import XCTest -struct Chunk: _RopeElement, Equatable, CustomStringConvertible { +struct Chunk: RopeElement, Equatable, CustomStringConvertible { var length: Int var value: Int - struct Summary: _RopeSummary, Comparable { + struct Summary: RopeSummary, Comparable { var length: Int init(_ length: Int) { @@ -43,7 +43,7 @@ struct Chunk: _RopeElement, Equatable, CustomStringConvertible { static var nodeSizeBitWidth: Int { 3 } } - struct Metric: _RopeMetric { + struct Metric: RopeMetric { typealias Element = Chunk func size(of summary: Chunk.Summary) -> Int { @@ -116,8 +116,8 @@ class TestRope: XCTestCase { } func test_empty() { - let empty = _Rope() - empty.invariantCheck() + let empty = Rope() + empty._invariantCheck() XCTAssertTrue(empty.isEmpty) XCTAssertEqual(empty.count, 0) XCTAssertTrue(empty.summary.isZero) @@ -130,18 +130,18 @@ class TestRope: XCTestCase { let ref = (0 ..< c).map { Chunk(length: ($0 % 4) + 1, value: $0) } - var builder = _Rope.Builder() + var builder = Rope.Builder() for chunk in ref { builder.append(chunk) - builder.invariantCheck() + builder._invariantCheck() } - let _rope = builder.finalize() + let rope = builder.finalize() - let actualSum = _rope.summary + let actualSum = rope.summary let expectedSum: Chunk.Summary = ref.reduce(into: .zero) { $0.add($1.summary) } XCTAssertEqual(actualSum, expectedSum) - XCTAssertTrue(_rope.elementsEqual(ref)) + XCTAssertTrue(rope.elementsEqual(ref)) } func test_iteration() { @@ -149,9 +149,9 @@ class TestRope: XCTestCase { let ref = (0 ..< c).map { Chunk(length: ($0 % 4) + 1, value: $0) } - let _rope = _Rope(ref) + let rope = Rope(ref) - var it = _rope.makeIterator() + var it = rope.makeIterator() var i = 0 while let next = it.next() { let expected = ref[i] @@ -162,7 +162,7 @@ class TestRope: XCTestCase { XCTAssertEqual(i, ref.count) let expectedLength = ref.reduce(into: 0) { $0 += $1.length } - let actualLength = _rope.reduce(into: 0) { $0 += $1.length } + let actualLength = rope.reduce(into: 0) { $0 += $1.length } XCTAssertEqual(actualLength, expectedLength) } } @@ -172,17 +172,17 @@ class TestRope: XCTestCase { let ref = (0 ..< c).map { Chunk(length: ($0 % 4) + 1, value: $0) } - let _rope = _Rope(ref) - XCTAssertTrue(_rope.elementsEqual(ref)) + let rope = Rope(ref) + XCTAssertTrue(rope.elementsEqual(ref)) - var i = _rope.startIndex + var i = rope.startIndex var j = 0 - while i != _rope.endIndex, j != ref.count { - XCTAssertEqual(_rope[i], ref[j]) - i = _rope.index(after: i) + while i != rope.endIndex, j != ref.count { + XCTAssertEqual(rope[i], ref[j]) + i = rope.index(after: i) j += 1 } - XCTAssertEqual(i, _rope.endIndex) + XCTAssertEqual(i, rope.endIndex) XCTAssertEqual(j, ref.count) } } @@ -192,18 +192,18 @@ class TestRope: XCTestCase { let ref = (0 ..< c).map { Chunk(length: ($0 % 4) + 1, value: $0) } - let _rope = _Rope(ref) - XCTAssertTrue(_rope.elementsEqual(ref)) + let rope = Rope(ref) + XCTAssertTrue(rope.elementsEqual(ref)) - var indices: [_Rope.Index] = [] - var i = _rope.startIndex - while i != _rope.endIndex { + var indices: [Rope.Index] = [] + var i = rope.startIndex + while i != rope.endIndex { indices.append(i) - i = _rope.index(after: i) + i = rope.index(after: i) } while let j = indices.popLast() { - i = _rope.index(before: i) + i = rope.index(before: i) XCTAssertEqual(i, j) } } @@ -215,13 +215,13 @@ class TestRope: XCTestCase { let ref = (0 ..< c).map { Chunk(length: ($0 % 4) + 1, value: $0) } - let _rope = _Rope(ref) + let rope = Rope(ref) - let indices = Array(_rope.indices) + [_rope.endIndex] + let indices = Array(rope.indices) + [rope.endIndex] XCTAssertEqual(indices.count, c + 1) for i in indices.indices { for j in indices.indices { - let d = _rope.distance(from: indices[i], to: indices[j], in: Chunk.Metric()) + let d = rope.distance(from: indices[i], to: indices[j], in: Chunk.Metric()) let r = ( i <= j ? ref[i..(ref) + let rope = Rope(ref) - let indices = Array(_rope.indices) + [_rope.endIndex] + let indices = Array(rope.indices) + [rope.endIndex] XCTAssertEqual(indices.count, c + 1) for i in indices.indices { for j in indices.indices { @@ -247,7 +247,7 @@ class TestRope: XCTestCase { i <= j ? ref[i..() + var rope = Rope() var ref: [Chunk] = [] for i in 0 ..< c { let chunk = Chunk(length: (i % 4) + 1, value: i) ref.append(chunk) - _rope.append(chunk) - _rope.invariantCheck() + rope.append(chunk) + rope._invariantCheck() } - let actualSum = _rope.summary + let actualSum = rope.summary let expectedSum: Chunk.Summary = ref.reduce(into: .zero) { $0.add($1.summary) } XCTAssertEqual(actualSum, expectedSum) - XCTAssertTrue(_rope.elementsEqual(ref)) + XCTAssertTrue(rope.elementsEqual(ref)) } func test_prepend_item() { @@ -280,17 +280,17 @@ class TestRope: XCTestCase { Chunk(length: ($0 % 4) + 1, value: $0) } - var _rope = _Rope() + var rope = Rope() for chunk in ref.reversed() { - _rope.insert(chunk, at: 0, in: Chunk.Metric()) - _rope.invariantCheck() + rope.insert(chunk, at: 0, in: Chunk.Metric()) + rope._invariantCheck() } - let actualSum = _rope.summary + let actualSum = rope.summary let expectedSum: Chunk.Summary = ref.reduce(into: .zero) { $0.add($1.summary) } XCTAssertEqual(actualSum, expectedSum) - XCTAssertTrue(_rope.elementsEqual(ref)) + XCTAssertTrue(rope.elementsEqual(ref)) } func test_insert_item() { @@ -302,21 +302,21 @@ class TestRope: XCTestCase { var rng = RepeatableRandomNumberGenerator(seed: 0) let input = ref.shuffled(using: &rng) - var _rope = _Rope() + var rope = Rope() for i in input.indices { let chunk = input[i] let position = input[..(ref) + var rope = Rope(ref) var rng = RepeatableRandomNumberGenerator(seed: 0) let input = ref.shuffled(using: &rng) @@ -335,13 +335,13 @@ class TestRope: XCTestCase { let offset = input[i...].reduce(into: 0) { $0 += $1.value < chunk.value ? 1 : 0 } - let index = _rope.index(_rope.startIndex, offsetBy: offset) - let removed = _rope.remove(at: index) + let index = rope.index(rope.startIndex, offsetBy: offset) + let removed = rope.remove(at: index) XCTAssertEqual(removed, chunk) - _rope.invariantCheck() + rope._invariantCheck() } - XCTAssertTrue(_rope.isEmpty) - XCTAssertEqual(_rope.summary, .zero) + XCTAssertTrue(rope.isEmpty) + XCTAssertEqual(rope.summary, .zero) } func test_remove_at_position() { @@ -350,7 +350,7 @@ class TestRope: XCTestCase { Chunk(length: ($0 % 4) + 1, value: $0) } - var _rope = _Rope(ref) + var rope = Rope(ref) var rng = RepeatableRandomNumberGenerator(seed: 0) let input = ref.shuffled(using: &rng) @@ -360,19 +360,19 @@ class TestRope: XCTestCase { let position = input[i...].reduce(into: 0) { $0 += $1.value < chunk.value ? $1.length : 0 } - let removed = _rope.remove(at: position, in: Chunk.Metric()) + let removed = rope.remove(at: position, in: Chunk.Metric()) XCTAssertEqual(removed, chunk) - _rope.invariantCheck() + rope._invariantCheck() } - XCTAssertTrue(_rope.isEmpty) - XCTAssertEqual(_rope.summary, .zero) + XCTAssertTrue(rope.isEmpty) + XCTAssertEqual(rope.summary, .zero) } func test_join() { let c = 100_000 var trees = (0 ..< c).map { let chunk = Chunk(length: ($0 % 4) + 1, value: $0) - return _Rope(CollectionOfOne(chunk)) + return Rope(CollectionOfOne(chunk)) } var ranges = (0 ..< c).map { $0 ..< $0 + 1 } @@ -383,10 +383,10 @@ class TestRope: XCTestCase { let a = trees[i] let b = trees.remove(at: i + 1) - trees[i] = _Rope() + trees[i] = Rope() - let joined = _Rope.join(a, b) - joined.invariantCheck() + let joined = Rope.join(a, b) + joined._invariantCheck() let actualValues = joined.map { $0.value } XCTAssertEqual(actualValues, Array(expectedRange)) trees[i] = joined @@ -415,7 +415,7 @@ class TestRope: XCTestCase { } func checkEqual( - _ x: _Rope, + _ x: Rope, _ y: [Int], file: StaticString = #file, line: UInt = #line @@ -426,7 +426,7 @@ class TestRope: XCTestCase { } func checkRemoveSubrange( - _ a: _Rope, + _ a: Rope, _ b: [Int], range: Range, file: StaticString = #file, @@ -441,91 +441,91 @@ class TestRope: XCTestCase { } func test_removeSubrange_simple() { - var _rope = _Rope() + var rope = Rope() for i in 0 ..< 10 { - _rope.append(Chunk(length: 10, value: i)) + rope.append(Chunk(length: 10, value: i)) } let ref = (0 ..< 10).flatMap { Array(repeating: $0, count: 10) } // Basics - checkRemoveSubrange(_rope, ref, range: 0 ..< 0) - checkRemoveSubrange(_rope, ref, range: 30 ..< 30) - checkRemoveSubrange(_rope, ref, range: 0 ..< 100) + checkRemoveSubrange(rope, ref, range: 0 ..< 0) + checkRemoveSubrange(rope, ref, range: 30 ..< 30) + checkRemoveSubrange(rope, ref, range: 0 ..< 100) // Whole individual chunks - checkRemoveSubrange(_rope, ref, range: 90 ..< 100) - checkRemoveSubrange(_rope, ref, range: 0 ..< 10) - checkRemoveSubrange(_rope, ref, range: 30 ..< 40) - checkRemoveSubrange(_rope, ref, range: 70 ..< 80) + checkRemoveSubrange(rope, ref, range: 90 ..< 100) + checkRemoveSubrange(rope, ref, range: 0 ..< 10) + checkRemoveSubrange(rope, ref, range: 30 ..< 40) + checkRemoveSubrange(rope, ref, range: 70 ..< 80) // Prefixes of single chunks - checkRemoveSubrange(_rope, ref, range: 0 ..< 1) - checkRemoveSubrange(_rope, ref, range: 30 ..< 35) - checkRemoveSubrange(_rope, ref, range: 60 ..< 66) - checkRemoveSubrange(_rope, ref, range: 90 ..< 98) + checkRemoveSubrange(rope, ref, range: 0 ..< 1) + checkRemoveSubrange(rope, ref, range: 30 ..< 35) + checkRemoveSubrange(rope, ref, range: 60 ..< 66) + checkRemoveSubrange(rope, ref, range: 90 ..< 98) // Suffixes of single chunks - checkRemoveSubrange(_rope, ref, range: 9 ..< 10) - checkRemoveSubrange(_rope, ref, range: 35 ..< 40) - checkRemoveSubrange(_rope, ref, range: 64 ..< 70) - checkRemoveSubrange(_rope, ref, range: 98 ..< 100) + checkRemoveSubrange(rope, ref, range: 9 ..< 10) + checkRemoveSubrange(rope, ref, range: 35 ..< 40) + checkRemoveSubrange(rope, ref, range: 64 ..< 70) + checkRemoveSubrange(rope, ref, range: 98 ..< 100) // Neighboring couple of whole chunks - checkRemoveSubrange(_rope, ref, range: 0 ..< 20) - checkRemoveSubrange(_rope, ref, range: 80 ..< 100) - checkRemoveSubrange(_rope, ref, range: 10 ..< 30) - checkRemoveSubrange(_rope, ref, range: 50 ..< 70) // Crosses nodes! + checkRemoveSubrange(rope, ref, range: 0 ..< 20) + checkRemoveSubrange(rope, ref, range: 80 ..< 100) + checkRemoveSubrange(rope, ref, range: 10 ..< 30) + checkRemoveSubrange(rope, ref, range: 50 ..< 70) // Crosses nodes! // Longer whole chunk sequences - checkRemoveSubrange(_rope, ref, range: 0 ..< 30) - checkRemoveSubrange(_rope, ref, range: 70 ..< 90) - checkRemoveSubrange(_rope, ref, range: 0 ..< 60) // entire first node - checkRemoveSubrange(_rope, ref, range: 60 ..< 100) // entire second node - checkRemoveSubrange(_rope, ref, range: 40 ..< 70) // crosses into second node - checkRemoveSubrange(_rope, ref, range: 10 ..< 90) // crosses into second node + checkRemoveSubrange(rope, ref, range: 0 ..< 30) + checkRemoveSubrange(rope, ref, range: 70 ..< 90) + checkRemoveSubrange(rope, ref, range: 0 ..< 60) // entire first node + checkRemoveSubrange(rope, ref, range: 60 ..< 100) // entire second node + checkRemoveSubrange(rope, ref, range: 40 ..< 70) // crosses into second node + checkRemoveSubrange(rope, ref, range: 10 ..< 90) // crosses into second node // Arbitrary cuts - checkRemoveSubrange(_rope, ref, range: 0 ..< 69) - checkRemoveSubrange(_rope, ref, range: 42 ..< 73) - checkRemoveSubrange(_rope, ref, range: 21 ..< 89) - checkRemoveSubrange(_rope, ref, range: 1 ..< 99) - checkRemoveSubrange(_rope, ref, range: 1 ..< 59) - checkRemoveSubrange(_rope, ref, range: 61 ..< 99) + checkRemoveSubrange(rope, ref, range: 0 ..< 69) + checkRemoveSubrange(rope, ref, range: 42 ..< 73) + checkRemoveSubrange(rope, ref, range: 21 ..< 89) + checkRemoveSubrange(rope, ref, range: 1 ..< 99) + checkRemoveSubrange(rope, ref, range: 1 ..< 59) + checkRemoveSubrange(rope, ref, range: 61 ..< 99) } func test_removeSubrange_larger() { - var _rope = _Rope() + var rope = Rope() for i in 0 ..< 100 { - _rope.append(Chunk(length: 10, value: i)) + rope.append(Chunk(length: 10, value: i)) } let ref = (0 ..< 100).flatMap { Array(repeating: $0, count: 10) } - checkRemoveSubrange(_rope, ref, range: 0 ..< 0) - checkRemoveSubrange(_rope, ref, range: 0 ..< 1000) - checkRemoveSubrange(_rope, ref, range: 0 ..< 100) - checkRemoveSubrange(_rope, ref, range: 900 ..< 1000) - checkRemoveSubrange(_rope, ref, range: 120 ..< 330) - checkRemoveSubrange(_rope, ref, range: 734 ..< 894) - checkRemoveSubrange(_rope, ref, range: 183 ..< 892) + checkRemoveSubrange(rope, ref, range: 0 ..< 0) + checkRemoveSubrange(rope, ref, range: 0 ..< 1000) + checkRemoveSubrange(rope, ref, range: 0 ..< 100) + checkRemoveSubrange(rope, ref, range: 900 ..< 1000) + checkRemoveSubrange(rope, ref, range: 120 ..< 330) + checkRemoveSubrange(rope, ref, range: 734 ..< 894) + checkRemoveSubrange(rope, ref, range: 183 ..< 892) - checkRemoveSubrange(_rope, ref, range: 181 ..< 479) - checkRemoveSubrange(_rope, ref, range: 191 ..< 469) - checkRemoveSubrange(_rope, ref, range: 2 ..< 722) - checkRemoveSubrange(_rope, ref, range: 358 ..< 718) - checkRemoveSubrange(_rope, ref, range: 12 ..< 732) - checkRemoveSubrange(_rope, ref, range: 348 ..< 728) - checkRemoveSubrange(_rope, ref, range: 63 ..< 783) - checkRemoveSubrange(_rope, ref, range: 297 ..< 655) + checkRemoveSubrange(rope, ref, range: 181 ..< 479) + checkRemoveSubrange(rope, ref, range: 191 ..< 469) + checkRemoveSubrange(rope, ref, range: 2 ..< 722) + checkRemoveSubrange(rope, ref, range: 358 ..< 718) + checkRemoveSubrange(rope, ref, range: 12 ..< 732) + checkRemoveSubrange(rope, ref, range: 348 ..< 728) + checkRemoveSubrange(rope, ref, range: 63 ..< 783) + checkRemoveSubrange(rope, ref, range: 297 ..< 655) } func test_removeSubrange_random() { for iteration in 0 ..< 20 { var rng = RepeatableRandomNumberGenerator(seed: iteration) let c = 1000 - var _rope = _Rope() + var rope = Rope() for i in 0 ..< c { - _rope.append(Chunk(length: 2, value: i)) + rope.append(Chunk(length: 2, value: i)) } var ref = (0 ..< c).flatMap { Array(repeating: $0, count: 2) } @@ -533,9 +533,9 @@ class TestRope: XCTestCase { print(ref.count) let i = (0 ..< ref.count).randomElement(using: &rng)! let j = (i + 1 ... ref.count).randomElement(using: &rng)! - _rope.removeSubrange(i ..< j, in: Chunk.Metric()) + rope.removeSubrange(i ..< j, in: Chunk.Metric()) ref.removeSubrange(i ..< j) - checkEqual(_rope, ref) + checkEqual(rope, ref) } } } From 88286b661d30291e827f8842b68aabe163083820 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 00:35:08 -0700 Subject: [PATCH 074/113] BigString: Fix Issue in utf16.distance when endpoint is on the trailing surrogate of the first scalar in a chunk --- .../BigString/Basics/BigString+Contents.swift | 5 +++-- .../BigString/Basics/BigString+Index.swift | 16 +++++++++++++--- Tests/RopeModuleTests/TestBString.swift | 3 +-- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift index 8a82ba92..1786ce85 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift @@ -51,8 +51,9 @@ extension BigString { precondition(start <= endIndex && end <= endIndex, "Invalid index") guard start != end else { return 0 } assert(!isEmpty) - let a = resolve(Swift.min(start, end), preferEnd: false) - let b = resolve(Swift.max(start, end), preferEnd: true) + let (lesser, greater) = (start <= end ? (start, end) : (end, start)) + let a = resolve(lesser, preferEnd: false) + let b = resolve(greater, preferEnd: true) var d = 0 let ropeIndexA = a._rope! diff --git a/Sources/RopeModule/BigString/Basics/BigString+Index.swift b/Sources/RopeModule/BigString/Basics/BigString+Index.swift index fd169a41..d8291b9d 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Index.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Index.swift @@ -212,7 +212,9 @@ extension BigString { func resolve(_ i: Index, preferEnd: Bool) -> Index { if var ri = i._rope, _rope.isValid(ri) { if preferEnd { - guard i.utf8Offset > 0, i._utf8ChunkOffset == 0 else { return i } + guard i.utf8Offset > 0, i._utf8ChunkOffset == 0, !i._isUTF16TrailingSurrogate else { + return i + } _rope.formIndex(before: &ri) let length = _rope[ri].utf8Count let ci = String.Index(_utf8Offset: length) @@ -230,10 +232,18 @@ extension BigString { return j } + // Indices addressing trailing surrogates must never be resolved at the end of chunk, + // because the +1 doesn't make sense on any endIndex. + let trailingSurrogate = i._isUTF16TrailingSurrogate + let (ri, chunkOffset) = _rope.find( - at: i.utf8Offset, in: _UTF8Metric(), preferEnd: preferEnd) + at: i.utf8Offset, + in: _UTF8Metric(), + preferEnd: preferEnd && !trailingSurrogate) + let ci = String.Index( - _utf8Offset: chunkOffset, utf16TrailingSurrogate: i._isUTF16TrailingSurrogate) + _utf8Offset: chunkOffset, + utf16TrailingSurrogate: trailingSurrogate) return Index(baseUTF8Offset: i.utf8Offset - ci._utf8Offset, _rope: ri, chunk: ci) } } diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBString.swift index e272254f..45470229 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBString.swift @@ -412,8 +412,7 @@ class TestBigString: CollectionTestCase { XCTAssertEqual(big.utf16.index(roundingDown: j2), j2) let b = big.utf16[i2 ..< j2] XCTAssertEqual(b.first, a.first) - // FIXME: Crash when i == 10 && j == 1282, seed == -3769053804926450170 - //XCTAssertEqual(b.last, a.last) + XCTAssertEqual(b.last, a.last) } } } From dc23b4d621b8a929ea0413fb250d5cf096d2c949 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 01:06:53 -0700 Subject: [PATCH 075/113] Rope: Fix splitting logic after insertions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I changed the minNodeSize formula to match with the B-tree definition, but I failed to match the insertion logic, so it left trees with undersized nodes. D’oh! --- .../Rope/Operations/Rope+Append.swift | 4 ++-- .../Rope/Operations/Rope+Insert.swift | 18 ++++++++++-------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/Sources/RopeModule/Rope/Operations/Rope+Append.swift b/Sources/RopeModule/Rope/Operations/Rope+Append.swift index cada001c..dc31c9ca 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Append.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Append.swift @@ -57,7 +57,7 @@ extension Rope._Node { return nil } - var spawn2 = split(keeping: childCount / 2) + var spawn2 = split(keeping: Summary.minNodeSize) spawn2._appendNode(spawn) return spawn2 } @@ -65,7 +65,7 @@ extension Rope._Node { _appendItem(item) return nil } - var spawn = split(keeping: childCount / 2) + var spawn = split(keeping: Summary.minNodeSize) spawn._appendItem(item) return spawn } diff --git a/Sources/RopeModule/Rope/Operations/Rope+Insert.swift b/Sources/RopeModule/Rope/Operations/Rope+Insert.swift index 2a317df8..873b9e71 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Insert.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Insert.swift @@ -149,12 +149,13 @@ extension Rope._Node { _insertNode(spawn, at: nextSlot) return nil } - var spawn2 = split(keeping: childCount / 2) - if nextSlot < childCount { + if nextSlot < Summary.minNodeSize { + let spawn2 = split(keeping: childCount / 2) _insertNode(spawn, at: nextSlot) - } else { - spawn2._insertNode(spawn, at: nextSlot - childCount) + return spawn2 } + var spawn2 = split(keeping: childCount / 2) + spawn2._insertNode(spawn, at: nextSlot - childCount) return spawn2 } } @@ -171,12 +172,13 @@ extension Rope._Node { _insertItem(item, at: slot) return nil } - var spawn = split(keeping: childCount / 2) - if slot <= childCount { + if slot < Summary.minNodeSize { + let spawn = split(keeping: childCount - Summary.minNodeSize) _insertItem(item, at: slot) - } else { - spawn._insertItem(item, at: slot - childCount) + return spawn } + var spawn = split(keeping: Summary.minNodeSize) + spawn._insertItem(item, at: slot - childCount) return spawn } From ad82bc3f805a2124d475bd0e36e175f024f049f3 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 01:21:43 -0700 Subject: [PATCH 076/113] Naming review --- .../BigString/Basics/BigString+Builder.swift | 10 ++-- .../Basics/BigString+Debugging.swift | 2 +- .../Operations/BigString+Append.swift | 2 +- .../Operations/BigString+Initializers.swift | 2 +- .../RopeModule/Rope/Basics/Rope+Builder.swift | 52 +++++++++---------- .../Rope/Operations/Rope+Extract.swift | 10 ++-- .../Rope/Operations/Rope+RemoveSubrange.swift | 38 +++++++------- .../Rope/Operations/Rope+Split.swift | 32 ++++++------ Tests/RopeModuleTests/TestRope.swift | 2 +- 9 files changed, 75 insertions(+), 75 deletions(-) diff --git a/Sources/RopeModule/BigString/Basics/BigString+Builder.swift b/Sources/RopeModule/BigString/Basics/BigString+Builder.swift index 25c04360..2f595fdd 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Builder.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Builder.swift @@ -79,7 +79,7 @@ extension BigString.Builder { self.base._prefix = prefix } while let next = ingester.nextChunk() { - base.append(next) + base.insertBeforeTip(next) } self.prefixEndState = ingester.state } @@ -92,7 +92,7 @@ extension BigString.Builder { mutating func append(_ newChunk: __owned _Chunk, state: inout _CharacterRecognizer) { var newChunk = newChunk newChunk.resyncBreaksFromStartToEnd(old: &state, new: &self.prefixEndState) - self.base.append(newChunk) + self.base.insertBeforeTip(newChunk) } mutating func append(_ other: __owned BigString) { @@ -102,14 +102,14 @@ extension BigString.Builder { mutating func append(_ other: __owned BigString, in range: Range) { let extract = BigString(other, in: range, state: &self.prefixEndState) - self.base.append(extract._rope) + self.base.insertBeforeTip(extract._rope) } mutating func append(_ other: __owned _Rope, state: inout _CharacterRecognizer) { guard !other.isEmpty else { return } var other = BigString(_rope: other) other._rope.resyncBreaksToEnd(old: &state, new: &self.prefixEndState) - self.base.append(other._rope) + self.base.insertBeforeTip(other._rope) } mutating func append(from ingester: inout _Ingester) { @@ -124,7 +124,7 @@ extension BigString.Builder { let suffixCount = base._suffix?.value.utf8Count ?? 0 while let chunk = ingester.nextWellSizedChunk(suffix: suffixCount) { - base.append(chunk) + base.insertBeforeTip(chunk) } precondition(ingester.isAtEnd) self.prefixEndState = ingester.state diff --git a/Sources/RopeModule/BigString/Basics/BigString+Debugging.swift b/Sources/RopeModule/BigString/Basics/BigString+Debugging.swift index b92126ff..c7263cd8 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Debugging.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Debugging.swift @@ -13,7 +13,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { - public func dump(heightLimit: Int = .max) { + public func _dump(heightLimit: Int = .max) { _rope._dump(heightLimit: heightLimit) } } diff --git a/Sources/RopeModule/BigString/Operations/BigString+Append.swift b/Sources/RopeModule/BigString/Operations/BigString+Append.swift index e82390a9..8c0bb36d 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Append.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Append.swift @@ -33,7 +33,7 @@ extension BigString { var builder = _Rope.Builder() while let chunk = ingester.nextWellSizedChunk() { precondition(!chunk.isUndersized) - builder.append(chunk) + builder.insertBeforeTip(chunk) } precondition(ingester.isAtEnd) _rope = _Rope.join(_rope, builder.finalize()) diff --git a/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift index 74b40529..37b045e4 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift @@ -17,7 +17,7 @@ extension BigString { var builder = _Rope.Builder() var ingester = _Ingester(input) while let chunk = ingester.nextWellSizedChunk() { - builder.append(chunk) + builder.insertBeforeTip(chunk) } self._rope = builder.finalize() } diff --git a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift index 414adba8..2a626a18 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift @@ -18,7 +18,7 @@ extension Rope { } var builder = Builder() for item in items { - builder.append(item) + builder.insertBeforeTip(item) } self = builder.finalize() } @@ -170,11 +170,11 @@ extension Rope { return nil } - public mutating func append(_ item: __owned Element) { - _append(Rope._Item(item)) + public mutating func insertBeforeTip(_ item: __owned Element) { + _insertBeforeTip(Rope._Item(item)) } - mutating func _append(_ item: __owned Rope._Item) { + mutating func _insertBeforeTip(_ item: __owned Rope._Item) { guard !item.isEmpty else { return } guard var prefix = self._prefix._take() else { self._prefix = item @@ -202,23 +202,23 @@ extension Rope { _invariantCheck() } - public mutating func append(_ rope: __owned Rope) { + public mutating func insertBeforeTip(_ rope: __owned Rope) { guard rope._root != nil else { return } - _append(rope.root) + _insertBeforeTip(rope.root) } - mutating func _append(_ node: __owned Rope._Node) { + mutating func _insertBeforeTip(_ node: __owned Rope._Node) { defer { _invariantCheck() } var node = node if node.height == 0 { if node.childCount == 1 { - _append(node.firstItem) + _insertBeforeTip(node.firstItem) return } if let item = self._prefix._take() { if let spawn = node.prepend(item) { - _append(node) - _append(spawn) + _insertBeforeTip(node) + _insertBeforeTip(spawn) return } } @@ -287,11 +287,11 @@ extension Rope { _prefixTrees.append(Rope(root: new)) } - public mutating func prependSuffix(_ item: __owned Element) { - _prependSuffix(_Item(item)) + public mutating func insertAfterTip(_ item: __owned Element) { + _insertAfterTip(_Item(item)) } - mutating func _prependSuffix(_ item: __owned _Item) { + mutating func _insertAfterTip(_ item: __owned _Item) { guard !item.isEmpty else { return } if var suffixItem = self._suffix._take() { var item = item @@ -306,56 +306,56 @@ extension Rope { self._suffix = item } - public mutating func prependSuffix(_ rope: __owned Rope) { + public mutating func insertAfterTip(_ rope: __owned Rope) { assert(_suffix == nil) assert(_suffixTrees.isEmpty || rope._height <= _suffixTrees.last!._height) _suffixTrees.append(rope) } - mutating func _prependSuffix(_ rope: __owned Rope._Node) { - prependSuffix(Rope(root: rope)) + mutating func _insertAfterTip(_ rope: __owned Rope._Node) { + insertAfterTip(Rope(root: rope)) } - mutating func _append(slots: Range, in node: __owned Rope._Node) { + mutating func _insertBeforeTip(slots: Range, in node: __owned Rope._Node) { assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) let c = slots.count guard c > 0 else { return } if c == 1 { if node.isLeaf { let item = node.readLeaf { $0.children[slots.lowerBound] } - _append(item) + _insertBeforeTip(item) } else { let child = node.readInner { $0.children[slots.lowerBound] } - _append(child) + _insertBeforeTip(child) } return } let copy = node.copy(slots: slots) - _append(copy) + _insertBeforeTip(copy) } - mutating func _prependSuffix(slots: Range, in node: __owned Rope._Node) { + mutating func _insertAfterTip(slots: Range, in node: __owned Rope._Node) { assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) let c = slots.count guard c > 0 else { return } if c == 1 { if node.isLeaf { let item = node.readLeaf { $0.children[slots.lowerBound] } - _prependSuffix(item) + _insertAfterTip(item) } else { let child = node.readInner { $0.children[slots.lowerBound] } - _prependSuffix(child) + _insertAfterTip(child) } return } let copy = node.copy(slots: slots) - _prependSuffix(copy) + _insertAfterTip(copy) } public mutating func finalize() -> Rope { // Integrate prefix & suffix chunks. if let suffixItem = self._suffix._take() { - _append(suffixItem) + _insertBeforeTip(suffixItem) } if var prefix = self._prefix._take() { if !prefix.isUndersized { @@ -375,7 +375,7 @@ extension Rope { } assert(self._prefix == nil && self._suffix == nil) while let tree = _suffixTrees.popLast() { - append(tree) + insertBeforeTip(tree) } // Merge all saplings, the seedling and the seed into a single rope. if let item = self._prefix._take() { diff --git a/Sources/RopeModule/Rope/Operations/Rope+Extract.swift b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift index 414586f1..5ffd2bc7 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Extract.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift @@ -46,19 +46,19 @@ extension Rope._Node { at: u.remaining - metric._nonnegativeSize(of: item.summary), in: item2.value) _ = item2.split(at: j) - builder._append(item2) + builder._insertBeforeTip(item2) return } assert(l.slot < u.slot) var left = c[l.slot] left = left.split(at: metric.index(at: l.remaining, in: left.value)) - builder._append(left) + builder._insertBeforeTip(left) for i in l.slot + 1 ..< u.slot { - builder._append(c[i]) + builder._insertBeforeTip(c[i]) } var right = c[u.slot] _ = right.split(at: metric.index(at: u.remaining, in: right.value)) - builder._append(right) + builder._insertBeforeTip(right) } return } @@ -76,7 +76,7 @@ extension Rope._Node { let lsize = metric._nonnegativeSize(of: c[l.slot].summary) c[l.slot].extract(from: l.remaining, to: lsize, in: metric, into: &builder) for i in l.slot + 1 ..< u.slot { - builder._append(c[i]) + builder._insertBeforeTip(c[i]) } c[u.slot].extract(from: 0, to: u.remaining, in: metric, into: &builder) } diff --git a/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift index f80d0193..2ade38a1 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift @@ -35,7 +35,7 @@ extension Rope { _invalidateIndices() var builder = builder(removing: bounds, in: metric) for item in newElements { - builder.append(item) + builder.insertBeforeTip(item) } self = builder.finalize() } @@ -87,10 +87,10 @@ extension Rope { assert(l.slot == u.slot) var item = node._leafSplit(at: l.slot, into: &builder) let i2 = metric.index(at: u.remaining, in: item.value) - builder._prependSuffix(item.split(at: i2)) + builder._insertAfterTip(item.split(at: i2)) let i1 = metric.index(at: l.remaining, in: item.value) _ = item.split(at: i1) - builder._append(item) + builder._insertBeforeTip(item) return builder } } @@ -106,9 +106,9 @@ extension Rope._Node { assert(start.remaining >= 0) assert(end.remaining >= 0) - builder._append(slots: 0 ..< start.slot, in: self) + builder._insertBeforeTip(slots: 0 ..< start.slot, in: self) if end.slot < childCount { - builder._prependSuffix(slots: end.slot + 1 ..< childCount, in: self) + builder._insertAfterTip(slots: end.slot + 1 ..< childCount, in: self) } guard isLeaf else { @@ -126,8 +126,8 @@ extension Rope._Node { let i1 = metric.index(at: start.remaining, in: lower.value) let i2 = metric.index(at: end.remaining, in: upper.value) _ = lower.split(at: i1) - builder._append(lower) - builder._prependSuffix(upper.split(at: i2)) + builder._insertBeforeTip(lower) + builder._insertAfterTip(upper.split(at: i2)) } __consuming func removeSuffix( @@ -141,7 +141,7 @@ extension Rope._Node { while true { guard position > 0 else { return } guard position < metric.size(of: node.summary) else { - builder._append(node) + builder._insertBeforeTip(node) return } @@ -155,7 +155,7 @@ extension Rope._Node { var item = node._leafRemoveSuffix(returning: r.slot, into: &builder) let i = metric.index(at: r.remaining, in: item.value) _ = item.split(at: i) - builder._append(item) + builder._insertBeforeTip(item) } __consuming func removePrefix( @@ -167,7 +167,7 @@ extension Rope._Node { var position = position while true { guard position > 0 else { - builder._prependSuffix(node) + builder._insertAfterTip(node) return } guard position < metric.size(of: node.summary) else { return } @@ -181,7 +181,7 @@ extension Rope._Node { let r = node.readLeaf { $0.findSlot(at: position, in: metric) } var item = node._leafRemovePrefix(returning: r.slot, into: &builder) let i = metric.index(at: r.remaining, in: item.value) - builder._prependSuffix(item.split(at: i)) + builder._insertAfterTip(item.split(at: i)) } mutating func _innerRemoveSuffix( @@ -200,7 +200,7 @@ extension Rope._Node { let c = $0.children return (c[0], c[1]) } - builder._append(remaining) + builder._insertBeforeTip(remaining) self = new return } @@ -213,7 +213,7 @@ extension Rope._Node { var n = _removeNode(at: slot) swap(&self, &n) assert(n.childCount > 1) - builder._append(n) + builder._insertBeforeTip(n) } __consuming func _leafRemoveSuffix( @@ -231,7 +231,7 @@ extension Rope._Node { let c = $0.children return (c[0], c[1]) } - builder._append(remaining) + builder._insertBeforeTip(remaining) return new } @@ -242,7 +242,7 @@ extension Rope._Node { n.summary.subtract(delta) } let item = n._removeItem(at: slot).removed - builder._append(n) + builder._insertBeforeTip(n) return item } @@ -262,7 +262,7 @@ extension Rope._Node { let c = $0.children return (c[$0.childCount - 2], c[$0.childCount - 1]) } - builder._prependSuffix(remaining) + builder._insertAfterTip(remaining) self = new return } @@ -276,7 +276,7 @@ extension Rope._Node { self.summary.subtract(delta) assert(self.childCount > 1) swap(&self, &n) - builder._prependSuffix(n) + builder._insertAfterTip(n) } __consuming func _leafRemovePrefix( @@ -294,7 +294,7 @@ extension Rope._Node { let c = $0.children return (c[$0.childCount - 2], c[$0.childCount - 1]) } - builder._prependSuffix(remaining) + builder._insertAfterTip(remaining) return new } @@ -307,7 +307,7 @@ extension Rope._Node { } n.summary.subtract(delta) assert(n.childCount > 1) - builder._prependSuffix(n) + builder._insertAfterTip(n) return item } } diff --git a/Sources/RopeModule/Rope/Operations/Rope+Split.swift b/Sources/RopeModule/Rope/Operations/Rope+Split.swift index 28deaa78..bae6da0a 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Split.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Split.swift @@ -30,8 +30,8 @@ extension Rope { var item = node._leafSplit(at: r.slot, into: &builder) let index = metric.index(at: r.remaining, in: item.value) let suffix = item.split(at: index) - builder._prependSuffix(suffix) - builder.append(item.value) + builder._insertAfterTip(suffix) + builder._insertBeforeTip(item) return builder } @@ -59,10 +59,10 @@ extension Rope { var (builder, item) = self.split(at: ropeIndex) let suffix = item.split(at: itemIndex) if !suffix.isEmpty { - builder.prependSuffix(suffix) + builder.insertAfterTip(suffix) } if !item.isEmpty { - builder.append(item) + builder.insertBeforeTip(item) } return builder } @@ -79,10 +79,10 @@ extension Rope._Node { var slot = slot if slot == childCount - 2 { - builder._prependSuffix(_removeNode(at: childCount - 1)) + builder._insertAfterTip(_removeNode(at: childCount - 1)) } if slot == 1 { - builder._append(_removeNode(at: 0)) + builder._insertBeforeTip(_removeNode(at: 0)) slot -= 1 } @@ -91,16 +91,16 @@ extension Rope._Node { guard n.childCount > 0 else { return } if slot == 0 { - builder._prependSuffix(n) + builder._insertAfterTip(n) return } if slot == n.childCount { - builder._append(n) + builder._insertBeforeTip(n) return } let suffix = n.split(keeping: slot) - builder._append(n) - builder._prependSuffix(suffix) + builder._insertBeforeTip(n) + builder._insertAfterTip(suffix) } __consuming func _leafSplit( @@ -115,10 +115,10 @@ extension Rope._Node { var slot = slot if slot == n.childCount - 2 { - builder._prependSuffix(n._removeItem(at: childCount - 1).removed) + builder._insertAfterTip(n._removeItem(at: childCount - 1).removed) } if slot == 1 { - builder.append(n._removeItem(at: 0).removed.value) + builder.insertBeforeTip(n._removeItem(at: 0).removed.value) slot -= 1 } @@ -126,13 +126,13 @@ extension Rope._Node { guard n.childCount > 0 else { return item } if slot == 0 { - builder._prependSuffix(n) + builder._insertAfterTip(n) } else if slot == n.childCount { - builder._append(n) + builder._insertBeforeTip(n) } else { let suffix = n.split(keeping: slot) - builder._append(n) - builder._prependSuffix(suffix) + builder._insertBeforeTip(n) + builder._insertAfterTip(suffix) } return item } diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index 16ce8d25..d5e7e098 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -132,7 +132,7 @@ class TestRope: XCTestCase { } var builder = Rope.Builder() for chunk in ref { - builder.append(chunk) + builder.insertBeforeTip(chunk) builder._invariantCheck() } let rope = builder.finalize() From 28010b2f6c481b766a8ba0150541b3f9b8dae840 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 01:28:13 -0700 Subject: [PATCH 077/113] Use COLLECTIONS_INTERNAL_CHECKS --- .../RopeModule/BigString/Basics/BigString+Invariants.swift | 2 +- .../BigString/Chunk/BigString+Chunk+RopeElement.swift | 2 +- Sources/RopeModule/Rope/Basics/Rope+Builder.swift | 2 +- Sources/RopeModule/Rope/Basics/Rope+Invariants.swift | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift b/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift index 864e5d34..989d9a73 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift @@ -14,7 +14,7 @@ @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension BigString { public func _invariantCheck() { -#if DEBUG +#if COLLECTIONS_INTERNAL_CHECKS _rope._invariantCheck() let allowUndersize = _rope.isSingleton diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift index 9f17f8e3..6f26a887 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+RopeElement.swift @@ -25,7 +25,7 @@ extension BigString._Chunk: RopeElement { var isUndersized: Bool { utf8Count < Self.minUTF8Count } func invariantCheck() { -#if DEBUG +#if COLLECTIONS_INTERNAL_CHECKS precondition(string.endIndex._canBeUTF8) let c = utf8Count if c == 0 { diff --git a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift index 2a626a18..244adb35 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift @@ -391,7 +391,7 @@ extension Rope { } public func _invariantCheck() { -#if DEBUG +#if COLLECTIONS_INTERNAL_CHECKS var h = UInt8.max for sapling in _prefixTrees { precondition(sapling._height <= h) diff --git a/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift b/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift index b26942c0..3cb7b645 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift @@ -11,7 +11,7 @@ extension Rope { public func _invariantCheck() { -#if DEBUG +#if COLLECTIONS_INTERNAL_CHECKS _root?.invariantCheck(depth: 0, height: root.height, recursive: true) #endif } @@ -19,7 +19,7 @@ extension Rope { extension Rope._Node { func invariantCheck(depth: UInt8, height: UInt8, recursive: Bool = true) { -#if DEBUG +#if COLLECTIONS_INTERNAL_CHECKS precondition(height == self.height, "Mismatching rope height") if isLeaf { precondition(self.childCount <= Summary.maxNodeSize, "Oversized leaf") From 8394ea7575b996a4dabc5be75eaca9fed85227b7 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 01:30:03 -0700 Subject: [PATCH 078/113] Clean up test definitions --- .../Rope/Operations/Rope+Remove.swift | 2 +- Tests/RopeModuleTests/TestBString2.swift | 65 ------------------- ...{TestBString.swift => TestBigString.swift} | 48 +++++++++++++- Tests/RopeModuleTests/TestRope.swift | 4 +- 4 files changed, 47 insertions(+), 72 deletions(-) delete mode 100644 Tests/RopeModuleTests/TestBString2.swift rename Tests/RopeModuleTests/{TestBString.swift => TestBigString.swift} (96%) diff --git a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift index f29aa6f8..7a19183a 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift @@ -44,7 +44,7 @@ extension Rope._Node { } extension Rope { - mutating func remove( + public mutating func remove( at position: Int, in metric: some RopeMetric ) -> Element { diff --git a/Tests/RopeModuleTests/TestBString2.swift b/Tests/RopeModuleTests/TestBString2.swift deleted file mode 100644 index cc650b38..00000000 --- a/Tests/RopeModuleTests/TestBString2.swift +++ /dev/null @@ -1,65 +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) && DEBUG -import _CollectionsTestSupport -import XCTest -@testable import _RopeModule - -@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) -class TestBigString2: CollectionTestCase { - override var isAvailable: Bool { isRunningOnSwiftStdlib5_8 } - - func testUTF8View() { - let str = BigString(shortSample) - checkBidirectionalCollection(str.utf8, expectedContents: shortSample.utf8) - } - - func testUTF16View() { - let str = BigString(shortSample) - checkBidirectionalCollection(str.utf16, expectedContents: shortSample.utf16) - } - - func testUnicodeScalarView() { - let str = BigString(shortSample) - checkBidirectionalCollection(str.unicodeScalars, expectedContents: shortSample.unicodeScalars) - } - - func testCharacterView() { - let str = BigString(shortSample) - checkBidirectionalCollection(str, expectedContents: shortSample) - } - - func testHashable_Characters() { - let classes: [[BigString]] = [ - ["Cafe\u{301}", "Café"], - ["Foo\u{301}\u{327}", "Foo\u{327}\u{301}"], - ["Foo;bar", "Foo\u{37e}bar"], - ] - checkHashable(equivalenceClasses: classes) - } - - func testHashable_Scalars() { - let classes: [BigString] = [ - "Cafe\u{301}", - "Café", - "Foo\u{301}\u{327}", - "Foo\u{327}\u{301}", - "Foo;bar", - "Foo\u{37e}bar", - ] - checkHashable(equivalenceClasses: classes.map { [$0.unicodeScalars] }) - checkHashable(equivalenceClasses: classes.map { [$0.utf8] }) - checkHashable(equivalenceClasses: classes.map { [$0.utf16] }) - } -} - -#endif diff --git a/Tests/RopeModuleTests/TestBString.swift b/Tests/RopeModuleTests/TestBigString.swift similarity index 96% rename from Tests/RopeModuleTests/TestBString.swift rename to Tests/RopeModuleTests/TestBigString.swift index 45470229..2b36ee1c 100644 --- a/Tests/RopeModuleTests/TestBString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -36,7 +36,6 @@ class TestBigString: CollectionTestCase { XCTAssertLessThanOrEqual(min, max) #if !DEBUG // Debug builds have smaller nodes - // We want big strings to hold at least as many UTF-8 code units as a regular String. // We want big strings to hold at least as many UTF-8 code units as a regular String. XCTAssertGreaterThanOrEqual(min, 1 << 48) #endif @@ -78,7 +77,7 @@ class TestBigString: CollectionTestCase { func test_string_conversion() { let big = BigString(sampleString) - + big._invariantCheck() XCTAssertEqual(big.count, sampleString.count) XCTAssertEqual(big.unicodeScalars.count, sampleString.unicodeScalars.count) @@ -88,7 +87,50 @@ class TestBigString: CollectionTestCase { let flat = String(big) XCTAssertEqual(flat, sampleString) } - + + func testUTF8View() { + let str = BigString(shortSample) + checkBidirectionalCollection(str.utf8, expectedContents: shortSample.utf8) + } + + func testUTF16View() { + let str = BigString(shortSample) + checkBidirectionalCollection(str.utf16, expectedContents: shortSample.utf16) + } + + func testUnicodeScalarView() { + let str = BigString(shortSample) + checkBidirectionalCollection(str.unicodeScalars, expectedContents: shortSample.unicodeScalars) + } + + func testCharacterView() { + let str = BigString(shortSample) + checkBidirectionalCollection(str, expectedContents: shortSample) + } + + func testHashable_Characters() { + let classes: [[BigString]] = [ + ["Cafe\u{301}", "Café"], + ["Foo\u{301}\u{327}", "Foo\u{327}\u{301}"], + ["Foo;bar", "Foo\u{37e}bar"], + ] + checkHashable(equivalenceClasses: classes) + } + + func testHashable_Scalars() { + let classes: [BigString] = [ + "Cafe\u{301}", + "Café", + "Foo\u{301}\u{327}", + "Foo\u{327}\u{301}", + "Foo;bar", + "Foo\u{37e}bar", + ] + checkHashable(equivalenceClasses: classes.map { [$0.unicodeScalars] }) + checkHashable(equivalenceClasses: classes.map { [$0.utf8] }) + checkHashable(equivalenceClasses: classes.map { [$0.utf16] }) + } + @discardableResult func checkCharacterIndices( _ flat: String, diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index d5e7e098..0c3f40e3 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -9,8 +9,7 @@ // //===----------------------------------------------------------------------===// -#if DEBUG -@testable import _RopeModule +import _RopeModule import XCTest struct Chunk: RopeElement, Equatable, CustomStringConvertible { @@ -541,4 +540,3 @@ class TestRope: XCTestCase { } } -#endif From fcd6800b9d1171fbe0a00f51a72afac32b0a1987 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 11:42:56 -0700 Subject: [PATCH 079/113] BigString: Slightly speed up a slow test --- Tests/RopeModuleTests/TestBigString.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index 2b36ee1c..c7bc5b94 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -638,6 +638,7 @@ class TestBigString: CollectionTestCase { var pieces = pieces(of: input, by: stride) var rng = RepeatableRandomNumberGenerator(seed: 0) pieces.shuffle(using: &rng) + let interval = Swift.max(pieces.count / 25, 25) let placeholder: Character = " " // To make this super slow, replace with "\u{200D}" var big = BigString(repeating: placeholder, count: pieces.count) @@ -659,7 +660,7 @@ class TestBigString: CollectionTestCase { big.replaceSubrange(k1 ..< k2, with: piece.str) - if i % 20 == 0 { + if i.isMultiple(of: interval) { big._invariantCheck() XCTAssertEqual(String(big), smol) checkUTF8Indices(smol, big) From 424c8ece985ea6e6ec2a578a075b5e58ebe86d21 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 16:37:22 -0700 Subject: [PATCH 080/113] =?UTF-8?q?HashTreeCollections:=20Qualify=20intern?= =?UTF-8?q?al=20type=20names=20with=20=E2=80=9CHash=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes them unique throughout the package, allowing this code to be built as a single, huge module. --- Sources/HashTreeCollections/CMakeLists.txt | 78 ++++++------ .../_AncestorHashSlots.swift} | 28 ++--- .../{Node => HashNode}/_Bitmap.swift | 10 +- .../{Node => HashNode}/_Bucket.swift | 0 .../{Node => HashNode}/_Hash.swift | 8 +- .../_HashLevel.swift} | 22 ++-- .../_HashNode+Builder.swift} | 86 ++++++------- .../_HashNode+Debugging.swift} | 16 +-- .../_HashNode+Initializers.swift} | 78 ++++++------ .../_HashNode+Invariants.swift} | 14 +-- .../_HashNode+Lookups.swift} | 54 ++++---- .../_HashNode+Primitive Insertions.swift} | 16 +-- .../_HashNode+Primitive Removals.swift} | 24 ++-- .../_HashNode+Primitive Replacement.swift} | 14 +-- .../_HashNode+Storage.swift} | 54 ++++---- ...ashNode+Structural compactMapValues.swift} | 8 +- .../_HashNode+Structural filter.swift} | 8 +- .../_HashNode+Structural intersection.swift} | 18 +-- .../_HashNode+Structural isDisjoint.swift} | 10 +- .../_HashNode+Structural isEqualSet.swift} | 4 +- .../_HashNode+Structural isSubset.swift} | 6 +- .../_HashNode+Structural mapValues.swift} | 14 +-- .../_HashNode+Structural merge.swift} | 32 ++--- .../_HashNode+Structural subtracting.swift} | 18 +-- ...Node+Structural symmetricDifference.swift} | 44 +++---- .../_HashNode+Structural union.swift} | 36 +++--- .../_HashNode+Subtree Insertions.swift} | 116 +++++++++--------- .../_HashNode+Subtree Modify.swift} | 26 ++-- .../_HashNode+Subtree Removals.swift} | 42 +++---- .../_HashNode+UnsafeHandle.swift} | 44 +++---- .../_Node.swift => HashNode/_HashNode.swift} | 32 ++--- .../_Slot.swift => HashNode/_HashSlot.swift} | 36 +++--- .../_HashStack.swift} | 4 +- .../_HashTreeIterator.swift | 32 ++--- .../_HashTreeStatistics.swift | 8 +- .../_RawHashNode+UnsafeHandle.swift} | 26 ++-- .../_RawHashNode.swift} | 20 +-- .../{Node => HashNode}/_StorageHeader.swift | 16 +-- .../_UnmanagedHashNode.swift} | 34 ++--- .../{Node => HashNode}/_UnsafePath.swift | 102 +++++++-------- .../TreeDictionary+Collection.swift | 4 +- .../TreeDictionary+Debugging.swift | 2 +- .../TreeDictionary/TreeDictionary+Keys.swift | 2 +- .../TreeDictionary+Sequence.swift | 4 +- .../TreeDictionary+Values.swift | 4 +- .../TreeDictionary/TreeDictionary.swift | 10 +- .../TreeSet/TreeSet+Collection.swift | 4 +- .../TreeSet/TreeSet+Debugging.swift | 2 +- .../TreeSet/TreeSet+Sequence.swift | 4 +- .../TreeSet+SetAlgebra intersection.swift | 4 +- .../TreeSet+SetAlgebra isEqualSet.swift | 2 +- .../TreeSet+SetAlgebra isStrictSubset.swift | 2 +- .../TreeSet+SetAlgebra isStrictSuperset.swift | 2 +- .../TreeSet/TreeSet+SetAlgebra isSubset.swift | 2 +- .../TreeSet+SetAlgebra subtracting.swift | 2 +- .../HashTreeCollections/TreeSet/TreeSet.swift | 10 +- 56 files changed, 653 insertions(+), 645 deletions(-) rename Sources/HashTreeCollections/{Node/_AncestorSlots.swift => HashNode/_AncestorHashSlots.swift} (79%) rename Sources/HashTreeCollections/{Node => HashNode}/_Bitmap.swift (95%) rename Sources/HashTreeCollections/{Node => HashNode}/_Bucket.swift (100%) rename Sources/HashTreeCollections/{Node => HashNode}/_Hash.swift (90%) rename Sources/HashTreeCollections/{Node/_Level.swift => HashNode/_HashLevel.swift} (85%) rename Sources/HashTreeCollections/{Node/_Node+Builder.swift => HashNode/_HashNode+Builder.swift} (78%) rename Sources/HashTreeCollections/{Node/_Node+Debugging.swift => HashNode/_HashNode+Debugging.swift} (91%) rename Sources/HashTreeCollections/{Node/_Node+Initializers.swift => HashNode/_HashNode+Initializers.swift} (80%) rename Sources/HashTreeCollections/{Node/_Node+Invariants.swift => HashNode/_HashNode+Invariants.swift} (89%) rename Sources/HashTreeCollections/{Node/_Node+Lookups.swift => HashNode/_HashNode+Lookups.swift} (86%) rename Sources/HashTreeCollections/{Node/_Node+Primitive Insertions.swift => HashNode/_HashNode+Primitive Insertions.swift} (88%) rename Sources/HashTreeCollections/{Node/_Node+Primitive Removals.swift => HashNode/_HashNode+Primitive Removals.swift} (88%) rename Sources/HashTreeCollections/{Node/_Node+Primitive Replacement.swift => HashNode/_HashNode+Primitive Replacement.swift} (87%) rename Sources/HashTreeCollections/{Node/_Node+Storage.swift => HashNode/_HashNode+Storage.swift} (82%) rename Sources/HashTreeCollections/{Node/_Node+Structural compactMapValues.swift => HashNode/_HashNode+Structural compactMapValues.swift} (89%) rename Sources/HashTreeCollections/{Node/_Node+Structural filter.swift => HashNode/_HashNode+Structural filter.swift} (94%) rename Sources/HashTreeCollections/{Node/_Node+Structural intersection.swift => HashNode/_HashNode+Structural intersection.swift} (95%) rename Sources/HashTreeCollections/{Node/_Node+Structural isDisjoint.swift => HashNode/_HashNode+Structural isDisjoint.swift} (96%) rename Sources/HashTreeCollections/{Node/_Node+Structural isEqualSet.swift => HashNode/_HashNode+Structural isEqualSet.swift} (97%) rename Sources/HashTreeCollections/{Node/_Node+Structural isSubset.swift => HashNode/_HashNode+Structural isSubset.swift} (97%) rename Sources/HashTreeCollections/{Node/_Node+Structural mapValues.swift => HashNode/_HashNode+Structural mapValues.swift} (89%) rename Sources/HashTreeCollections/{Node/_Node+Structural merge.swift => HashNode/_HashNode+Structural merge.swift} (93%) rename Sources/HashTreeCollections/{Node/_Node+Structural subtracting.swift => HashNode/_HashNode+Structural subtracting.swift} (95%) rename Sources/HashTreeCollections/{Node/_Node+Structural symmetricDifference.swift => HashNode/_HashNode+Structural symmetricDifference.swift} (91%) rename Sources/HashTreeCollections/{Node/_Node+Structural union.swift => HashNode/_HashNode+Structural union.swift} (90%) rename Sources/HashTreeCollections/{Node/_Node+Subtree Insertions.swift => HashNode/_HashNode+Subtree Insertions.swift} (89%) rename Sources/HashTreeCollections/{Node/_Node+Subtree Modify.swift => HashNode/_HashNode+Subtree Modify.swift} (93%) rename Sources/HashTreeCollections/{Node/_Node+Subtree Removals.swift => HashNode/_HashNode+Subtree Removals.swift} (90%) rename Sources/HashTreeCollections/{Node/_Node+UnsafeHandle.swift => HashNode/_HashNode+UnsafeHandle.swift} (85%) rename Sources/HashTreeCollections/{Node/_Node.swift => HashNode/_HashNode.swift} (84%) rename Sources/HashTreeCollections/{Node/_Slot.swift => HashNode/_HashSlot.swift} (75%) rename Sources/HashTreeCollections/{Node/_Stack.swift => HashNode/_HashStack.swift} (97%) rename Sources/HashTreeCollections/{Node => HashNode}/_HashTreeIterator.swift (77%) rename Sources/HashTreeCollections/{Node => HashNode}/_HashTreeStatistics.swift (95%) rename Sources/HashTreeCollections/{Node/_RawNode+UnsafeHandle.swift => HashNode/_RawHashNode+UnsafeHandle.swift} (79%) rename Sources/HashTreeCollections/{Node/_RawNode.swift => HashNode/_RawHashNode.swift} (82%) rename Sources/HashTreeCollections/{Node => HashNode}/_StorageHeader.swift (92%) rename Sources/HashTreeCollections/{Node/_UnmanagedNode.swift => HashNode/_UnmanagedHashNode.swift} (69%) rename Sources/HashTreeCollections/{Node => HashNode}/_UnsafePath.swift (92%) diff --git a/Sources/HashTreeCollections/CMakeLists.txt b/Sources/HashTreeCollections/CMakeLists.txt index c5690fbf..96bc2ac0 100644 --- a/Sources/HashTreeCollections/CMakeLists.txt +++ b/Sources/HashTreeCollections/CMakeLists.txt @@ -8,45 +8,45 @@ See https://swift.org/LICENSE.txt for license information #]] add_library(HashTreeCollections - "Node/_AncestorSlots.swift" - "Node/_Bitmap.swift" - "Node/_Bucket.swift" - "Node/_Hash.swift" - "Node/_HashTreeIterator.swift" - "Node/_HashTreeStatistics.swift" - "Node/_Level.swift" - "Node/_Node+Builder.swift" - "Node/_Node+Debugging.swift" - "Node/_Node+Initializers.swift" - "Node/_Node+Invariants.swift" - "Node/_Node+Lookups.swift" - "Node/_Node+Primitive Insertions.swift" - "Node/_Node+Primitive Removals.swift" - "Node/_Node+Primitive Replacement.swift" - "Node/_Node+Storage.swift" - "Node/_Node+Structural compactMapValues.swift" - "Node/_Node+Structural filter.swift" - "Node/_Node+Structural intersection.swift" - "Node/_Node+Structural isDisjoint.swift" - "Node/_Node+Structural isEqualSet.swift" - "Node/_Node+Structural isSubset.swift" - "Node/_Node+Structural mapValues.swift" - "Node/_Node+Structural merge.swift" - "Node/_Node+Structural subtracting.swift" - "Node/_Node+Structural symmetricDifference.swift" - "Node/_Node+Structural union.swift" - "Node/_Node+Subtree Insertions.swift" - "Node/_Node+Subtree Modify.swift" - "Node/_Node+Subtree Removals.swift" - "Node/_Node+UnsafeHandle.swift" - "Node/_Node.swift" - "Node/_RawNode+UnsafeHandle.swift" - "Node/_RawNode.swift" - "Node/_Slot.swift" - "Node/_Stack.swift" - "Node/_StorageHeader.swift" - "Node/_UnmanagedNode.swift" - "Node/_UnsafePath.swift" + "HashNode/_AncestorHashSlots.swift" + "HashNode/_Bitmap.swift" + "HashNode/_Bucket.swift" + "HashNode/_Hash.swift" + "HashNode/_HashTreeIterator.swift" + "HashNode/_HashTreeStatistics.swift" + "HashNode/_HashLevel.swift" + "HashNode/_HashNode+Builder.swift" + "HashNode/_HashNode+Debugging.swift" + "HashNode/_HashNode+Initializers.swift" + "HashNode/_HashNode+Invariants.swift" + "HashNode/_HashNode+Lookups.swift" + "HashNode/_HashNode+Primitive Insertions.swift" + "HashNode/_HashNode+Primitive Removals.swift" + "HashNode/_HashNode+Primitive Replacement.swift" + "HashNode/_HashNode+Storage.swift" + "HashNode/_HashNode+Structural compactMapValues.swift" + "HashNode/_HashNode+Structural filter.swift" + "HashNode/_HashNode+Structural intersection.swift" + "HashNode/_HashNode+Structural isDisjoint.swift" + "HashNode/_HashNode+Structural isEqualSet.swift" + "HashNode/_HashNode+Structural isSubset.swift" + "HashNode/_HashNode+Structural mapValues.swift" + "HashNode/_HashNode+Structural merge.swift" + "HashNode/_HashNode+Structural subtracting.swift" + "HashNode/_HashNode+Structural symmetricDifference.swift" + "HashNode/_HashNode+Structural union.swift" + "HashNode/_HashNode+Subtree Insertions.swift" + "HashNode/_HashNode+Subtree Modify.swift" + "HashNode/_HashNode+Subtree Removals.swift" + "HashNode/_HashNode+UnsafeHandle.swift" + "HashNode/_HashNode.swift" + "HashNode/_RawHashNode+UnsafeHandle.swift" + "HashNode/_RawHashNode.swift" + "HashNode/_HashSlot.swift" + "HashNode/_HashStack.swift" + "HashNode/_HashNodeHeader.swift" + "HashNode/_UnmanagedHashNode.swift" + "HashNode/_UnsafePath.swift" "TreeDictionary/TreeDictionary+Codable.swift" "TreeDictionary/TreeDictionary+Collection.swift" "TreeDictionary/TreeDictionary+CustomReflectable.swift" diff --git a/Sources/HashTreeCollections/Node/_AncestorSlots.swift b/Sources/HashTreeCollections/HashNode/_AncestorHashSlots.swift similarity index 79% rename from Sources/HashTreeCollections/Node/_AncestorSlots.swift rename to Sources/HashTreeCollections/HashNode/_AncestorHashSlots.swift index 54d12375..c9e7872c 100644 --- a/Sources/HashTreeCollections/Node/_AncestorSlots.swift +++ b/Sources/HashTreeCollections/HashNode/_AncestorHashSlots.swift @@ -12,14 +12,14 @@ /// A collection of slot values logically addressing a particular node in a /// hash tree. The collection is (logically) extended with zero slots up to /// the maximum depth of the tree -- to unambiguously address a single node, -/// this therefore needs to be augmented with a `_Level` value. +/// this therefore needs to be augmented with a `_HashLevel` value. /// /// This construct can only be used to identify a particular node in the tree; /// it does not necessarily have room to include an item offset in the addressed /// node. (See `_Path` if you need to address a particular item.) @usableFromInline @frozen -struct _AncestorSlots { +struct _AncestorHashSlots { @usableFromInline internal var path: UInt @@ -29,27 +29,27 @@ struct _AncestorSlots { } } -extension _AncestorSlots: Equatable { +extension _AncestorHashSlots: Equatable { @inlinable @inline(__always) internal static func ==(left: Self, right: Self) -> Bool { left.path == right.path } } -extension _AncestorSlots { +extension _AncestorHashSlots { @inlinable @inline(__always) internal static var empty: Self { Self(0) } } -extension _AncestorSlots { +extension _AncestorHashSlots { /// Return or set the slot value at the specified level. /// If this is used to mutate the collection, then the original value /// on the given level must be zero. @inlinable @inline(__always) - internal subscript(_ level: _Level) -> _Slot { + internal subscript(_ level: _HashLevel) -> _HashSlot { get { assert(level.shift < UInt.bitWidth) - return _Slot((path &>> level.shift) & _Bucket.bitMask) + return _HashSlot((path &>> level.shift) & _Bucket.bitMask) } set { assert(newValue._value < _Bitmap.capacity) @@ -59,7 +59,7 @@ extension _AncestorSlots { } @inlinable @inline(__always) - internal func appending(_ slot: _Slot, at level: _Level) -> Self { + internal func appending(_ slot: _HashSlot, at level: _HashLevel) -> Self { var result = self result[level] = slot return result @@ -67,14 +67,14 @@ extension _AncestorSlots { /// Clear the slot at the specified level, by setting it to zero. @inlinable - internal mutating func clear(_ level: _Level) { + internal mutating func clear(_ level: _HashLevel) { guard level.shift < UInt.bitWidth else { return } path &= ~(_Bucket.bitMask &<< level.shift) } /// Clear all slots at or below the specified level, by setting them to zero. @inlinable - internal mutating func clear(atOrBelow level: _Level) { + internal mutating func clear(atOrBelow level: _HashLevel) { guard level.shift < UInt.bitWidth else { return } path &= ~(UInt.max &<< level.shift) } @@ -82,16 +82,16 @@ extension _AncestorSlots { /// Truncate this path to the specified level. /// Slots at or beyond the specified level are cleared. @inlinable - internal func truncating(to level: _Level) -> _AncestorSlots { + internal func truncating(to level: _HashLevel) -> _AncestorHashSlots { assert(level.shift <= UInt.bitWidth) guard level.shift < UInt.bitWidth else { return self } - return _AncestorSlots(path & ((1 &<< level.shift) &- 1)) + return _AncestorHashSlots(path & ((1 &<< level.shift) &- 1)) } /// Returns true if this path contains non-zero slots at or beyond the /// specified level, otherwise returns false. @inlinable - internal func hasDataBelow(_ level: _Level) -> Bool { + internal func hasDataBelow(_ level: _HashLevel) -> Bool { guard level.shift < UInt.bitWidth else { return false } return (path &>> level.shift) != 0 } @@ -99,7 +99,7 @@ extension _AncestorSlots { /// Compares this path to `other` up to but not including the specified level. /// Returns true if the path prefixes compare equal, otherwise returns false. @inlinable - internal func isEqual(to other: Self, upTo level: _Level) -> Bool { + internal func isEqual(to other: Self, upTo level: _HashLevel) -> Bool { if level.isAtRoot { return true } if level.isAtBottom { return self == other } let s = UInt(UInt.bitWidth) - level.shift diff --git a/Sources/HashTreeCollections/Node/_Bitmap.swift b/Sources/HashTreeCollections/HashNode/_Bitmap.swift similarity index 95% rename from Sources/HashTreeCollections/Node/_Bitmap.swift rename to Sources/HashTreeCollections/HashNode/_Bitmap.swift index cb06f271..3f366e5c 100644 --- a/Sources/HashTreeCollections/Node/_Bitmap.swift +++ b/Sources/HashTreeCollections/HashNode/_Bitmap.swift @@ -138,12 +138,12 @@ extension _Bitmap { } @inlinable @inline(__always) - internal func slot(of bucket: _Bucket) -> _Slot { - _Slot(_value._rank(ofBit: bucket.value)) + internal func slot(of bucket: _Bucket) -> _HashSlot { + _HashSlot(_value._rank(ofBit: bucket.value)) } @inlinable @inline(__always) - internal func bucket(at slot: _Slot) -> _Bucket { + internal func bucket(at slot: _HashSlot) -> _Bucket { _Bucket(_value._bit(ranked: slot.value)!) } } @@ -182,7 +182,7 @@ extension _Bitmap { extension _Bitmap: Sequence { @usableFromInline - internal typealias Element = (bucket: _Bucket, slot: _Slot) + internal typealias Element = (bucket: _Bucket, slot: _HashSlot) @usableFromInline @frozen @@ -191,7 +191,7 @@ extension _Bitmap: Sequence { internal var bitmap: _Bitmap @usableFromInline - internal var slot: _Slot + internal var slot: _HashSlot @inlinable internal init(_ bitmap: _Bitmap) { diff --git a/Sources/HashTreeCollections/Node/_Bucket.swift b/Sources/HashTreeCollections/HashNode/_Bucket.swift similarity index 100% rename from Sources/HashTreeCollections/Node/_Bucket.swift rename to Sources/HashTreeCollections/HashNode/_Bucket.swift diff --git a/Sources/HashTreeCollections/Node/_Hash.swift b/Sources/HashTreeCollections/HashNode/_Hash.swift similarity index 90% rename from Sources/HashTreeCollections/Node/_Hash.swift rename to Sources/HashTreeCollections/HashNode/_Hash.swift index ad26ab1b..975ba561 100644 --- a/Sources/HashTreeCollections/Node/_Hash.swift +++ b/Sources/HashTreeCollections/HashNode/_Hash.swift @@ -41,7 +41,7 @@ extension _Hash: CustomStringConvertible { // Print hash values in radix 32 & reversed, so that the path in the hash // tree is readily visible. let p = String(value, radix: _Bitmap.capacity, uppercase: true) - let c = _Level.limit + let c = _HashLevel.limit let path = String(repeating: "0", count: Swift.max(0, c - p.count)) + p return String(path.reversed()) } @@ -55,7 +55,7 @@ extension _Hash { extension _Hash { @inlinable - internal subscript(_ level: _Level) -> _Bucket { + internal subscript(_ level: _HashLevel) -> _Bucket { get { assert(!level.isAtBottom) return _Bucket((value &>> level.shift) & _Bucket.bitMask) @@ -75,7 +75,7 @@ extension _Hash { } @inlinable - internal func appending(_ bucket: _Bucket, at level: _Level) -> Self { + internal func appending(_ bucket: _Bucket, at level: _HashLevel) -> Self { assert(value >> level.shift == 0) var copy = self copy[level] = bucket @@ -83,7 +83,7 @@ extension _Hash { } @inlinable - internal func isEqual(to other: _Hash, upTo level: _Level) -> Bool { + internal func isEqual(to other: _Hash, upTo level: _HashLevel) -> Bool { if level.isAtRoot { return true } if level.isAtBottom { return self == other } let s = UInt(UInt.bitWidth) - level.shift diff --git a/Sources/HashTreeCollections/Node/_Level.swift b/Sources/HashTreeCollections/HashNode/_HashLevel.swift similarity index 85% rename from Sources/HashTreeCollections/Node/_Level.swift rename to Sources/HashTreeCollections/HashNode/_HashLevel.swift index afda20c2..4519a54d 100644 --- a/Sources/HashTreeCollections/Node/_Level.swift +++ b/Sources/HashTreeCollections/HashNode/_HashLevel.swift @@ -15,7 +15,7 @@ /// the level always fits in an `UInt8` value. @usableFromInline @frozen -internal struct _Level { +internal struct _HashLevel { /// The bit position within a hash value that begins the hash slice that is /// associated with this level. For collision nodes, this can be larger than /// `UInt.bitWidth`. @@ -35,12 +35,12 @@ internal struct _Level { @inlinable @inline(__always) init(depth: Int) { - assert(depth > 0 && depth < _Level.limit) + assert(depth > 0 && depth < _HashLevel.limit) self.init(shift: UInt(bitPattern: depth * _Bitmap.bitWidth)) } } -extension _Level { +extension _HashLevel { @inlinable @inline(__always) internal static var limit: Int { (_Hash.bitWidth + _Bitmap.bitWidth - 1) / _Bitmap.bitWidth @@ -52,8 +52,8 @@ extension _Level { } @inlinable @inline(__always) - internal static var top: _Level { - _Level(shift: 0) + internal static var top: _HashLevel { + _HashLevel(shift: 0) } /// The bit position within a hash value that begins the hash slice that is @@ -74,26 +74,26 @@ extension _Level { } @inlinable @inline(__always) - internal func descend() -> _Level { + internal func descend() -> _HashLevel { // FIXME: Consider returning nil when we run out of bits - _Level(_shift: _shift &+ Self._step) + _HashLevel(_shift: _shift &+ Self._step) } @inlinable @inline(__always) - internal func ascend() -> _Level { + internal func ascend() -> _HashLevel { assert(!isAtRoot) - return _Level(_shift: _shift &- Self._step) + return _HashLevel(_shift: _shift &- Self._step) } } -extension _Level: Equatable { +extension _HashLevel: Equatable { @inlinable @inline(__always) internal static func ==(left: Self, right: Self) -> Bool { left._shift == right._shift } } -extension _Level: Comparable { +extension _HashLevel: Comparable { @inlinable @inline(__always) internal static func <(left: Self, right: Self) -> Bool { left._shift < right._shift diff --git a/Sources/HashTreeCollections/Node/_Node+Builder.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift similarity index 78% rename from Sources/HashTreeCollections/Node/_Node+Builder.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift index 56045ee5..d8f8131a 100644 --- a/Sources/HashTreeCollections/Node/_Node+Builder.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift @@ -9,36 +9,36 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { @usableFromInline @frozen internal struct Builder { - @usableFromInline typealias Element = _Node.Element + @usableFromInline typealias Element = _HashNode.Element @usableFromInline @frozen internal enum Kind { case empty case item(Element, at: _Bucket) - case node(_Node) - case collisionNode(_Node) + case node(_HashNode) + case collisionNode(_HashNode) } @usableFromInline - internal var level: _Level + internal var level: _HashLevel @usableFromInline internal var kind: Kind @inlinable - internal init(_ level: _Level, _ kind: Kind) { + internal init(_ level: _HashLevel, _ kind: Kind) { self.level = level self.kind = kind } } } -extension _Node.Builder { +extension _HashNode.Builder { @usableFromInline internal func dump() { let head = "Builder(level: \(level.depth), kind: " @@ -46,7 +46,7 @@ extension _Node.Builder { case .empty: print(head + "empty)") case .item(let item, at: let bucket): - print(head + "item(\(_Node._itemString(for: item)), at: \(bucket))") + print(head + "item(\(_HashNode._itemString(for: item)), at: \(bucket))") case .node(let node): print(head + "node)") node.dump() @@ -57,22 +57,22 @@ extension _Node.Builder { } } -extension _Node.Builder { +extension _HashNode.Builder { @inlinable @inline(__always) - internal static func empty(_ level: _Level) -> Self { + internal static func empty(_ level: _HashLevel) -> Self { Self(level, .empty) } @inlinable @inline(__always) internal static func item( - _ level: _Level, _ item: __owned Element, at bucket: _Bucket + _ level: _HashLevel, _ item: __owned Element, at bucket: _Bucket ) -> Self { Self(level, .item(item, at: bucket)) } @inlinable @inline(__always) internal static func node( - _ level: _Level, _ node: __owned _Node + _ level: _HashLevel, _ node: __owned _HashNode ) -> Self { assert(!node.isCollisionNode) return Self(level, .node(node)) @@ -80,14 +80,14 @@ extension _Node.Builder { @inlinable @inline(__always) internal static func collisionNode( - _ level: _Level, _ node: __owned _Node + _ level: _HashLevel, _ node: __owned _HashNode ) -> Self { assert(node.isCollisionNode) return Self(level, .collisionNode(node)) } } -extension _Node.Builder { +extension _HashNode.Builder { @inlinable internal var count: Int { switch kind { @@ -109,9 +109,9 @@ extension _Node.Builder { } } -extension _Node.Builder { +extension _HashNode.Builder { @inlinable - internal init(_ level: _Level, _ node: _Node) { + internal init(_ level: _HashLevel, _ node: _HashNode) { self.level = level if node.count == 0 { kind = .empty @@ -126,7 +126,7 @@ extension _Node.Builder { } @inlinable - internal __consuming func finalize(_ level: _Level) -> _Node { + internal __consuming func finalize(_ level: _HashLevel) -> _HashNode { assert(level.isAtRoot && self.level.isAtRoot) switch kind { case .empty: @@ -141,10 +141,10 @@ extension _Node.Builder { } } -extension _Node { +extension _HashNode { @inlinable internal mutating func applyReplacement( - _ level: _Level, + _ level: _HashLevel, _ replacement: Builder ) -> Element? { assert(level == replacement.level) @@ -164,10 +164,10 @@ extension _Node { } } -extension _Node.Builder { +extension _HashNode.Builder { @inlinable internal mutating func addNewCollision( - _ level: _Level, _ newItem: __owned Element, _ hash: _Hash + _ level: _HashLevel, _ newItem: __owned Element, _ hash: _Hash ) { assert(level == self.level) switch kind { @@ -175,7 +175,7 @@ extension _Node.Builder { kind = .item(newItem, at: hash[level]) case .item(let oldItem, at: let bucket): assert(hash[level] == bucket) - let node = _Node._collisionNode(hash, oldItem, newItem) + let node = _HashNode._collisionNode(hash, oldItem, newItem) kind = .collisionNode(node) case .collisionNode(var node): kind = .empty @@ -190,7 +190,7 @@ extension _Node.Builder { @inlinable internal mutating func addNewItem( - _ level: _Level, _ newItem: __owned Element, at newBucket: _Bucket + _ level: _HashLevel, _ newItem: __owned Element, at newBucket: _Bucket ) { assert(level == self.level) switch kind { @@ -198,7 +198,7 @@ extension _Node.Builder { kind = .item(newItem, at: newBucket) case .item(let oldItem, let oldBucket): assert(oldBucket != newBucket) - let node = _Node._regularNode(oldItem, oldBucket, newItem, newBucket) + let node = _HashNode._regularNode(oldItem, oldBucket, newItem, newBucket) kind = .node(node) case .node(var node): kind = .empty @@ -209,7 +209,7 @@ extension _Node.Builder { // Expansion assert(!level.isAtBottom) self.kind = .empty - node = _Node._regularNode( + node = _HashNode._regularNode( newItem, newBucket, node, node.collisionHash[level]) kind = .node(node) } @@ -217,7 +217,7 @@ extension _Node.Builder { @inlinable internal mutating func addNewChildNode( - _ level: _Level, _ newChild: __owned _Node, at newBucket: _Bucket + _ level: _HashLevel, _ newChild: __owned _HashNode, at newBucket: _Bucket ) { assert(level == self.level) switch self.kind { @@ -230,20 +230,20 @@ extension _Node.Builder { self.kind = .node(._regularNode(newChild, newBucket)) } case let .item(oldItem, oldBucket): - let node = _Node._regularNode(oldItem, oldBucket, newChild, newBucket) + let node = _HashNode._regularNode(oldItem, oldBucket, newChild, newBucket) self.kind = .node(node) case .node(var node): self.kind = .empty let isUnique = node.isUnique() node.ensureUnique( - isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild) + isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild) node.insertChild(newChild, newBucket) self.kind = .node(node) case .collisionNode(var node): // Expansion self.kind = .empty assert(!level.isAtBottom) - node = _Node._regularNode( + node = _HashNode._regularNode( node, node.collisionHash[level], newChild, newBucket) self.kind = .node(node) } @@ -251,7 +251,7 @@ extension _Node.Builder { @inlinable internal mutating func addNewChildBranch( - _ level: _Level, _ newChild: __owned Self, at newBucket: _Bucket + _ level: _HashLevel, _ newChild: __owned Self, at newBucket: _Bucket ) { assert(level == self.level) assert(newChild.level == self.level.descend()) @@ -267,7 +267,7 @@ extension _Node.Builder { @inlinable internal static func childBranch( - _ level: _Level, _ child: Self, at bucket: _Bucket + _ level: _HashLevel, _ child: Self, at bucket: _Bucket ) -> Self { assert(child.level == level.descend()) switch child.kind { @@ -285,25 +285,25 @@ extension _Node.Builder { } } -extension _Node.Builder { +extension _HashNode.Builder { @inlinable internal mutating func copyCollisions( - from source: _Node.UnsafeHandle, - upTo end: _Slot + from source: _HashNode.UnsafeHandle, + upTo end: _HashSlot ) { assert(isEmpty) assert(source.isCollisionNode) assert(end < source.itemsEndSlot) let h = source.collisionHash - for slot: _Slot in stride(from: .zero, to: end, by: 1) { + for slot: _HashSlot in stride(from: .zero, to: end, by: 1) { self.addNewCollision(self.level, source[item: slot], h) } } @inlinable internal mutating func copyItems( - _ level: _Level, - from source: _Node.UnsafeHandle, + _ level: _HashLevel, + from source: _HashNode.UnsafeHandle, upTo end: _Bucket ) { assert(level == self.level) @@ -316,8 +316,8 @@ extension _Node.Builder { @inlinable internal mutating func copyItemsAndChildren( - _ level: _Level, - from source: _Node.UnsafeHandle, + _ level: _HashLevel, + from source: _HashNode.UnsafeHandle, upTo end: _Bucket ) { assert(level == self.level) @@ -332,11 +332,11 @@ extension _Node.Builder { } } -extension _Node.Builder { +extension _HashNode.Builder { @inlinable internal func mapValues( _ transform: (Element) -> Value2 - ) -> _Node.Builder { + ) -> _HashNode.Builder { switch kind { case .empty: return .empty(level) @@ -351,9 +351,9 @@ extension _Node.Builder { } @inlinable - internal func mapValuesToVoid() -> _Node.Builder { + internal func mapValuesToVoid() -> _HashNode.Builder { if Value.self == Void.self { - return unsafeBitCast(self, to: _Node.Builder.self) + return unsafeBitCast(self, to: _HashNode.Builder.self) } return mapValues { _ in () } } diff --git a/Sources/HashTreeCollections/Node/_Node+Debugging.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift similarity index 91% rename from Sources/HashTreeCollections/Node/_Node+Debugging.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift index 094a2476..75d7c1bf 100644 --- a/Sources/HashTreeCollections/Node/_Node+Debugging.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift @@ -11,7 +11,7 @@ import _CollectionsUtilities -extension _Node { +extension _HashNode { @usableFromInline internal func dump( iterationOrder: Bool = false, @@ -32,23 +32,23 @@ extension _Node { } } -extension _Node.Storage { +extension _HashNode.Storage { @usableFromInline final internal func dump(iterationOrder: Bool = false) { UnsafeHandle.read(self) { $0.dump(iterationOrder: iterationOrder) } } } -extension _Node { +extension _HashNode { internal static func _itemString(for item: Element) -> String { let hash = _Hash(item.key).description return "hash: \(hash), key: \(item.key), value: \(item.value)" } } -extension _Node.UnsafeHandle { - internal func _itemString(at slot: _Slot) -> String { +extension _HashNode.UnsafeHandle { + internal func _itemString(at slot: _HashSlot) -> String { let item = self[item: slot] - return _Node._itemString(for: item) + return _HashNode._itemString(for: item) } @usableFromInline @@ -96,8 +96,8 @@ extension _Node.UnsafeHandle { print("\(restPrefix)[\(slot)] \(_itemString(at: slot))") } } else { - var itemSlot: _Slot = .zero - var childSlot: _Slot = .zero + var itemSlot: _HashSlot = .zero + var childSlot: _HashSlot = .zero for b in 0 ..< UInt(_Bitmap.capacity) { let bucket = _Bucket(b) let bucketStr = "#\(String(b, radix: _Bitmap.capacity, uppercase: true))" diff --git a/Sources/HashTreeCollections/Node/_Node+Initializers.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift similarity index 80% rename from Sources/HashTreeCollections/Node/_Node+Initializers.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift index c6a17c3b..f01a3bd2 100644 --- a/Sources/HashTreeCollections/Node/_Node+Initializers.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift @@ -11,10 +11,10 @@ import _CollectionsUtilities -extension _Node { +extension _HashNode { @inlinable @inline(__always) - internal static func _emptyNode() -> _Node { - _Node(storage: _emptySingleton, count: 0) + internal static func _emptyNode() -> _HashNode { + _HashNode(storage: _emptySingleton, count: 0) } @inlinable @@ -22,8 +22,8 @@ extension _Node { _ hash: _Hash, _ item1: __owned Element, _ item2: __owned Element - ) -> _Node { - let node = _Node.allocateCollision(count: 2, hash) { items in + ) -> _HashNode { + let node = _HashNode.allocateCollision(count: 2, hash) { items in items.initializeElement(at: 1, to: item1) items.initializeElement(at: 0, to: item2) }.node @@ -36,8 +36,8 @@ extension _Node { _ hash: _Hash, _ item1: __owned Element, _ inserter2: (UnsafeMutablePointer) -> Void - ) -> _Node { - let node = _Node.allocateCollision(count: 2, hash) { items in + ) -> _HashNode { + let node = _HashNode.allocateCollision(count: 2, hash) { items in items.initializeElement(at: 1, to: item1) inserter2(items.baseAddress.unsafelyUnwrapped) }.node @@ -49,8 +49,8 @@ extension _Node { internal static func _regularNode( _ item: __owned Element, _ bucket: _Bucket - ) -> _Node { - let r = _Node.allocate( + ) -> _HashNode { + let r = _HashNode.allocate( itemMap: _Bitmap(bucket), childMap: .empty, count: 1 @@ -68,7 +68,7 @@ extension _Node { _ bucket1: _Bucket, _ item2: __owned Element, _ bucket2: _Bucket - ) -> _Node { + ) -> _HashNode { _regularNode( item1, bucket1, { $0.initialize(to: item2) }, bucket2).node @@ -80,19 +80,19 @@ extension _Node { _ bucket1: _Bucket, _ inserter2: (UnsafeMutablePointer) -> Void, _ bucket2: _Bucket - ) -> (node: _Node, slot1: _Slot, slot2: _Slot) { + ) -> (node: _HashNode, slot1: _HashSlot, slot2: _HashSlot) { assert(bucket1 != bucket2) - let r = _Node.allocate( + let r = _HashNode.allocate( itemMap: _Bitmap(bucket1, bucket2), childMap: .empty, count: 2 - ) { children, items -> (_Slot, _Slot) in + ) { children, items -> (_HashSlot, _HashSlot) in assert(items.count == 2 && children.count == 0) let i1 = bucket1 < bucket2 ? 1 : 0 let i2 = 1 &- i1 items.initializeElement(at: i1, to: item1) inserter2(items.baseAddress.unsafelyUnwrapped + i2) - return (_Slot(i2), _Slot(i1)) // Note: swapped + return (_HashSlot(i2), _HashSlot(i1)) // Note: swapped } r.node._invariantCheck() return (r.node, r.result.0, r.result.1) @@ -100,10 +100,10 @@ extension _Node { @inlinable internal static func _regularNode( - _ child: __owned _Node, + _ child: __owned _HashNode, _ bucket: _Bucket - ) -> _Node { - let r = _Node.allocate( + ) -> _HashNode { + let r = _HashNode.allocate( itemMap: .empty, childMap: _Bitmap(bucket), count: child.count @@ -119,9 +119,9 @@ extension _Node { internal static func _regularNode( _ item: __owned Element, _ itemBucket: _Bucket, - _ child: __owned _Node, + _ child: __owned _HashNode, _ childBucket: _Bucket - ) -> _Node { + ) -> _HashNode { _regularNode( { $0.initialize(to: item) }, itemBucket, child, childBucket) @@ -131,11 +131,11 @@ extension _Node { internal static func _regularNode( _ inserter: (UnsafeMutablePointer) -> Void, _ itemBucket: _Bucket, - _ child: __owned _Node, + _ child: __owned _HashNode, _ childBucket: _Bucket - ) -> _Node { + ) -> _HashNode { assert(itemBucket != childBucket) - let r = _Node.allocate( + let r = _HashNode.allocate( itemMap: _Bitmap(itemBucket), childMap: _Bitmap(childBucket), count: child.count &+ 1 @@ -150,13 +150,13 @@ extension _Node { @inlinable internal static func _regularNode( - _ child1: __owned _Node, + _ child1: __owned _HashNode, _ child1Bucket: _Bucket, - _ child2: __owned _Node, + _ child2: __owned _HashNode, _ child2Bucket: _Bucket - ) -> _Node { + ) -> _HashNode { assert(child1Bucket != child2Bucket) - let r = _Node.allocate( + let r = _HashNode.allocate( itemMap: .empty, childMap: _Bitmap(child1Bucket, child2Bucket), count: child1.count &+ child2.count @@ -170,19 +170,19 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal static func build( - level: _Level, + level: _HashLevel, item1: __owned Element, _ hash1: _Hash, item2 inserter2: (UnsafeMutablePointer) -> Void, _ hash2: _Hash - ) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) { + ) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) { assert(hash1.isEqual(to: hash2, upTo: level.ascend())) if hash1 == hash2 { let top = _collisionNode(hash1, item1, inserter2) - return (top, top.unmanaged, _Slot(0), _Slot(1)) + return (top, top.unmanaged, _HashSlot(0), _HashSlot(1)) } let r = _build( level: level, item1: item1, hash1, item2: inserter2, hash2) @@ -191,12 +191,12 @@ extension _Node { @inlinable internal static func _build( - level: _Level, + level: _HashLevel, item1: __owned Element, _ hash1: _Hash, item2 inserter2: (UnsafeMutablePointer) -> Void, _ hash2: _Hash - ) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) { + ) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) { assert(hash1 != hash2) let b1 = hash1[level] let b2 = hash2[level] @@ -213,12 +213,12 @@ extension _Node { @inlinable internal static func build( - level: _Level, + level: _HashLevel, item1 inserter1: (UnsafeMutablePointer) -> Void, _ hash1: _Hash, - child2: __owned _Node, + child2: __owned _HashNode, _ hash2: _Hash - ) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) { + ) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) { assert(child2.isCollisionNode) assert(hash1 != hash2) let b1 = hash1[level] @@ -236,12 +236,12 @@ extension _Node { @inlinable internal static func build( - level: _Level, - child1: __owned _Node, + level: _HashLevel, + child1: __owned _HashNode, _ hash1: _Hash, - child2: __owned _Node, + child2: __owned _HashNode, _ hash2: _Hash - ) -> _Node { + ) -> _HashNode { assert(child1.isCollisionNode) assert(child2.isCollisionNode) assert(hash1 != hash2) diff --git a/Sources/HashTreeCollections/Node/_Node+Invariants.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Invariants.swift similarity index 89% rename from Sources/HashTreeCollections/Node/_Node+Invariants.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Invariants.swift index 570df8cc..7b488404 100644 --- a/Sources/HashTreeCollections/Node/_Node+Invariants.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Invariants.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -extension _StorageHeader { +extension _HashNodeHeader { #if COLLECTIONS_INTERNAL_CHECKS @usableFromInline @inline(never) internal func _invariantCheck() { @@ -27,7 +27,7 @@ extension _StorageHeader { #endif } -extension _Node { +extension _HashNode { #if COLLECTIONS_INTERNAL_CHECKS @usableFromInline @inline(never) internal func _invariantCheck() { @@ -43,7 +43,7 @@ extension _Node { assert($0.collisionHash == _Hash($0[item: .zero].key)) } else { - let childBytes = $0.childCount * MemoryLayout<_Node>.stride + let childBytes = $0.childCount * MemoryLayout<_HashNode>.stride assert(itemBytes + $0.bytesFree + childBytes == $0.byteCapacity) } @@ -63,7 +63,7 @@ extension _Node { #if COLLECTIONS_INTERNAL_CHECKS @inlinable @inline(never) - internal func _fullInvariantCheck(_ level: _Level, _ path: _Hash) { + internal func _fullInvariantCheck(_ level: _HashLevel, _ path: _Hash) { _invariantCheck() read { precondition(level.isAtRoot || !hasSingletonItem) @@ -79,8 +79,8 @@ extension _Node { precondition(_Hash(item.key) == hash) } } - var itemSlot: _Slot = .zero - var childSlot: _Slot = .zero + var itemSlot: _HashSlot = .zero + var childSlot: _HashSlot = .zero for b in 0 ..< UInt(_Bitmap.capacity) { let bucket = _Bucket(b) let path = path.appending(bucket, at: level) @@ -101,7 +101,7 @@ extension _Node { } #else @inlinable @inline(__always) - internal func _fullInvariantCheck(_ level: _Level, _ path: _Hash) {} + internal func _fullInvariantCheck(_ level: _HashLevel, _ path: _Hash) {} #endif } diff --git a/Sources/HashTreeCollections/Node/_Node+Lookups.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Lookups.swift similarity index 86% rename from Sources/HashTreeCollections/Node/_Node+Lookups.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Lookups.swift index 7185509b..88c3eca3 100644 --- a/Sources/HashTreeCollections/Node/_Node+Lookups.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Lookups.swift @@ -11,20 +11,20 @@ // MARK: Node-level lookup operations -extension _Node { +extension _HashNode { @inlinable internal func find( - _ level: _Level, _ key: Key, _ hash: _Hash - ) -> (descend: Bool, slot: _Slot)? { + _ level: _HashLevel, _ key: Key, _ hash: _Hash + ) -> (descend: Bool, slot: _HashSlot)? { read { $0.find(level, key, hash) } } } -extension _Node.UnsafeHandle { +extension _HashNode.UnsafeHandle { @inlinable internal func find( - _ level: _Level, _ key: Key, _ hash: _Hash - ) -> (descend: Bool, slot: _Slot)? { + _ level: _HashLevel, _ key: Key, _ hash: _Hash + ) -> (descend: Bool, slot: _HashSlot)? { guard !isCollisionNode else { let r = _findInCollision(level, key, hash) guard r.code == 0 else { return nil } @@ -45,8 +45,8 @@ extension _Node.UnsafeHandle { @inlinable @inline(never) internal func _findInCollision( - _ level: _Level, _ key: Key, _ hash: _Hash - ) -> (code: Int, slot: _Slot) { + _ level: _HashLevel, _ key: Key, _ hash: _Hash + ) -> (code: Int, slot: _HashSlot) { assert(isCollisionNode) if !level.isAtBottom { if hash != self.collisionHash { return (2, .zero) } @@ -54,7 +54,7 @@ extension _Node.UnsafeHandle { // Note: this searches the items in reverse insertion order. guard let slot = reverseItems.firstIndex(where: { $0.key == key }) else { return (1, self.itemsEndSlot) } - return (0, _Slot(itemCount &- 1 &- slot)) + return (0, _HashSlot(itemCount &- 1 &- slot)) } } @@ -75,7 +75,7 @@ internal enum _FindResult { /// /// If the current node is a collision node, then the bucket value is /// set to `_Bucket.invalid`. - case found(_Bucket, _Slot) + case found(_Bucket, _HashSlot) /// The item we're looking for is not currently inside the subtree rooted at /// this node. @@ -85,7 +85,7 @@ internal enum _FindResult { /// /// When the node is a collision node, the `insertCollision` case is returned /// instead of this one. - case insert(_Bucket, _Slot) + case insert(_Bucket, _HashSlot) /// The item we're looking for is not currently inside the subtree rooted at /// this collision node. @@ -103,7 +103,7 @@ internal enum _FindResult { /// it with a new child node. /// /// (This case is never returned if the current node is a collision node.) - case spawnChild(_Bucket, _Slot) + case spawnChild(_Bucket, _HashSlot) /// The item we're looking for is not in this subtree. /// @@ -125,22 +125,22 @@ internal enum _FindResult { /// bucket & slot. /// /// (This case is never returned if the current node is a collision node.) - case descend(_Bucket, _Slot) + case descend(_Bucket, _HashSlot) } -extension _Node { +extension _HashNode { @inlinable internal func findForInsertion( - _ level: _Level, _ key: Key, _ hash: _Hash + _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> _FindResult { read { $0.findForInsertion(level, key, hash) } } } -extension _Node.UnsafeHandle { +extension _HashNode.UnsafeHandle { @inlinable internal func findForInsertion( - _ level: _Level, _ key: Key, _ hash: _Hash + _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> _FindResult { guard !isCollisionNode else { let r = _findInCollision(level, key, hash) @@ -172,9 +172,9 @@ extension _Node.UnsafeHandle { // MARK: Subtree-level lookup operations -extension _Node { +extension _HashNode { @inlinable - internal func get(_ level: _Level, _ key: Key, _ hash: _Hash) -> Value? { + internal func get(_ level: _HashLevel, _ key: Key, _ hash: _Hash) -> Value? { var node = unmanaged var level = level while true { @@ -191,10 +191,10 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal func containsKey( - _ level: _Level, _ key: Key, _ hash: _Hash + _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> Bool { var node = unmanaged var level = level @@ -208,11 +208,11 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal func lookup( - _ level: _Level, _ key: Key, _ hash: _Hash - ) -> (node: _UnmanagedNode, slot: _Slot)? { + _ level: _HashLevel, _ key: Key, _ hash: _Hash + ) -> (node: _UnmanagedHashNode, slot: _HashSlot)? { var node = unmanaged var level = level while true { @@ -229,10 +229,10 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal func position( - forKey key: Key, _ level: _Level, _ hash: _Hash + forKey key: Key, _ level: _HashLevel, _ hash: _Hash ) -> Int? { guard let r = find(level, key, hash) else { return nil } guard r.descend else { return r.slot.value } @@ -253,7 +253,7 @@ extension _Node { var itemsToSkip = position let itemCount = $0.itemCount if itemsToSkip < itemCount { - return $0[item: _Slot(itemsToSkip)] + return $0[item: _HashSlot(itemsToSkip)] } itemsToSkip -= itemCount let children = $0.children diff --git a/Sources/HashTreeCollections/Node/_Node+Primitive Insertions.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Insertions.swift similarity index 88% rename from Sources/HashTreeCollections/Node/_Node+Primitive Insertions.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Primitive Insertions.swift index d1f17675..d5630eb1 100644 --- a/Sources/HashTreeCollections/Node/_Node+Primitive Insertions.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Insertions.swift @@ -11,7 +11,7 @@ // MARK: Node-level insertion operations -extension _Node.UnsafeHandle { +extension _HashNode.UnsafeHandle { /// Make room for a new item at `slot` corresponding to `bucket`. /// There must be enough free space in the node to fit the new item. /// @@ -23,7 +23,7 @@ extension _Node.UnsafeHandle { /// initialize this memory. @inlinable internal func _makeRoomForNewItem( - at slot: _Slot, _ bucket: _Bucket + at slot: _HashSlot, _ bucket: _Bucket ) -> UnsafeMutablePointer { assertMutable() let c = itemCount @@ -59,25 +59,25 @@ extension _Node.UnsafeHandle { /// `childMap` must not yet reflect the insertion at the time this /// function is called. This method does not update `childMap`. @inlinable - internal func _insertChild(_ child: __owned _Node, at slot: _Slot) { + internal func _insertChild(_ child: __owned _HashNode, at slot: _HashSlot) { assertMutable() assert(!isCollisionNode) let c = childMap.count assert(slot.value <= c) - let stride = MemoryLayout<_Node>.stride + let stride = MemoryLayout<_HashNode>.stride assert(bytesFree >= stride) bytesFree &-= stride - _memory.bindMemory(to: _Node.self, capacity: c &+ 1) + _memory.bindMemory(to: _HashNode.self, capacity: c &+ 1) let q = _childrenStart + slot.value (q + 1).moveInitialize(from: q, count: c &- slot.value) q.initialize(to: child) } } -extension _Node { +extension _HashNode { @inlinable @inline(__always) internal mutating func insertItem( _ item: __owned Element, at bucket: _Bucket @@ -88,7 +88,7 @@ extension _Node { @inlinable @inline(__always) internal mutating func insertItem( - _ item: __owned Element, at slot: _Slot, _ bucket: _Bucket + _ item: __owned Element, at slot: _HashSlot, _ bucket: _Bucket ) { self.count &+= 1 update { @@ -101,7 +101,7 @@ extension _Node { /// node to fit the new child. @inlinable internal mutating func insertChild( - _ child: __owned _Node, _ bucket: _Bucket + _ child: __owned _HashNode, _ bucket: _Bucket ) { count &+= child.count update { diff --git a/Sources/HashTreeCollections/Node/_Node+Primitive Removals.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Removals.swift similarity index 88% rename from Sources/HashTreeCollections/Node/_Node+Primitive Removals.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Primitive Removals.swift index 367bf787..424a9334 100644 --- a/Sources/HashTreeCollections/Node/_Node+Primitive Removals.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Removals.swift @@ -11,7 +11,7 @@ // MARK: Node-level removal operations -extension _Node.UnsafeHandle { +extension _HashNode.UnsafeHandle { /// Remove and return the item at `slot`, increasing the amount of free /// space available in the node. /// @@ -19,7 +19,7 @@ extension _Node.UnsafeHandle { /// function is called. This method does not update `itemMap`. @inlinable internal func _removeItem( - at slot: _Slot, + at slot: _HashSlot, by remover: (UnsafeMutablePointer) -> R ) -> R { assertMutable() @@ -46,13 +46,13 @@ extension _Node.UnsafeHandle { /// `childMap` must not yet reflect the removal at the time this /// function is called. This method does not update `childMap`. @inlinable - internal func _removeChild(at slot: _Slot) -> _Node { + internal func _removeChild(at slot: _HashSlot) -> _HashNode { assertMutable() assert(!isCollisionNode) let count = childCount assert(slot.value < count) - bytesFree &+= MemoryLayout<_Node>.stride + bytesFree &+= MemoryLayout<_HashNode>.stride let q = _childrenStart + slot.value let child = q.move() @@ -61,7 +61,7 @@ extension _Node.UnsafeHandle { } } -extension _Node { +extension _HashNode { @inlinable internal mutating func removeItem( at bucket: _Bucket @@ -72,7 +72,7 @@ extension _Node { @inlinable internal mutating func removeItem( - at bucket: _Bucket, _ slot: _Slot + at bucket: _Bucket, _ slot: _HashSlot ) -> Element { removeItem(at: bucket, slot, by: { $0.move() }) } @@ -84,7 +84,7 @@ extension _Node { /// storage slot corresponding to the item to be removed. @inlinable internal mutating func removeItem( - at bucket: _Bucket, _ slot: _Slot, + at bucket: _Bucket, _ slot: _HashSlot, by remover: (UnsafeMutablePointer) -> R ) -> R { defer { _invariantCheck() } @@ -106,10 +106,10 @@ extension _Node { @inlinable internal mutating func removeChild( - at bucket: _Bucket, _ slot: _Slot - ) -> _Node { + at bucket: _Bucket, _ slot: _HashSlot + ) -> _HashNode { assert(!isCollisionNode) - let child: _Node = update { + let child: _HashNode = update { assert($0.childMap.contains(bucket)) assert($0.childMap.slot(of: bucket) == slot) let child = $0._removeChild(at: slot) @@ -135,9 +135,9 @@ extension _Node { } @inlinable - internal mutating func removeSingletonChild() -> _Node { + internal mutating func removeSingletonChild() -> _HashNode { defer { _invariantCheck() } - let child: _Node = update { + let child: _HashNode = update { assert($0.hasSingletonChild) let child = $0._removeChild(at: .zero) $0.childMap = .empty diff --git a/Sources/HashTreeCollections/Node/_Node+Primitive Replacement.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Replacement.swift similarity index 87% rename from Sources/HashTreeCollections/Node/_Node+Primitive Replacement.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Primitive Replacement.swift index a687a3ce..dee317d7 100644 --- a/Sources/HashTreeCollections/Node/_Node+Primitive Replacement.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Replacement.swift @@ -9,10 +9,10 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { @inlinable internal mutating func replaceItem( - at bucket: _Bucket, _ slot: _Slot, with item: __owned Element + at bucket: _Bucket, _ slot: _HashSlot, with item: __owned Element ) { update { assert($0.isCollisionNode || $0.itemMap.contains(bucket)) @@ -24,7 +24,7 @@ extension _Node { @inlinable internal mutating func replaceChild( - at bucket: _Bucket, with child: __owned _Node + at bucket: _Bucket, with child: __owned _HashNode ) -> Int { let slot = read { $0.childMap.slot(of: bucket) } return replaceChild(at: bucket, slot, with: child) @@ -32,7 +32,7 @@ extension _Node { @inlinable internal mutating func replaceChild( - at bucket: _Bucket, _ slot: _Slot, with child: __owned _Node + at bucket: _Bucket, _ slot: _HashSlot, with child: __owned _HashNode ) -> Int { let delta: Int = update { assert(!$0.isCollisionNode) @@ -49,9 +49,9 @@ extension _Node { @inlinable internal func replacingChild( - _ level: _Level, + _ level: _HashLevel, at bucket: _Bucket, - _ slot: _Slot, + _ slot: _HashSlot, with child: __owned Builder ) -> Builder { assert(child.level == level.descend()) @@ -67,7 +67,7 @@ extension _Node { if hasSingletonChild { return .item(level, item, at: bucket) } - var node = self.copy(withFreeSpace: _Node.spaceForInlinedChild) + var node = self.copy(withFreeSpace: _HashNode.spaceForInlinedChild) _ = node.removeChild(at: bucket, slot) node.insertItem(item, at: bucket) node._invariantCheck() diff --git a/Sources/HashTreeCollections/Node/_Node+Storage.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift similarity index 82% rename from Sources/HashTreeCollections/Node/_Node+Storage.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift index 44308155..00299cd0 100644 --- a/Sources/HashTreeCollections/Node/_Node+Storage.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift @@ -14,30 +14,30 @@ import _CollectionsUtilities /// A base representation of a hash tree node, capturing functionality /// independent of the `Key` and `Value` types. @usableFromInline -internal typealias _RawStorage = ManagedBuffer<_StorageHeader, _RawNode> +internal typealias _RawHashStorage = ManagedBuffer<_HashNodeHeader, _RawHashNode> /// Type-punned storage for the singleton root node used in empty hash trees /// (of all `Key` and `Value` types). /// -/// `_Node` is carefully defined to use a `_RawStorage` reference as its +/// `_HashNode` is carefully defined to use a `_RawHashStorage` reference as its /// storage variable, so that this can work. (The only reason we need the -/// `_Node.Storage` subclass is to allow storage instances to properly clean up -/// after themselves in their `deinit` method.) +/// `_HashNode.Storage` subclass is to allow storage instances to properly +/// clean up after themselves in their `deinit` method.) @usableFromInline -internal let _emptySingleton: _RawStorage = _RawStorage.create( +internal let _emptySingleton: _RawHashStorage = _RawHashStorage.create( minimumCapacity: 0, - makingHeaderWith: { _ in _StorageHeader(byteCapacity: 0) }) + makingHeaderWith: { _ in _HashNodeHeader(byteCapacity: 0) }) -extension _Node { +extension _HashNode { /// Instances of this class hold (tail-allocated) storage for individual /// nodes in a hash tree. @usableFromInline - internal final class Storage: _RawStorage { + internal final class Storage: _RawHashStorage { @usableFromInline internal typealias Element = (key: Key, value: Value) @usableFromInline - internal typealias UnsafeHandle = _Node.UnsafeHandle + internal typealias UnsafeHandle = _HashNode.UnsafeHandle deinit { UnsafeHandle.update(self) { handle in @@ -48,13 +48,13 @@ extension _Node { } } -extension _Node.Storage { +extension _HashNode.Storage { @inlinable - internal static func allocate(byteCapacity: Int) -> _Node.Storage { + internal static func allocate(byteCapacity: Int) -> _HashNode.Storage { assert(byteCapacity >= 0) let itemStride = MemoryLayout.stride - let childStride = MemoryLayout<_Node>.stride + let childStride = MemoryLayout<_HashNode>.stride let unit = Swift.max(itemStride, childStride) // Round up request to nearest power-of-two number of units. @@ -69,16 +69,16 @@ extension _Node.Storage { var bytes = unit * capacityInUnits._roundUpToPowerOfTwo() let itemAlignment = MemoryLayout.alignment - let childAlignment = MemoryLayout<_Node>.alignment + let childAlignment = MemoryLayout<_HashNode>.alignment if itemAlignment > childAlignment { // Make sure we always have enough room to properly align trailing items. bytes += itemAlignment - childAlignment } - let object = _Node.Storage.create( + let object = _HashNode.Storage.create( minimumCapacity: (bytes &+ childStride &- 1) / childStride ) { buffer in - _StorageHeader(byteCapacity: buffer.capacity * childStride) + _HashNodeHeader(byteCapacity: buffer.capacity * childStride) } object.withUnsafeMutablePointers { header, elements in @@ -90,11 +90,11 @@ extension _Node.Storage { header.pointee._bytesFree = header.pointee._byteCapacity assert(byteCapacity <= header.pointee.byteCapacity) } - return unsafeDowncast(object, to: _Node.Storage.self) + return unsafeDowncast(object, to: _HashNode.Storage.self) } } -extension _Node { +extension _HashNode { @inlinable @inline(__always) internal static var spaceForNewItem: Int { MemoryLayout.stride @@ -102,7 +102,7 @@ extension _Node { @inlinable @inline(__always) internal static var spaceForNewChild: Int { - MemoryLayout<_Node>.stride + MemoryLayout<_HashNode>.stride } @inlinable @inline(__always) @@ -151,23 +151,23 @@ extension _Node { count: Int, extraBytes: Int = 0, initializingWith initializer: ( - UnsafeMutableBufferPointer<_Node>, UnsafeMutableBufferPointer + UnsafeMutableBufferPointer<_HashNode>, UnsafeMutableBufferPointer ) -> R - ) -> (node: _Node, result: R) { + ) -> (node: _HashNode, result: R) { assert(extraBytes >= 0) assert(itemMap.isDisjoint(with: childMap)) // No collisions let itemCount = itemMap.count let childCount = childMap.count let itemStride = MemoryLayout.stride - let childStride = MemoryLayout<_Node>.stride + let childStride = MemoryLayout<_HashNode>.stride let itemBytes = itemCount * itemStride let childBytes = childCount * childStride let occupiedBytes = itemBytes &+ childBytes let storage = Storage.allocate( byteCapacity: occupiedBytes &+ extraBytes) - var node = _Node(storage: storage, count: count) + var node = _HashNode(storage: storage, count: count) let result: R = node.update { $0.itemMap = itemMap $0.childMap = childMap @@ -176,7 +176,7 @@ extension _Node { $0.bytesFree &-= occupiedBytes let childStart = $0._memory - .bindMemory(to: _Node.self, capacity: childCount) + .bindMemory(to: _HashNode.self, capacity: childCount) let itemStart = ($0._memory + ($0.byteCapacity - itemBytes)) .bindMemory(to: Element.self, capacity: itemCount) @@ -193,15 +193,15 @@ extension _Node { _ hash: _Hash, extraBytes: Int = 0, initializingWith initializer: (UnsafeMutableBufferPointer) -> R - ) -> (node: _Node, result: R) { + ) -> (node: _HashNode, result: R) { assert(count >= 2) assert(extraBytes >= 0) let itemBytes = count * MemoryLayout.stride let hashBytes = MemoryLayout<_Hash>.stride let bytes = itemBytes &+ hashBytes - assert(MemoryLayout<_Hash>.alignment <= MemoryLayout<_RawNode>.alignment) + assert(MemoryLayout<_Hash>.alignment <= MemoryLayout<_RawHashNode>.alignment) let storage = Storage.allocate(byteCapacity: bytes &+ extraBytes) - var node = _Node(storage: storage, count: count) + var node = _HashNode(storage: storage, count: count) let result: R = node.update { $0.itemMap = _Bitmap(bitPattern: count) $0.childMap = $0.itemMap @@ -221,7 +221,7 @@ extension _Node { @inlinable @inline(never) - internal func copy(withFreeSpace space: Int = 0) -> _Node { + internal func copy(withFreeSpace space: Int = 0) -> _HashNode { assert(space >= 0) if isCollisionNode { diff --git a/Sources/HashTreeCollections/Node/_Node+Structural compactMapValues.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural compactMapValues.swift similarity index 89% rename from Sources/HashTreeCollections/Node/_Node+Structural compactMapValues.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural compactMapValues.swift index a52b4384..c5abe96c 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural compactMapValues.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural compactMapValues.swift @@ -9,14 +9,14 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { @inlinable internal func compactMapValues( - _ level: _Level, + _ level: _HashLevel, _ transform: (Value) throws -> T? - ) rethrows -> _Node.Builder { + ) rethrows -> _HashNode.Builder { return try self.read { - var result: _Node.Builder = .empty(level) + var result: _HashNode.Builder = .empty(level) if isCollisionNode { let items = $0.reverseItems diff --git a/Sources/HashTreeCollections/Node/_Node+Structural filter.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural filter.swift similarity index 94% rename from Sources/HashTreeCollections/Node/_Node+Structural filter.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural filter.swift index 93cc75c9..45b8293b 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural filter.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural filter.swift @@ -9,10 +9,10 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { @inlinable internal func filter( - _ level: _Level, + _ level: _HashLevel, _ isIncluded: (Element) throws -> Bool ) rethrows -> Builder? { guard !isCollisionNode else { @@ -57,14 +57,14 @@ extension _Node { @inlinable @inline(never) internal func _filter_slow( - _ level: _Level, + _ level: _HashLevel, _ isIncluded: (Element) throws -> Bool ) rethrows -> Builder? { try self.read { var result: Builder = .empty(level) var removing = false - for slot: _Slot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) { + for slot: _HashSlot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) { let p = $0.itemPtr(at: slot) let include = try isIncluded(p.pointee) if include, removing { diff --git a/Sources/HashTreeCollections/Node/_Node+Structural intersection.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural intersection.swift similarity index 95% rename from Sources/HashTreeCollections/Node/_Node+Structural intersection.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural intersection.swift index 72adda82..511a6c2e 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural intersection.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural intersection.swift @@ -9,12 +9,12 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { @inlinable internal func intersection( - _ level: _Level, - _ other: _Node - ) -> _Node? { + _ level: _HashLevel, + _ other: _HashNode + ) -> _HashNode? { assert(level.isAtRoot) let builder = _intersection(level, other) guard let builder = builder else { return nil } @@ -25,8 +25,8 @@ extension _Node { @inlinable internal func _intersection( - _ level: _Level, - _ other: _Node + _ level: _HashLevel, + _ other: _HashNode ) -> Builder? { if self.raw.storage === other.raw.storage { return nil } @@ -106,8 +106,8 @@ extension _Node { @inlinable @inline(never) internal func _intersection_slow( - _ level: _Level, - _ other: _Node + _ level: _HashLevel, + _ other: _HashNode ) -> Builder? { let lc = self.isCollisionNode let rc = other.isCollisionNode @@ -119,7 +119,7 @@ extension _Node { var removing = false let ritems = r.reverseItems - for lslot: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { + for lslot: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { let lp = l.itemPtr(at: lslot) let include = ritems.contains { $0.key == lp.pointee.key } if include, removing { diff --git a/Sources/HashTreeCollections/Node/_Node+Structural isDisjoint.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isDisjoint.swift similarity index 96% rename from Sources/HashTreeCollections/Node/_Node+Structural isDisjoint.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural isDisjoint.swift index 80eb8ecf..539d55b3 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural isDisjoint.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isDisjoint.swift @@ -9,13 +9,13 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { /// Returns true if `self` contains a disjoint set of keys than `other`. /// Otherwise, returns false. @inlinable @inline(never) internal func isDisjoint( - _ level: _Level, - with other: _Node + _ level: _HashLevel, + with other: _HashNode ) -> Bool { if self.count == 0 || other.count == 0 { return true } if self.raw.storage === other.raw.storage { return false } @@ -72,8 +72,8 @@ extension _Node { @inlinable @inline(never) internal func _isDisjointCollision( - _ level: _Level, - with other: _Node + _ level: _HashLevel, + with other: _HashNode ) -> Bool { assert(isCollisionNode) if other.isCollisionNode { diff --git a/Sources/HashTreeCollections/Node/_Node+Structural isEqualSet.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isEqualSet.swift similarity index 97% rename from Sources/HashTreeCollections/Node/_Node+Structural isEqualSet.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural isEqualSet.swift index 530d417e..90e376da 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural isEqualSet.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isEqualSet.swift @@ -10,10 +10,10 @@ //===----------------------------------------------------------------------===// // TODO: `Equatable` needs more test coverage, apart from hash-collision smoke test -extension _Node { +extension _HashNode { @inlinable internal func isEqualSet( - to other: _Node, + to other: _HashNode, by areEquivalent: (Value, Value2) -> Bool ) -> Bool { if self.raw.storage === other.raw.storage { return true } diff --git a/Sources/HashTreeCollections/Node/_Node+Structural isSubset.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isSubset.swift similarity index 97% rename from Sources/HashTreeCollections/Node/_Node+Structural isSubset.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural isSubset.swift index 261f9cf0..c217a0c2 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural isSubset.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isSubset.swift @@ -9,13 +9,13 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { /// Returns true if `self` contains a subset of the keys in `other`. /// Otherwise, returns false. @inlinable @inline(never) internal func isSubset( - _ level: _Level, - of other: _Node + _ level: _HashLevel, + of other: _HashNode ) -> Bool { guard self.count > 0 else { return true } if self.raw.storage === other.raw.storage { return true } diff --git a/Sources/HashTreeCollections/Node/_Node+Structural mapValues.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift similarity index 89% rename from Sources/HashTreeCollections/Node/_Node+Structural mapValues.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift index abab98ec..d4a6b727 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural mapValues.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift @@ -11,21 +11,21 @@ import _CollectionsUtilities -extension _Node { +extension _HashNode { @inlinable internal func mapValues( _ transform: (Element) throws -> T - ) rethrows -> _Node { + ) rethrows -> _HashNode { let c = self.count return try read { source in - var result: _Node + var result: _HashNode if isCollisionNode { - result = _Node.allocateCollision( + result = _HashNode.allocateCollision( count: c, source.collisionHash, initializingWith: { _ in } ).node } else { - result = _Node.allocate( + result = _HashNode.allocate( itemMap: source.itemMap, childMap: source.childMap, count: c, @@ -75,9 +75,9 @@ extension _Node { @inlinable internal func mapValuesToVoid( copy: Bool = false, extraBytes: Int = 0 - ) -> _Node { + ) -> _HashNode { if Value.self == Void.self { - let node = unsafeBitCast(self, to: _Node.self) + let node = unsafeBitCast(self, to: _HashNode.self) guard copy || !node.hasFreeSpace(extraBytes) else { return node } return node.copy(withFreeSpace: extraBytes) } diff --git a/Sources/HashTreeCollections/Node/_Node+Structural merge.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural merge.swift similarity index 93% rename from Sources/HashTreeCollections/Node/_Node+Structural merge.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural merge.swift index 4d5daf3e..e0d495ec 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural merge.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural merge.swift @@ -9,12 +9,12 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { /// - Returns: The number of new items added to `self`. @inlinable internal mutating func merge( - _ level: _Level, - _ other: _Node, + _ level: _HashLevel, + _ other: _HashNode, _ combine: (Value, Value) throws -> Value ) rethrows -> Int { guard other.count > 0 else { return 0 } @@ -52,8 +52,8 @@ extension _Node { @inlinable internal mutating func _merge( - _ level: _Level, - _ other: _Node, + _ level: _HashLevel, + _ other: _HashNode, _ combine: (Value, Value) throws -> Value ) rethrows -> Int { // Note: don't check storage identities -- we do need to merge the contents @@ -105,7 +105,7 @@ extension _Node { let rp = r.childPtr(at: rslot) self.ensureUnique( - isUnique: isUnique, withFreeSpace: _Node.spaceForSpawningChild) + isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild) let item = self.removeItem(at: bucket) delta &-= 1 var child = rp.pointee @@ -182,7 +182,7 @@ extension _Node { for (bucket, _) in r.childMap.subtracting(seen) { let rslot = r.childMap.slot(of: bucket) self.ensureUnique( - isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild) + isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild) self.insertChild(r[child: rslot], bucket) delta &+= r[child: rslot].count isUnique = true @@ -195,15 +195,15 @@ extension _Node { @inlinable @inline(never) internal mutating func _merge_slow( - _ level: _Level, - _ other: _Node, + _ level: _HashLevel, + _ other: _HashNode, _ combine: (Value, Value) throws -> Value ) rethrows -> Int { let lc = self.isCollisionNode let rc = other.isCollisionNode if lc && rc { guard self.collisionHash == other.collisionHash else { - self = _Node.build( + self = _HashNode.build( level: level, child1: self, self.collisionHash, child2: other, other.collisionHash) @@ -213,14 +213,14 @@ extension _Node { var isUnique = self.isUnique() var delta = 0 let originalItemCount = self.count - for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { + for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { let rp = r.itemPtr(at: rs) - let lslot: _Slot? = self.read { l in + let lslot: _HashSlot? = self.read { l in let litems = l.reverseItems return litems .suffix(originalItemCount) .firstIndex { $0.key == rp.pointee.key } - .map { _Slot(litems.count &- 1 &- $0) } + .map { _HashSlot(litems.count &- 1 &- $0) } } if let lslot = lslot { self.ensureUnique(isUnique: isUnique) @@ -278,7 +278,7 @@ extension _Node { return self.count - originalCount } - var node = other.copy(withFreeSpace: _Node.spaceForNewChild) + var node = other.copy(withFreeSpace: _HashNode.spaceForNewChild) node.insertChild(self, bucket) self = node return other.count @@ -292,7 +292,7 @@ extension _Node { let bucket = r.collisionHash[level] if self.read({ $0.itemMap.contains(bucket) }) { self.ensureUnique( - isUnique: isUnique, withFreeSpace: _Node.spaceForSpawningChild) + isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild) let item = self.removeItem(at: bucket) let h = _Hash(item.key) var copy = other @@ -321,7 +321,7 @@ extension _Node { return delta } self.ensureUnique( - isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild) + isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild) self.insertChild(other, bucket) return other.count } diff --git a/Sources/HashTreeCollections/Node/_Node+Structural subtracting.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural subtracting.swift similarity index 95% rename from Sources/HashTreeCollections/Node/_Node+Structural subtracting.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural subtracting.swift index 4540974b..43b4e953 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural subtracting.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural subtracting.swift @@ -9,12 +9,12 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { @inlinable internal func subtracting( - _ level: _Level, - _ other: _Node - ) -> _Node? { + _ level: _HashLevel, + _ other: _HashNode + ) -> _HashNode? { assert(level.isAtRoot) let builder = _subtracting(level, other) guard let builder = builder else { return nil } @@ -25,8 +25,8 @@ extension _Node { @inlinable internal func _subtracting( - _ level: _Level, - _ other: _Node + _ level: _HashLevel, + _ other: _HashNode ) -> Builder? { if self.raw.storage === other.raw.storage { return .empty(level) } @@ -109,8 +109,8 @@ extension _Node { @inlinable @inline(never) internal func _subtracting_slow( - _ level: _Level, - _ other: _Node + _ level: _HashLevel, + _ other: _HashNode ) -> Builder? { let lc = self.isCollisionNode let rc = other.isCollisionNode @@ -124,7 +124,7 @@ extension _Node { var removing = false let ritems = r.reverseItems - for lslot: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { + for lslot: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { let lp = l.itemPtr(at: lslot) let include = !ritems.contains { $0.key == lp.pointee.key } if include, removing { diff --git a/Sources/HashTreeCollections/Node/_Node+Structural symmetricDifference.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural symmetricDifference.swift similarity index 91% rename from Sources/HashTreeCollections/Node/_Node+Structural symmetricDifference.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural symmetricDifference.swift index b236e3e5..5ea7810f 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural symmetricDifference.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural symmetricDifference.swift @@ -9,12 +9,12 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { @inlinable internal func symmetricDifference( - _ level: _Level, - _ other: _Node - ) -> _Node.Builder? { + _ level: _HashLevel, + _ other: _HashNode + ) -> _HashNode.Builder? { guard self.count > 0 else { return .init(level, other.mapValuesToVoid()) } @@ -24,10 +24,10 @@ extension _Node { @inlinable internal func _symmetricDifference( - _ level: _Level, - _ other: _Node - ) -> _Node.Builder { - typealias VoidNode = _Node + _ level: _HashLevel, + _ other: _HashNode + ) -> _HashNode.Builder { + typealias VoidNode = _HashNode assert(self.count > 0 && other.count > 0) @@ -130,9 +130,9 @@ extension _Node { @inlinable @inline(never) internal func _symmetricDifference_slow( - _ level: _Level, - _ other: _Node - ) -> _Node.Builder { + _ level: _HashLevel, + _ other: _HashNode + ) -> _HashNode.Builder { switch (self.isCollisionNode, other.isCollisionNode) { case (true, true): return self._symmetricDifference_slow_both(level, other) @@ -145,10 +145,10 @@ extension _Node { @inlinable internal func _symmetricDifference_slow_both( - _ level: _Level, - _ other: _Node - ) -> _Node.Builder { - typealias VoidNode = _Node + _ level: _HashLevel, + _ other: _HashNode + ) -> _HashNode.Builder { + typealias VoidNode = _HashNode return read { l in other.read { r in guard l.collisionHash == r.collisionHash else { @@ -160,7 +160,7 @@ extension _Node { } var result: VoidNode.Builder = .empty(level) let ritems = r.reverseItems - for ls: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { + for ls: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { let lp = l.itemPtr(at: ls) let include = !ritems.contains(where: { $0.key == lp.pointee.key }) if include { @@ -170,7 +170,7 @@ extension _Node { // FIXME: Consider remembering slots of shared items in r by // caching them in a bitset. let litems = l.reverseItems - for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { + for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { let rp = r.itemPtr(at: rs) let include = !litems.contains(where: { $0.key == rp.pointee.key }) if include { @@ -184,10 +184,10 @@ extension _Node { @inlinable internal func _symmetricDifference_slow_left( - _ level: _Level, - _ other: _Node - ) -> _Node.Builder { - typealias VoidNode = _Node + _ level: _HashLevel, + _ other: _HashNode + ) -> _HashNode.Builder { + typealias VoidNode = _HashNode // `self` is a collision node on a compressed path. The other tree might // have the same set of collisions, just expanded a bit deeper. return read { l in @@ -218,7 +218,7 @@ extension _Node { with: (litems[1 &- li].key, ())) return .node(level, node) } - let lslot = _Slot(litems.count &- 1 &- li) + let lslot = _HashSlot(litems.count &- 1 &- li) var child = self.mapValuesToVoid(copy: true) _ = child.removeItem(at: .invalid, lslot) if other.hasSingletonItem { diff --git a/Sources/HashTreeCollections/Node/_Node+Structural union.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural union.swift similarity index 90% rename from Sources/HashTreeCollections/Node/_Node+Structural union.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Structural union.swift index 4f0b3b21..8ef23bef 100644 --- a/Sources/HashTreeCollections/Node/_Node+Structural union.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural union.swift @@ -9,12 +9,12 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { @inlinable internal func union( - _ level: _Level, - _ other: _Node - ) -> (copied: Bool, node: _Node) { + _ level: _HashLevel, + _ other: _HashNode + ) -> (copied: Bool, node: _HashNode) { guard self.count > 0 else { return (true, other.mapValuesToVoid()) } guard other.count > 0 else { return (false, self.mapValuesToVoid()) } if level.isAtRoot, self.hasSingletonItem { @@ -42,9 +42,9 @@ extension _Node { @inlinable internal func _union( - _ level: _Level, - _ other: _Node - ) -> (copied: Bool, node: _Node) { + _ level: _HashLevel, + _ other: _HashNode + ) -> (copied: Bool, node: _HashNode) { if self.raw.storage === other.raw.storage { return (false, self.mapValuesToVoid()) } @@ -88,7 +88,7 @@ extension _Node { let rp = r.childPtr(at: rslot) node.ensureUnique( - isUnique: copied, withFreeSpace: _Node.spaceForSpawningChild) + isUnique: copied, withFreeSpace: _HashNode.spaceForSpawningChild) let item = node.removeItem(at: bucket) let r = rp.pointee.mapValuesToVoid() .inserting(level.descend(), (item.key, ()), _Hash(item.key)) @@ -142,7 +142,7 @@ extension _Node { for (bucket, _) in r.childMap.subtracting(seen) { let rslot = r.childMap.slot(of: bucket) node.ensureUnique( - isUnique: copied, withFreeSpace: _Node.spaceForNewChild) + isUnique: copied, withFreeSpace: _HashNode.spaceForNewChild) copied = true node.insertChild(r[child: rslot].mapValuesToVoid(), bucket) } @@ -154,16 +154,16 @@ extension _Node { @inlinable @inline(never) internal func _union_slow( - _ level: _Level, - _ other: _Node - ) -> (copied: Bool, node: _Node) { + _ level: _HashLevel, + _ other: _HashNode + ) -> (copied: Bool, node: _HashNode) { let lc = self.isCollisionNode let rc = other.isCollisionNode if lc && rc { return read { l in other.read { r in guard l.collisionHash == r.collisionHash else { - let node = _Node.build( + let node = _HashNode.build( level: level, child1: self.mapValuesToVoid(), l.collisionHash, child2: other.mapValuesToVoid(), r.collisionHash) @@ -172,7 +172,7 @@ extension _Node { var copied = false var node = self.mapValuesToVoid() let litems = l.reverseItems - for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { + for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { let p = r.itemPtr(at: rs) if !litems.contains(where: { $0.key == p.pointee.key }) { _ = node.ensureUniqueAndAppendCollision( @@ -218,7 +218,7 @@ extension _Node { } var node = other.mapValuesToVoid( - copy: true, extraBytes: _Node.spaceForNewChild) + copy: true, extraBytes: _HashNode.spaceForNewChild) node.insertChild(self.mapValuesToVoid(), bucket) return (true, node) } @@ -227,8 +227,8 @@ extension _Node { assert(rc) // `other` is a collision node on a compressed path. - return read { l -> (copied: Bool, node: _Node) in - other.read { r -> (copied: Bool, node: _Node) in + return read { l -> (copied: Bool, node: _HashNode) in + other.read { r -> (copied: Bool, node: _HashNode) in let bucket = r.collisionHash[level] if l.itemMap.contains(bucket) { let lslot = l.itemMap.slot(of: bucket) @@ -248,7 +248,7 @@ extension _Node { } var node = self.mapValuesToVoid( - copy: true, extraBytes: _Node.spaceForNewChild) + copy: true, extraBytes: _HashNode.spaceForNewChild) node.insertChild(other.mapValuesToVoid(), bucket) return (true, node) } diff --git a/Sources/HashTreeCollections/Node/_Node+Subtree Insertions.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift similarity index 89% rename from Sources/HashTreeCollections/Node/_Node+Subtree Insertions.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift index 1c131781..a3457f19 100644 --- a/Sources/HashTreeCollections/Node/_Node+Subtree Insertions.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift @@ -11,23 +11,23 @@ import _CollectionsUtilities -extension _Node { +extension _HashNode { @inlinable internal mutating func insert( - _ level: _Level, + _ level: _HashLevel, _ item: Element, _ hash: _Hash - ) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) { + ) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) { insert(level, item.key, hash) { $0.initialize(to: item) } } @inlinable internal mutating func insert( - _ level: _Level, + _ level: _HashLevel, _ key: Key, _ hash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void - ) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) { + ) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) { defer { _invariantCheck() } let isUnique = self.isUnique() if !isUnique { @@ -56,7 +56,7 @@ extension _Node { inserter) return (true, r.leaf, r.slot) case .expansion: - let r = _Node.build( + let r = _HashNode.build( level: level, item1: inserter, hash, child2: self, self.collisionHash) @@ -73,20 +73,24 @@ extension _Node { @inlinable internal func inserting( - _ level: _Level, + _ level: _HashLevel, _ item: __owned Element, _ hash: _Hash - ) -> (inserted: Bool, node: _Node, leaf: _UnmanagedNode, slot: _Slot) { + ) -> ( + inserted: Bool, node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot + ) { inserting(level, item.key, hash, { $0.initialize(to: item) }) } @inlinable internal func inserting( - _ level: _Level, + _ level: _HashLevel, _ key: Key, _ hash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void - ) -> (inserted: Bool, node: _Node, leaf: _UnmanagedNode, slot: _Slot) { + ) -> ( + inserted: Bool, node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot + ) { defer { _invariantCheck() } let r = findForInsertion(level, key, hash) switch r { @@ -109,7 +113,7 @@ extension _Node { inserter) return (true, r.node, r.leaf, r.slot) case .expansion: - let r = _Node.build( + let r = _HashNode.build( level: level, item1: inserter, hash, child2: self, self.collisionHash) @@ -130,11 +134,11 @@ extension _Node { @inlinable internal mutating func updateValue( - _ level: _Level, + _ level: _HashLevel, forKey key: Key, _ hash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void - ) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) { + ) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) { defer { _invariantCheck() } let isUnique = self.isUnique() let r = findForInsertion(level, key, hash) @@ -159,7 +163,7 @@ extension _Node { inserter) return (true, r.leaf, r.slot) case .expansion: - let r = _Node.build( + let r = _HashNode.build( level: level, item1: inserter, hash, child2: self, self.collisionHash) @@ -177,7 +181,7 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal mutating func ensureUniqueAndInsertItem( isUnique: Bool, @@ -198,7 +202,7 @@ extension _Node { internal mutating func ensureUniqueAndInsertItem( isUnique: Bool, at bucket: _Bucket, - itemSlot slot: _Slot, + itemSlot slot: _HashSlot, _ inserter: (UnsafeMutablePointer) -> Void ) { assert(!isCollisionNode) @@ -222,9 +226,9 @@ extension _Node { @inlinable @inline(never) internal func copyNodeAndInsertItem( at bucket: _Bucket, - itemSlot slot: _Slot, + itemSlot slot: _HashSlot, _ inserter: (UnsafeMutablePointer) -> Void - ) -> _Node { + ) -> _HashNode { assert(!isCollisionNode) let c = self.count return read { src in @@ -253,7 +257,7 @@ extension _Node { @inlinable @inline(never) internal mutating func resizeNodeAndInsertItem( at bucket: _Bucket, - itemSlot slot: _Slot, + itemSlot slot: _HashSlot, _ inserter: (UnsafeMutablePointer) -> Void ) { assert(!isCollisionNode) @@ -284,12 +288,12 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal mutating func ensureUniqueAndAppendCollision( isUnique: Bool, _ item: Element - ) -> _Slot { + ) -> _HashSlot { ensureUniqueAndAppendCollision(isUnique: isUnique) { $0.initialize(to: item) } @@ -299,7 +303,7 @@ extension _Node { internal mutating func ensureUniqueAndAppendCollision( isUnique: Bool, _ inserter: (UnsafeMutablePointer) -> Void - ) -> _Slot { + ) -> _HashSlot { assert(isCollisionNode) if !isUnique { let r = copyNodeAndAppendCollision(inserter) @@ -315,13 +319,13 @@ extension _Node { inserter(p) } self.count &+= 1 - return _Slot(self.count &- 1) + return _HashSlot(self.count &- 1) } @inlinable @inline(never) internal func copyNodeAndAppendCollision( _ inserter: (UnsafeMutablePointer) -> Void - ) -> (node: _Node, slot: _Slot) { + ) -> (node: _HashNode, slot: _HashSlot) { assert(isCollisionNode) assert(self.count == read { $0.collisionCount }) let c = self.count @@ -333,13 +337,13 @@ extension _Node { inserter(dstItems.baseAddress!) }.node } - return (node, _Slot(c)) + return (node, _HashSlot(c)) } @inlinable @inline(never) internal mutating func resizeNodeAndAppendCollision( _ inserter: (UnsafeMutablePointer) -> Void - ) -> _Slot { + ) -> _HashSlot { assert(isCollisionNode) assert(self.count == read { $0.collisionCount }) let c = self.count @@ -353,18 +357,18 @@ extension _Node { src.clear() }.node } - return _Slot(c) + return _HashSlot(c) } } -extension _Node { +extension _HashNode { @inlinable internal func _copyNodeAndReplaceItemWithNewChild( - level: _Level, - _ newChild: __owned _Node, + level: _HashLevel, + _ newChild: __owned _HashNode, at bucket: _Bucket, - itemSlot: _Slot - ) -> _Node { + itemSlot: _HashSlot + ) -> _HashNode { let c = self.count return read { src in assert(!src.isCollisionNode) @@ -409,13 +413,13 @@ extension _Node { /// this function is called. @inlinable internal mutating func _resizeNodeAndReplaceItemWithNewChild( - level: _Level, - _ newChild: __owned _Node, + level: _HashLevel, + _ newChild: __owned _HashNode, at bucket: _Bucket, - itemSlot: _Slot + itemSlot: _HashSlot ) { let c = self.count - let node: _Node = update { src in + let node: _HashNode = update { src in assert(!src.isCollisionNode) assert(src.itemMap.contains(bucket)) assert(!src.childMap.contains(bucket)) @@ -453,14 +457,14 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable @inline(never) internal func copyNodeAndPushItemIntoNewChild( - level: _Level, - _ newChild: __owned _Node, + level: _HashLevel, + _ newChild: __owned _HashNode, at bucket: _Bucket, - itemSlot: _Slot - ) -> _Node { + itemSlot: _HashSlot + ) -> _HashNode { assert(!isCollisionNode) let item = read { $0[item: itemSlot] } let hash = _Hash(item.key) @@ -473,22 +477,22 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal mutating func ensureUniqueAndSpawnChild( isUnique: Bool, - level: _Level, + level: _HashLevel, replacing bucket: _Bucket, - itemSlot: _Slot, + itemSlot: _HashSlot, newHash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void - ) -> (leaf: _UnmanagedNode, slot: _Slot) { + ) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) { let existingHash = read { _Hash($0[item: itemSlot].key) } assert(existingHash.isEqual(to: newHash, upTo: level)) if newHash == existingHash, hasSingletonItem { // Convert current node to a collision node. - self = _Node._collisionNode(newHash, read { $0[item: .zero] }, inserter) - return (unmanaged, _Slot(1)) + self = _HashNode._collisionNode(newHash, read { $0[item: .zero] }, inserter) + return (unmanaged, _HashSlot(1)) } if !isUnique { @@ -513,7 +517,7 @@ extension _Node { } let existing = removeItem(at: bucket, itemSlot) - let r = _Node.build( + let r = _HashNode.build( level: level.descend(), item1: existing, existingHash, item2: inserter, newHash) @@ -523,15 +527,15 @@ extension _Node { @inlinable @inline(never) internal func copyNodeAndSpawnChild( - level: _Level, + level: _HashLevel, replacing bucket: _Bucket, - itemSlot: _Slot, + itemSlot: _HashSlot, existingHash: _Hash, newHash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void - ) -> (node: _Node, leaf: _UnmanagedNode, slot: _Slot) { + ) -> (node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot) { let r = read { - _Node.build( + _HashNode.build( level: level.descend(), item1: $0[item: itemSlot], existingHash, item2: inserter, newHash) @@ -547,15 +551,15 @@ extension _Node { @inlinable @inline(never) internal mutating func resizeNodeAndSpawnChild( - level: _Level, + level: _HashLevel, replacing bucket: _Bucket, - itemSlot: _Slot, + itemSlot: _HashSlot, existingHash: _Hash, newHash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void - ) -> (leaf: _UnmanagedNode, slot: _Slot) { + ) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) { let r = update { - _Node.build( + _HashNode.build( level: level.descend(), item1: $0.itemPtr(at: itemSlot).move(), existingHash, item2: inserter, newHash) diff --git a/Sources/HashTreeCollections/Node/_Node+Subtree Modify.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Modify.swift similarity index 93% rename from Sources/HashTreeCollections/Node/_Node+Subtree Modify.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Subtree Modify.swift index fcf5bac0..f53c81b9 100644 --- a/Sources/HashTreeCollections/Node/_Node+Subtree Modify.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Modify.swift @@ -11,11 +11,11 @@ // MARK: Subtree-level in-place mutation operations -extension _Node { +extension _HashNode { @inlinable internal mutating func ensureUnique( - level: _Level, at path: _UnsafePath - ) -> (leaf: _UnmanagedNode, slot: _Slot) { + level: _HashLevel, at path: _UnsafePath + ) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) { ensureUnique(isUnique: isUnique()) guard level < path.level else { return (unmanaged, path.currentItemSlot) } return update { @@ -25,7 +25,7 @@ extension _Node { } } -extension _Node { +extension _HashNode { @usableFromInline @frozen internal struct ValueUpdateState { @@ -93,7 +93,7 @@ extension _Node { state.path.selectItem(at: slot) case .appendCollision: - state.path.selectItem(at: _Slot(self.count)) + state.path.selectItem(at: _HashSlot(self.count)) case .spawnChild(_, let slot): state.path.selectItem(at: slot) @@ -140,7 +140,7 @@ extension _Node { @inlinable internal mutating func _finalizeRemoval( - _ level: _Level, _ hash: _Hash, at path: _UnsafePath + _ level: _HashLevel, _ hash: _Hash, at path: _UnsafePath ) -> Element? { assert(isUnique()) if level == path.level { @@ -157,7 +157,7 @@ extension _Node { } } -extension _Node { +extension _HashNode { @usableFromInline @frozen internal struct DefaultedValueUpdateState { @@ -165,10 +165,10 @@ extension _Node { internal var item: Element @usableFromInline - internal var node: _UnmanagedNode + internal var node: _UnmanagedHashNode @usableFromInline - internal var slot: _Slot + internal var slot: _HashSlot @usableFromInline internal var inserted: Bool @@ -176,8 +176,8 @@ extension _Node { @inlinable internal init( _ item: Element, - in node: _UnmanagedNode, - at slot: _Slot, + in node: _UnmanagedHashNode, + at slot: _HashSlot, inserted: Bool ) { self.item = item @@ -189,7 +189,7 @@ extension _Node { @inlinable internal mutating func prepareDefaultedValueUpdate( - _ level: _Level, + _ level: _HashLevel, _ key: Key, _ defaultValue: () -> Value, _ hash: _Hash @@ -237,7 +237,7 @@ extension _Node { inserted: true) case .expansion: - let r = _Node.build( + let r = _HashNode.build( level: level, item1: { _ in }, hash, child2: self, self.collisionHash diff --git a/Sources/HashTreeCollections/Node/_Node+Subtree Removals.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Removals.swift similarity index 90% rename from Sources/HashTreeCollections/Node/_Node+Subtree Removals.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+Subtree Removals.swift index 302b91c4..1df9ee61 100644 --- a/Sources/HashTreeCollections/Node/_Node+Subtree Removals.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Removals.swift @@ -11,7 +11,7 @@ // MARK: Subtree-level removal operations -extension _Node { +extension _HashNode { /// Remove the item with the specified key from this subtree and return it. /// /// This function may leave `self` containing a singleton item. @@ -19,7 +19,7 @@ extension _Node { /// by inlining the remaining item into the parent node. @inlinable internal mutating func remove( - _ level: _Level, _ key: Key, _ hash: _Hash + _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> (removed: Element, remainder: Element?)? { guard self.isUnique() else { guard let r = removing(level, key, hash) else { return nil } @@ -46,10 +46,10 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal func removing( - _ level: _Level, _ key: Key, _ hash: _Hash + _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> (removed: Element, replacement: Builder)? { guard let r = find(level, key, hash) else { return nil } let bucket = hash[level] @@ -64,10 +64,10 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal mutating func remove( - _ level: _Level, at path: _UnsafePath + _ level: _HashLevel, at path: _UnsafePath ) -> (removed: Element, remainder: Element?) { defer { _invariantCheck() } guard self.isUnique() else { @@ -94,7 +94,7 @@ extension _Node { @inlinable internal func removing( - _ level: _Level, at path: _UnsafePath + _ level: _HashLevel, at path: _UnsafePath ) -> (removed: Element, replacement: Builder) { if level == path.level { let slot = path.currentItemSlot @@ -112,12 +112,12 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal mutating func _removeItemFromUniqueLeafNode( - _ level: _Level, + _ level: _HashLevel, at bucket: _Bucket, - _ slot: _Slot, + _ slot: _HashSlot, by remover: (UnsafeMutablePointer) -> R ) -> (result: R, remainder: Element?) { assert(isUnique()) @@ -140,7 +140,7 @@ extension _Node { @inlinable internal func _removingItemFromLeaf( - _ level: _Level, at bucket: _Bucket, _ slot: _Slot + _ level: _HashLevel, at bucket: _Bucket, _ slot: _HashSlot ) -> (removed: Element, replacement: Builder) { read { if $0.isCollisionNode { @@ -148,7 +148,7 @@ extension _Node { if $0.collisionCount == 2 { // Node will evaporate - let remainder = _Slot(1 &- slot.value) + let remainder = _HashSlot(1 &- slot.value) let bucket = $0.collisionHash[level] return ( removed: $0[item: slot], @@ -178,7 +178,7 @@ extension _Node { if $0.itemMap.count == 2 && $0.childMap.isEmpty { // Evaporating node - let remainder = _Slot(1 &- slot.value) + let remainder = _HashSlot(1 &- slot.value) var map = $0.itemMap if remainder != .zero { _ = map.popFirst() } @@ -196,21 +196,21 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal func _removingChild( - _ level: _Level, at bucket: _Bucket, _ slot: _Slot + _ level: _HashLevel, at bucket: _Bucket, _ slot: _HashSlot ) -> Builder { read { assert(!$0.isCollisionNode && $0.childMap.contains(bucket)) let willAtrophy = ( $0.itemMap.isEmpty && $0.childCount == 2 - && $0[child: _Slot(1 &- slot.value)].isCollisionNode + && $0[child: _HashSlot(1 &- slot.value)].isCollisionNode ) if willAtrophy { // Compression - let child = $0[child: _Slot(1 &- slot.value)] + let child = $0[child: _HashSlot(1 &- slot.value)] return .collisionNode(level, child) } if $0.itemMap.hasExactlyOneMember && $0.childMap.hasExactlyOneMember { @@ -229,12 +229,12 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal mutating func _fixupUniqueAncestorAfterItemRemoval( - _ level: _Level, + _ level: _HashLevel, at bucket: (UnsafeHandle) -> _Bucket, - _ childSlot: _Slot, + _ childSlot: _HashSlot, remainder: Element? ) -> Element? { assert(isUnique()) @@ -261,7 +261,7 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal mutating func _convertToRegularNode() { assert(isCollisionNode && hasSingletonItem) diff --git a/Sources/HashTreeCollections/Node/_Node+UnsafeHandle.swift b/Sources/HashTreeCollections/HashNode/_HashNode+UnsafeHandle.swift similarity index 85% rename from Sources/HashTreeCollections/Node/_Node+UnsafeHandle.swift rename to Sources/HashTreeCollections/HashNode/_HashNode+UnsafeHandle.swift index 680e0517..cd99b57b 100644 --- a/Sources/HashTreeCollections/Node/_Node+UnsafeHandle.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+UnsafeHandle.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -extension _Node { +extension _HashNode { /// An unsafe view of the data stored inside a node in the hash tree, hiding /// the mechanics of accessing storage from the code that uses it. /// @@ -27,7 +27,7 @@ extension _Node { internal typealias Element = (key: Key, value: Value) @usableFromInline - internal let _header: UnsafeMutablePointer<_StorageHeader> + internal let _header: UnsafeMutablePointer<_HashNodeHeader> @usableFromInline internal let _memory: UnsafeMutableRawPointer @@ -39,7 +39,7 @@ extension _Node { @inlinable internal init( - _ header: UnsafeMutablePointer<_StorageHeader>, + _ header: UnsafeMutablePointer<_HashNodeHeader>, _ memory: UnsafeMutableRawPointer, isMutable: Bool ) { @@ -52,7 +52,7 @@ extension _Node { } } -extension _Node.UnsafeHandle { +extension _HashNode.UnsafeHandle { @inlinable @inline(__always) func assertMutable() { @@ -62,10 +62,10 @@ extension _Node.UnsafeHandle { } } -extension _Node.UnsafeHandle { +extension _HashNode.UnsafeHandle { @inlinable @inline(__always) static func read( - _ node: _UnmanagedNode, + _ node: _UnmanagedHashNode, _ body: (Self) throws -> R ) rethrows -> R { try node.ref._withUnsafeGuaranteedRef { storage in @@ -77,7 +77,7 @@ extension _Node.UnsafeHandle { @inlinable @inline(__always) static func read( - _ storage: _RawStorage, + _ storage: _RawHashStorage, _ body: (Self) throws -> R ) rethrows -> R { try storage.withUnsafeMutablePointers { header, elements in @@ -87,7 +87,7 @@ extension _Node.UnsafeHandle { @inlinable @inline(__always) static func update( - _ node: _UnmanagedNode, + _ node: _UnmanagedHashNode, _ body: (Self) throws -> R ) rethrows -> R { try node.ref._withUnsafeGuaranteedRef { storage in @@ -99,7 +99,7 @@ extension _Node.UnsafeHandle { @inlinable @inline(__always) static func update( - _ storage: _RawStorage, + _ storage: _RawHashStorage, _ body: (Self) throws -> R ) rethrows -> R { try storage.withUnsafeMutablePointers { header, elements in @@ -108,7 +108,7 @@ extension _Node.UnsafeHandle { } } -extension _Node.UnsafeHandle { +extension _HashNode.UnsafeHandle { @inlinable @inline(__always) internal var itemMap: _Bitmap { get { @@ -173,8 +173,8 @@ extension _Node.UnsafeHandle { } @inlinable @inline(__always) - internal var _childrenStart: UnsafeMutablePointer<_Node> { - _memory.assumingMemoryBound(to: _Node.self) + internal var _childrenStart: UnsafeMutablePointer<_HashNode> { + _memory.assumingMemoryBound(to: _HashNode.self) } @inlinable @inline(__always) @@ -188,29 +188,29 @@ extension _Node.UnsafeHandle { } @inlinable - internal func childBucket(at slot: _Slot) -> _Bucket { + internal func childBucket(at slot: _HashSlot) -> _Bucket { guard !isCollisionNode else { return .invalid } return childMap.bucket(at: slot) } @inlinable @inline(__always) - internal var childrenEndSlot: _Slot { + internal var childrenEndSlot: _HashSlot { _header.pointee.childrenEndSlot } @inlinable - internal var children: UnsafeMutableBufferPointer<_Node> { + internal var children: UnsafeMutableBufferPointer<_HashNode> { UnsafeMutableBufferPointer(start: _childrenStart, count: childCount) } @inlinable - internal func childPtr(at slot: _Slot) -> UnsafeMutablePointer<_Node> { + internal func childPtr(at slot: _HashSlot) -> UnsafeMutablePointer<_HashNode> { assert(slot.value < childCount) return _childrenStart + slot.value } @inlinable - internal subscript(child slot: _Slot) -> _Node { + internal subscript(child slot: _HashSlot) -> _HashNode { unsafeAddress { UnsafePointer(childPtr(at: slot)) } @@ -237,13 +237,13 @@ extension _Node.UnsafeHandle { } @inlinable - internal func itemBucket(at slot: _Slot) -> _Bucket { + internal func itemBucket(at slot: _HashSlot) -> _Bucket { guard !isCollisionNode else { return .invalid } return itemMap.bucket(at: slot) } @inlinable @inline(__always) - internal var itemsEndSlot: _Slot { + internal var itemsEndSlot: _HashSlot { _header.pointee.itemsEndSlot } @@ -254,13 +254,13 @@ extension _Node.UnsafeHandle { } @inlinable - internal func itemPtr(at slot: _Slot) -> UnsafeMutablePointer { + internal func itemPtr(at slot: _HashSlot) -> UnsafeMutablePointer { assert(slot.value <= itemCount) return _itemsEnd.advanced(by: -1 &- slot.value) } @inlinable - internal subscript(item slot: _Slot) -> Element { + internal subscript(item slot: _HashSlot) -> Element { unsafeAddress { UnsafePointer(itemPtr(at: slot)) } @@ -277,7 +277,7 @@ extension _Node.UnsafeHandle { } } -extension _Node.UnsafeHandle { +extension _HashNode.UnsafeHandle { @inlinable internal var hasSingletonItem: Bool { _header.pointee.hasSingletonItem diff --git a/Sources/HashTreeCollections/Node/_Node.swift b/Sources/HashTreeCollections/HashNode/_HashNode.swift similarity index 84% rename from Sources/HashTreeCollections/Node/_Node.swift rename to Sources/HashTreeCollections/HashNode/_HashNode.swift index 9a0a3c17..e9e35e2f 100644 --- a/Sources/HashTreeCollections/Node/_Node.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode.swift @@ -36,31 +36,31 @@ /// items map. @usableFromInline @frozen -internal struct _Node { - // Warning: This struct must be kept layout-compatible with _RawNode. +internal struct _HashNode { + // Warning: This struct must be kept layout-compatible with _RawHashNode. // Do not add any new stored properties to this type. // // Swift guarantees that frozen structs with a single stored property will // be layout-compatible with the type they are wrapping. // - // (_RawNode is used as the Element type of the ManagedBuffer underlying - // node storage, and the memory is then rebound to `_Node` later. - // This will not work correctly unless `_Node` has the exact same alignment + // (_RawHashNode is used as the Element type of the ManagedBuffer underlying + // node storage, and the memory is then rebound to `_HashNode` later. + // This will not work correctly unless `_HashNode` has the exact same alignment // and stride as `RawNode`.) @usableFromInline internal typealias Element = (key: Key, value: Value) @usableFromInline - internal var raw: _RawNode + internal var raw: _RawHashNode @inlinable - internal init(storage: _RawStorage, count: Int) { - self.raw = _RawNode(storage: storage, count: count) + internal init(storage: _RawHashStorage, count: Int) { + self.raw = _RawHashNode(storage: storage, count: count) } } -extension _Node { +extension _HashNode { @inlinable @inline(__always) internal var count: Int { get { raw.count } @@ -68,19 +68,19 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable @inline(__always) - internal var unmanaged: _UnmanagedNode { - _UnmanagedNode(raw.storage) + internal var unmanaged: _UnmanagedHashNode { + _UnmanagedHashNode(raw.storage) } @inlinable @inline(__always) - internal func isIdentical(to other: _UnmanagedNode) -> Bool { + internal func isIdentical(to other: _UnmanagedHashNode) -> Bool { raw.isIdentical(to: other) } } -extension _Node { +extension _HashNode { @inlinable @inline(__always) internal func read( _ body: (UnsafeHandle) throws -> R @@ -98,7 +98,7 @@ extension _Node { // MARK: Shortcuts to reading header data -extension _Node { +extension _HashNode { @inlinable internal var isCollisionNode: Bool { read { $0.isCollisionNode } @@ -125,7 +125,7 @@ extension _Node { } } -extension _Node { +extension _HashNode { @inlinable internal var initialVersionNumber: UInt { // Ideally we would simply just generate a true random number, but the diff --git a/Sources/HashTreeCollections/Node/_Slot.swift b/Sources/HashTreeCollections/HashNode/_HashSlot.swift similarity index 75% rename from Sources/HashTreeCollections/Node/_Slot.swift rename to Sources/HashTreeCollections/HashNode/_HashSlot.swift index 788e4369..7f9d64dd 100644 --- a/Sources/HashTreeCollections/Node/_Slot.swift +++ b/Sources/HashTreeCollections/HashNode/_HashSlot.swift @@ -11,14 +11,14 @@ /// Identifies a position within a contiguous storage region within a hash tree /// node. Hash tree nodes have two storage regions, one for items and one for -/// children; the same `_Slot` type is used to refer to positions within both. +/// children; the same `_HashSlot` type is used to refer to positions within both. /// /// We use the term "slot" to refer to internal storage entries, to avoid /// confusion with terms that sometimes appear in public API, such as /// "index", "position" or "offset". @usableFromInline @frozen -internal struct _Slot { +internal struct _HashSlot { @usableFromInline internal var _value: UInt32 @@ -40,55 +40,55 @@ internal struct _Slot { } } -extension _Slot { +extension _HashSlot { @inlinable @inline(__always) - internal static var zero: _Slot { _Slot(0) } + internal static var zero: _HashSlot { _HashSlot(0) } } -extension _Slot { +extension _HashSlot { @inlinable @inline(__always) internal var value: Int { Int(truncatingIfNeeded: _value) } } -extension _Slot: Equatable { +extension _HashSlot: Equatable { @inlinable @inline(__always) internal static func ==(left: Self, right: Self) -> Bool { left._value == right._value } } -extension _Slot: Comparable { +extension _HashSlot: Comparable { @inlinable @inline(__always) internal static func <(left: Self, right: Self) -> Bool { left._value < right._value } } -extension _Slot: Hashable { +extension _HashSlot: Hashable { @inlinable internal func hash(into hasher: inout Hasher) { hasher.combine(_value) } } -extension _Slot: CustomStringConvertible { +extension _HashSlot: CustomStringConvertible { @usableFromInline internal var description: String { "\(_value)" } } -extension _Slot: Strideable { +extension _HashSlot: Strideable { @inlinable @inline(__always) - internal func advanced(by n: Int) -> _Slot { + internal func advanced(by n: Int) -> _HashSlot { assert(n >= 0 || value + n >= 0) - return _Slot(_value &+ UInt32(truncatingIfNeeded: n)) + return _HashSlot(_value &+ UInt32(truncatingIfNeeded: n)) } @inlinable @inline(__always) - internal func distance(to other: _Slot) -> Int { + internal func distance(to other: _HashSlot) -> Int { if self < other { return Int(truncatingIfNeeded: other._value - self._value) } @@ -96,16 +96,16 @@ extension _Slot: Strideable { } } -extension _Slot { +extension _HashSlot { @inlinable @inline(__always) - internal func next() -> _Slot { + internal func next() -> _HashSlot { assert(_value < .max) - return _Slot(_value &+ 1) + return _HashSlot(_value &+ 1) } @inlinable @inline(__always) - internal func previous() -> _Slot { + internal func previous() -> _HashSlot { assert(_value > 0) - return _Slot(_value &- 1) + return _HashSlot(_value &- 1) } } diff --git a/Sources/HashTreeCollections/Node/_Stack.swift b/Sources/HashTreeCollections/HashNode/_HashStack.swift similarity index 97% rename from Sources/HashTreeCollections/Node/_Stack.swift rename to Sources/HashTreeCollections/HashNode/_HashStack.swift index bbf9c962..8d69b44e 100644 --- a/Sources/HashTreeCollections/Node/_Stack.swift +++ b/Sources/HashTreeCollections/HashNode/_HashStack.swift @@ -13,7 +13,7 @@ /// `TreeDictionary`. @usableFromInline @frozen -internal struct _Stack { +internal struct _HashStack { #if arch(x86_64) || arch(arm64) @inlinable @inline(__always) @@ -45,7 +45,7 @@ internal struct _Stack { @inlinable internal init(filledWith value: Element) { - assert(Self.capacity == _Level.limit) + assert(Self.capacity == _HashLevel.limit) #if arch(x86_64) || arch(arm64) _contents = ( value, value, value, value, diff --git a/Sources/HashTreeCollections/Node/_HashTreeIterator.swift b/Sources/HashTreeCollections/HashNode/_HashTreeIterator.swift similarity index 77% rename from Sources/HashTreeCollections/Node/_HashTreeIterator.swift rename to Sources/HashTreeCollections/HashNode/_HashTreeIterator.swift index 402e4b12..29adc235 100644 --- a/Sources/HashTreeCollections/Node/_HashTreeIterator.swift +++ b/Sources/HashTreeCollections/HashNode/_HashTreeIterator.swift @@ -14,39 +14,39 @@ internal struct _HashTreeIterator { @usableFromInline internal struct _Opaque { - internal var ancestorSlots: _AncestorSlots - internal var ancestorNodes: _Stack<_UnmanagedNode> - internal var level: _Level + internal var ancestorSlots: _AncestorHashSlots + internal var ancestorNodes: _HashStack<_UnmanagedHashNode> + internal var level: _HashLevel internal var isAtEnd: Bool @usableFromInline @_effects(releasenone) - internal init(_ root: _UnmanagedNode) { + internal init(_ root: _UnmanagedHashNode) { self.ancestorSlots = .empty - self.ancestorNodes = _Stack(filledWith: root) + self.ancestorNodes = _HashStack(filledWith: root) self.level = .top self.isAtEnd = false } } @usableFromInline - internal let root: _RawStorage + internal let root: _RawHashStorage @usableFromInline - internal var node: _UnmanagedNode + internal var node: _UnmanagedHashNode @usableFromInline - internal var slot: _Slot + internal var slot: _HashSlot @usableFromInline - internal var endSlot: _Slot + internal var endSlot: _HashSlot @usableFromInline internal var _o: _Opaque @usableFromInline @_effects(releasenone) - internal init(root: __shared _RawNode) { + internal init(root: __shared _RawHashNode) { self.root = root.storage self.node = root.unmanaged self.slot = .zero @@ -64,7 +64,8 @@ internal struct _HashTreeIterator { extension _HashTreeIterator: IteratorProtocol { @inlinable - internal mutating func next() -> (node: _UnmanagedNode, slot: _Slot)? { + internal mutating func next( + ) -> (node: _UnmanagedHashNode, slot: _HashSlot)? { guard slot < endSlot else { return _next() } @@ -74,7 +75,8 @@ extension _HashTreeIterator: IteratorProtocol { @usableFromInline @_effects(releasenone) - internal mutating func _next() -> (node: _UnmanagedNode, slot: _Slot)? { + internal mutating func _next( + ) -> (node: _UnmanagedHashNode, slot: _HashSlot)? { if _o.isAtEnd { return nil } if node.hasChildren { _descendToLeftmostItem(ofChildAtSlot: .zero) @@ -98,7 +100,7 @@ extension _HashTreeIterator: IteratorProtocol { } extension _HashTreeIterator { - internal mutating func _descend(toChildSlot childSlot: _Slot) { + internal mutating func _descend(toChildSlot childSlot: _HashSlot) { assert(childSlot < node.childrenEndSlot) _o.ancestorSlots[_o.level] = childSlot _o.ancestorNodes.push(node) @@ -108,7 +110,7 @@ extension _HashTreeIterator { endSlot = node.itemsEndSlot } - internal mutating func _ascend() -> _Slot { + internal mutating func _ascend() -> _HashSlot { assert(!_o.level.isAtRoot) node = _o.ancestorNodes.pop() _o.level = _o.level.ascend() @@ -118,7 +120,7 @@ extension _HashTreeIterator { } internal mutating func _descendToLeftmostItem( - ofChildAtSlot childSlot: _Slot + ofChildAtSlot childSlot: _HashSlot ) { _descend(toChildSlot: childSlot) while endSlot == .zero { diff --git a/Sources/HashTreeCollections/Node/_HashTreeStatistics.swift b/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift similarity index 95% rename from Sources/HashTreeCollections/Node/_HashTreeStatistics.swift rename to Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift index 1161414d..9c5003c4 100644 --- a/Sources/HashTreeCollections/Node/_HashTreeStatistics.swift +++ b/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift @@ -86,9 +86,9 @@ public struct _HashTreeStatistics { } -extension _Node { +extension _HashNode { internal func gatherStatistics( - _ level: _Level, _ stats: inout _HashTreeStatistics + _ level: _HashLevel, _ stats: inout _HashTreeStatistics ) { // The empty singleton does not count as a node and occupies no space. if self.raw.storage === _emptySingleton { return } @@ -111,7 +111,7 @@ extension _Node { stats.capacityBytes += $0.byteCapacity stats.freeBytes += $0.bytesFree stats.itemBytes += $0.itemCount * (keyStride + valueStride) - stats.childBytes += $0.childCount * MemoryLayout<_RawNode>.stride + stats.childBytes += $0.childCount * MemoryLayout<_RawHashNode>.stride let objectHeaderSize = 2 * MemoryLayout.stride @@ -119,7 +119,7 @@ extension _Node { // the object header and the storage header. let start = _getUnsafePointerToStoredProperties(self.raw.storage) let capacity = self.raw.storage.capacity - let end = $0._memory + capacity * MemoryLayout<_RawNode>.stride + let end = $0._memory + capacity * MemoryLayout<_RawHashNode>.stride stats.grossBytes += objectHeaderSize + (end - start) for child in $0.children { diff --git a/Sources/HashTreeCollections/Node/_RawNode+UnsafeHandle.swift b/Sources/HashTreeCollections/HashNode/_RawHashNode+UnsafeHandle.swift similarity index 79% rename from Sources/HashTreeCollections/Node/_RawNode+UnsafeHandle.swift rename to Sources/HashTreeCollections/HashNode/_RawHashNode+UnsafeHandle.swift index f7ea8557..cd92cc37 100644 --- a/Sources/HashTreeCollections/Node/_RawNode+UnsafeHandle.swift +++ b/Sources/HashTreeCollections/HashNode/_RawHashNode+UnsafeHandle.swift @@ -9,12 +9,12 @@ // //===----------------------------------------------------------------------===// -extension _RawNode { +extension _RawHashNode { /// An unsafe, non-generic view of the data stored inside a node in the /// hash tree, hiding the mechanics of accessing storage from the code that /// uses it. /// - /// This is the non-generic equivalent of `_Node.UnsafeHandle`, sharing some + /// This is the non-generic equivalent of `_HashNode.UnsafeHandle`, sharing some /// of its functionality, but it only provides read-only access to the tree /// structure (incl. subtree counts) -- it doesn't provide any ways to mutate /// the underlying data or to access user payload. @@ -26,14 +26,14 @@ extension _RawNode { @frozen internal struct UnsafeHandle { @usableFromInline - internal let _header: UnsafePointer<_StorageHeader> + internal let _header: UnsafePointer<_HashNodeHeader> @usableFromInline internal let _memory: UnsafeRawPointer @inlinable internal init( - _ header: UnsafePointer<_StorageHeader>, + _ header: UnsafePointer<_HashNodeHeader>, _ memory: UnsafeRawPointer ) { self._header = header @@ -42,10 +42,10 @@ extension _RawNode { } } -extension _RawNode.UnsafeHandle { +extension _RawHashNode.UnsafeHandle { @inlinable @inline(__always) static func read( - _ node: _UnmanagedNode, + _ node: _UnmanagedHashNode, _ body: (Self) throws -> R ) rethrows -> R { try node.ref._withUnsafeGuaranteedRef { storage in @@ -56,7 +56,7 @@ extension _RawNode.UnsafeHandle { } } -extension _RawNode.UnsafeHandle { +extension _RawHashNode.UnsafeHandle { @inline(__always) internal var isCollisionNode: Bool { _header.pointee.isCollisionNode @@ -79,7 +79,7 @@ extension _RawNode.UnsafeHandle { } @inline(__always) - internal var childrenEndSlot: _Slot { + internal var childrenEndSlot: _HashSlot { _header.pointee.childrenEndSlot } @@ -94,23 +94,23 @@ extension _RawNode.UnsafeHandle { } @inline(__always) - internal var itemsEndSlot: _Slot { + internal var itemsEndSlot: _HashSlot { _header.pointee.itemsEndSlot } @inline(__always) - internal var _childrenStart: UnsafePointer<_RawNode> { - _memory.assumingMemoryBound(to: _RawNode.self) + internal var _childrenStart: UnsafePointer<_RawHashNode> { + _memory.assumingMemoryBound(to: _RawHashNode.self) } - internal subscript(child slot: _Slot) -> _RawNode { + internal subscript(child slot: _HashSlot) -> _RawHashNode { unsafeAddress { assert(slot < childrenEndSlot) return _childrenStart + slot.value } } - internal var children: UnsafeBufferPointer<_RawNode> { + internal var children: UnsafeBufferPointer<_RawHashNode> { UnsafeBufferPointer(start: _childrenStart, count: childCount) } } diff --git a/Sources/HashTreeCollections/Node/_RawNode.swift b/Sources/HashTreeCollections/HashNode/_RawHashNode.swift similarity index 82% rename from Sources/HashTreeCollections/Node/_RawNode.swift rename to Sources/HashTreeCollections/HashNode/_RawHashNode.swift index fe06e03c..56ff0b59 100644 --- a/Sources/HashTreeCollections/Node/_RawNode.swift +++ b/Sources/HashTreeCollections/HashNode/_RawHashNode.swift @@ -17,21 +17,21 @@ /// `distance(from:to:)`, `index(_:offsetBy:)` in non-generic code. @usableFromInline @frozen -internal struct _RawNode { +internal struct _RawHashNode { @usableFromInline - internal var storage: _RawStorage + internal var storage: _RawHashStorage @usableFromInline internal var count: Int @inlinable - internal init(storage: _RawStorage, count: Int) { + internal init(storage: _RawHashStorage, count: Int) { self.storage = storage self.count = count } } -extension _RawNode { +extension _RawHashNode { @inline(__always) internal func read(_ body: (UnsafeHandle) -> R) -> R { storage.withUnsafeMutablePointers { header, elements in @@ -40,22 +40,22 @@ extension _RawNode { } } -extension _RawNode { +extension _RawHashNode { @inlinable @inline(__always) - internal var unmanaged: _UnmanagedNode { - _UnmanagedNode(storage) + internal var unmanaged: _UnmanagedHashNode { + _UnmanagedHashNode(storage) } @inlinable @inline(__always) - internal func isIdentical(to other: _UnmanagedNode) -> Bool { + internal func isIdentical(to other: _UnmanagedHashNode) -> Bool { other.ref.toOpaque() == Unmanaged.passUnretained(storage).toOpaque() } } -extension _RawNode { +extension _RawHashNode { @usableFromInline internal func validatePath(_ path: _UnsafePath) { - var l = _Level.top + var l = _HashLevel.top var n = self.unmanaged while l < path.level { let slot = path.ancestors[l] diff --git a/Sources/HashTreeCollections/Node/_StorageHeader.swift b/Sources/HashTreeCollections/HashNode/_StorageHeader.swift similarity index 92% rename from Sources/HashTreeCollections/Node/_StorageHeader.swift rename to Sources/HashTreeCollections/HashNode/_StorageHeader.swift index 3684b4a9..4b04ed09 100644 --- a/Sources/HashTreeCollections/Node/_StorageHeader.swift +++ b/Sources/HashTreeCollections/HashNode/_StorageHeader.swift @@ -14,7 +14,7 @@ /// information about the currently occupied hash table buckets. @usableFromInline @frozen -internal struct _StorageHeader { +internal struct _HashNodeHeader { @usableFromInline internal var itemMap: _Bitmap @@ -37,7 +37,7 @@ internal struct _StorageHeader { } } -extension _StorageHeader { +extension _HashNodeHeader { @inlinable @inline(__always) internal var byteCapacity: Int { get { Int(truncatingIfNeeded: _byteCapacity) } @@ -54,7 +54,7 @@ extension _StorageHeader { } } -extension _StorageHeader { +extension _HashNodeHeader { @inlinable @inline(__always) internal var isEmpty: Bool { return itemMap.isEmpty && childMap.isEmpty @@ -101,13 +101,13 @@ extension _StorageHeader { } @inlinable @inline(__always) - internal var childrenEndSlot: _Slot { - _Slot(childCount) + internal var childrenEndSlot: _HashSlot { + _HashSlot(childCount) } @inlinable @inline(__always) - internal var itemsEndSlot: _Slot { - _Slot(itemCount) + internal var itemsEndSlot: _HashSlot { + _HashSlot(itemCount) } @inlinable @@ -125,7 +125,7 @@ extension _StorageHeader { } } -extension _StorageHeader { +extension _HashNodeHeader { @inlinable internal mutating func clear() { itemMap = .empty diff --git a/Sources/HashTreeCollections/Node/_UnmanagedNode.swift b/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift similarity index 69% rename from Sources/HashTreeCollections/Node/_UnmanagedNode.swift rename to Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift index 724efca8..e007ad18 100644 --- a/Sources/HashTreeCollections/Node/_UnmanagedNode.swift +++ b/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift @@ -12,24 +12,24 @@ import _CollectionsUtilities /// An unsafe, unowned, type-erased reference to a hash tree node; essentially -/// just a lightweight wrapper around `Unmanaged<_RawStorage>`. +/// just a lightweight wrapper around `Unmanaged<_RawHashStorage>`. /// /// Because such a reference may outlive the underlying object, use sites must -/// be extraordinarily careful to never dereference an invalid `_UnmanagedNode`. -/// Doing so results in undefined behavior. +/// be extraordinarily careful to never dereference an invalid +/// `_UnmanagedHashNode`. Doing so results in undefined behavior. @usableFromInline @frozen -internal struct _UnmanagedNode { +internal struct _UnmanagedHashNode { @usableFromInline - internal var ref: Unmanaged<_RawStorage> + internal var ref: Unmanaged<_RawHashStorage> @inlinable @inline(__always) - internal init(_ storage: _RawStorage) { + internal init(_ storage: _RawHashStorage) { self.ref = .passUnretained(storage) } } -extension _UnmanagedNode: Equatable { +extension _UnmanagedHashNode: Equatable { /// Indicates whether two unmanaged node references are equal. /// /// This function is safe to call even if one or both of its arguments are @@ -42,24 +42,24 @@ extension _UnmanagedNode: Equatable { } } -extension _UnmanagedNode: CustomStringConvertible { +extension _UnmanagedHashNode: CustomStringConvertible { @usableFromInline internal var description: String { _addressString(for: ref.toOpaque()) } } -extension _UnmanagedNode { +extension _UnmanagedHashNode { @inlinable @inline(__always) - internal func withRaw(_ body: (_RawStorage) -> R) -> R { + internal func withRaw(_ body: (_RawHashStorage) -> R) -> R { ref._withUnsafeGuaranteedRef(body) } @inline(__always) - internal func read(_ body: (_RawNode.UnsafeHandle) -> R) -> R { + internal func read(_ body: (_RawHashNode.UnsafeHandle) -> R) -> R { ref._withUnsafeGuaranteedRef { storage in storage.withUnsafeMutablePointers { header, elements in - body(_RawNode.UnsafeHandle(header, UnsafeRawPointer(elements))) + body(_RawHashNode.UnsafeHandle(header, UnsafeRawPointer(elements))) } } } @@ -85,17 +85,17 @@ extension _UnmanagedNode { } @inlinable - internal var itemsEndSlot: _Slot { - withRaw { _Slot($0.header.itemCount) } + internal var itemsEndSlot: _HashSlot { + withRaw { _HashSlot($0.header.itemCount) } } @inlinable - internal var childrenEndSlot: _Slot { - withRaw { _Slot($0.header.childCount) } + internal var childrenEndSlot: _HashSlot { + withRaw { _HashSlot($0.header.childCount) } } @inlinable - internal func unmanagedChild(at slot: _Slot) -> Self { + internal func unmanagedChild(at slot: _HashSlot) -> Self { withRaw { raw in assert(slot.value < raw.header.childCount) return raw.withUnsafeMutablePointerToElements { p in diff --git a/Sources/HashTreeCollections/Node/_UnsafePath.swift b/Sources/HashTreeCollections/HashNode/_UnsafePath.swift similarity index 92% rename from Sources/HashTreeCollections/Node/_UnsafePath.swift rename to Sources/HashTreeCollections/HashNode/_UnsafePath.swift index 58170d57..02cff820 100644 --- a/Sources/HashTreeCollections/Node/_UnsafePath.swift +++ b/Sources/HashTreeCollections/HashNode/_UnsafePath.swift @@ -24,7 +24,7 @@ /// including the final node on the path. /// /// However, to speed up common operations, path values also include a single -/// `_UnmanagedNode` reference to their final node. This reference does not +/// `_UnmanagedHashNode` reference to their final node. This reference does not /// keep the targeted node alive -- it is the use site's responsibility to /// ensure that the path is still valid before calling most of its operations. /// @@ -37,22 +37,22 @@ @frozen internal struct _UnsafePath { @usableFromInline - internal var ancestors: _AncestorSlots + internal var ancestors: _AncestorHashSlots @usableFromInline - internal var node: _UnmanagedNode + internal var node: _UnmanagedHashNode @usableFromInline - internal var nodeSlot: _Slot + internal var nodeSlot: _HashSlot @usableFromInline - internal var level: _Level + internal var level: _HashLevel @usableFromInline internal var _isItem: Bool @inlinable - internal init(root: __shared _RawNode) { + internal init(root: __shared _RawHashNode) { self.level = .top self.ancestors = .empty self.node = root.unmanaged @@ -63,10 +63,10 @@ internal struct _UnsafePath { extension _UnsafePath { internal init( - _ level: _Level, - _ ancestors: _AncestorSlots, - _ node: _UnmanagedNode, - childSlot: _Slot + _ level: _HashLevel, + _ ancestors: _AncestorHashSlots, + _ node: _UnmanagedHashNode, + childSlot: _HashSlot ) { assert(childSlot < node.childrenEndSlot) self.level = level @@ -78,10 +78,10 @@ extension _UnsafePath { @inlinable internal init( - _ level: _Level, - _ ancestors: _AncestorSlots, - _ node: _UnmanagedNode, - itemSlot: _Slot + _ level: _HashLevel, + _ ancestors: _AncestorHashSlots, + _ node: _UnmanagedHashNode, + itemSlot: _HashSlot ) { assert(itemSlot < node.itemsEndSlot) self.level = level @@ -126,7 +126,7 @@ extension _UnsafePath: Comparable { // Paths addressing items within a node are ordered before paths addressing // a child node within the same node. - var level: _Level = .top + var level: _HashLevel = .top while level < left.level, level < right.level { let l = left.ancestors[level] let r = right.ancestors[level] @@ -156,7 +156,7 @@ extension _UnsafePath: CustomStringConvertible { @usableFromInline internal var description: String { var d = "@" - var l: _Level = .top + var l: _HashLevel = .top while l < self.level { d += ".\(self.ancestors[l])" l = l.descend() @@ -226,7 +226,7 @@ extension _UnsafePath { /// - Note: It is undefined behavior to call this on a path that is no longer /// valid. @inlinable - internal var currentChild: _UnmanagedNode { + internal var currentChild: _UnmanagedHashNode { assert(isOnChild) return node.unmanagedChild(at: nodeSlot) } @@ -236,7 +236,7 @@ extension _UnsafePath { /// - Note: It is undefined behavior to call this on a path that is no longer /// valid. @inlinable - internal func childSlot(at level: _Level) -> _Slot { + internal func childSlot(at level: _HashLevel) -> _HashSlot { assert(level < self.level) return ancestors[level] } @@ -245,7 +245,7 @@ extension _UnsafePath { /// - Note: It is undefined behavior to call this on a path that is no longer /// valid. @inlinable @inline(__always) - internal var currentItemSlot: _Slot { + internal var currentItemSlot: _HashSlot { assert(isOnItem) return nodeSlot } @@ -258,7 +258,7 @@ extension _UnsafePath { /// - Note: It is undefined behavior to call this on a path that is no longer /// valid. @inlinable - internal mutating func selectItem(at slot: _Slot) { + internal mutating func selectItem(at slot: _HashSlot) { // As a special exception, this allows slot to equal the item count. // This can happen for paths that address the position a new item might be // inserted later. @@ -273,7 +273,7 @@ extension _UnsafePath { /// - Note: It is undefined behavior to call this on a path that is no longer /// valid. @inlinable - internal mutating func selectChild(at slot: _Slot) { + internal mutating func selectChild(at slot: _HashSlot) { // As a special exception, this allows slot to equal the child count. // This is equivalent to a call to `selectEnd()`. assert(slot <= node.childrenEndSlot) @@ -317,7 +317,7 @@ extension _UnsafePath { /// valid. @inlinable internal mutating func descendToChild( - _ child: _UnmanagedNode, at slot: _Slot + _ child: _UnmanagedHashNode, at slot: _HashSlot ) { assert(slot < node.childrenEndSlot) assert(child == node.unmanagedChild(at: slot)) @@ -328,7 +328,9 @@ extension _UnsafePath { self.level = level.descend() } - internal mutating func ascend(to ancestor: _UnmanagedNode, at level: _Level) { + internal mutating func ascend( + to ancestor: _UnmanagedHashNode, at level: _HashLevel + ) { guard level != self.level else { return } assert(level < self.level) self.level = level @@ -347,13 +349,13 @@ extension _UnsafePath { /// - Note: It is undefined behavior to call this on a path that is no longer /// valid. internal mutating func ascendToNearestAncestor( - under root: _RawNode, - where test: (_UnmanagedNode, _Slot) -> Bool + under root: _RawHashNode, + where test: (_UnmanagedHashNode, _HashSlot) -> Bool ) -> Bool { if self.level.isAtRoot { return false } var best: _UnsafePath? = nil var n = root.unmanaged - var l: _Level = .top + var l: _HashLevel = .top while l < self.level { let slot = self.ancestors[l] if test(n, slot) { @@ -442,7 +444,7 @@ extension _UnsafePath { /// path does not currently address an item. @usableFromInline @_effects(releasenone) - internal mutating func findSuccessorItem(under root: _RawNode) -> Bool { + internal mutating func findSuccessorItem(under root: _RawHashNode) -> Bool { guard isOnItem else { return false } if selectNextItem() { return true } if node.hasChildren { @@ -469,7 +471,7 @@ extension _UnsafePath { /// Return false if there is no previous item. @usableFromInline @_effects(releasenone) - internal mutating func findPredecessorItem(under root: _RawNode) -> Bool { + internal mutating func findPredecessorItem(under root: _RawHashNode) -> Bool { switch (isOnItem, nodeSlot > .zero) { case (true, true): selectItem(at: nodeSlot.previous()) @@ -505,14 +507,14 @@ extension _UnsafePath { } } -extension _RawNode { +extension _RawHashNode { /// Return the integer position of the item addressed by the given path /// within a preorder walk of the tree. If the path addresses the end /// position, then return the number of items in the tree. /// /// This method must only be called on the root node. internal func preorderPosition( - _ level: _Level, of path: _UnsafePath + _ level: _HashLevel, of path: _UnsafePath ) -> Int { if path.isOnNodeEnd { return count } assert(path.isOnItem) @@ -551,7 +553,7 @@ extension _UnsafePath { while !stop { let itemCount = node.itemCount if remaining < itemCount { - selectItem(at: _Slot(remaining)) + selectItem(at: _HashSlot(remaining)) return (true, 0) } remaining -= itemCount @@ -560,7 +562,7 @@ extension _UnsafePath { for i in children.indices { let c = children[i].count if remaining < c { - descendToChild(children[i].unmanaged, at: _Slot(i)) + descendToChild(children[i].unmanaged, at: _HashSlot(i)) return } remaining &-= c @@ -574,7 +576,7 @@ extension _UnsafePath { } } -extension _RawNode { +extension _RawHashNode { /// Return the number of steps between two paths within a preorder walk of the /// tree. The two paths must not address a child node. /// @@ -582,7 +584,7 @@ extension _RawNode { @usableFromInline @_effects(releasenone) internal func distance( - _ level: _Level, from start: _UnsafePath, to end: _UnsafePath + _ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath ) -> Int { assert(level.isAtRoot) if start.isOnNodeEnd { @@ -623,7 +625,7 @@ extension _RawNode { } internal func _distance( - _ level: _Level, from start: _UnsafePath, to end: _UnsafePath + _ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath ) -> Int { assert(start < end) assert(level < start.level) @@ -648,9 +650,9 @@ extension _RawNode { } } -extension _UnmanagedNode { +extension _UnmanagedHashNode { internal func _distance( - _ level: _Level, fromItemAt start: _Slot, to end: _UnsafePath + _ level: _HashLevel, fromItemAt start: _HashSlot, to end: _UnsafePath ) -> Int { read { assert(start < $0.itemsEndSlot) @@ -666,7 +668,7 @@ extension _UnmanagedNode { } } -extension _Node { +extension _HashNode { /// Return the path to the given key in this tree if it exists; otherwise /// return nil. @inlinable @@ -674,8 +676,8 @@ extension _Node { to key: Key, _ hash: _Hash ) -> _UnsafePath? { var node = unmanaged - var level: _Level = .top - var ancestors: _AncestorSlots = .empty + var level: _HashLevel = .top + var ancestors: _AncestorHashSlots = .empty while true { let r = UnsafeHandle.read(node) { $0.find(level, key, hash) } guard let r = r else { break } @@ -690,11 +692,11 @@ extension _Node { } } -extension _RawNode { +extension _RawHashNode { @usableFromInline @_effects(releasenone) internal func seek( - _ level: _Level, + _ level: _HashLevel, _ path: inout _UnsafePath, offsetBy distance: Int, limitedBy limit: _UnsafePath @@ -718,7 +720,7 @@ extension _RawNode { @usableFromInline @_effects(releasenone) internal func seek( - _ level: _Level, + _ level: _HashLevel, _ path: inout _UnsafePath, offsetBy distance: Int ) -> Bool { @@ -733,7 +735,7 @@ extension _RawNode { } internal func _seek( - _ level: _Level, + _ level: _HashLevel, _ path: inout _UnsafePath, offsetBy distance: inout Int ) -> Bool { @@ -768,7 +770,7 @@ extension _RawNode { let slot = path.nodeSlot distance &+= slot.value if distance >= 0 { - path.selectItem(at: _Slot(distance)) + path.selectItem(at: _HashSlot(distance)) distance = 0 return true } @@ -782,7 +784,7 @@ extension _RawNode { /// Find the item at the given positive distance from the last item within the /// subtree rooted at the current node in `path`. internal func _seekForward( - _ level: _Level, + _ level: _HashLevel, by distance: inout Int, fromSubtree path: inout _UnsafePath ) -> Bool { @@ -806,7 +808,7 @@ extension _RawNode { while i < children.endIndex { let c = children[i].count if distance < c { - path.descendToChild(children[i].unmanaged, at: _Slot(i)) + path.descendToChild(children[i].unmanaged, at: _HashSlot(i)) let r = path.findItemAtPreorderPosition(distance) precondition(r.found, "Internal inconsistency: invalid node counts") assert(r.remaining == 0) @@ -824,7 +826,7 @@ extension _RawNode { /// Find the item at the given negative distance from the first item within the /// subtree rooted at the current node in `path`. internal func _seekBackward( - _ level: _Level, + _ level: _HashLevel, by distance: inout Int, fromSubtree path: inout _UnsafePath ) -> Bool { @@ -833,7 +835,7 @@ extension _RawNode { return read { let children = $0.children - var slot: _Slot + var slot: _HashSlot if level < path.level { // We need to descend to the end of the path before we can start the // search for real. @@ -875,7 +877,7 @@ extension _RawNode { // See if the target is hiding somwhere in our immediate items. distance &+= $0.itemCount if distance >= 0 { - path.selectItem(at: _Slot(distance)) + path.selectItem(at: _HashSlot(distance)) distance = 0 return true } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift index e05279f2..86089e61 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift @@ -19,7 +19,7 @@ extension TreeDictionary { @frozen public struct Index { @usableFromInline - internal let _root: _UnmanagedNode + internal let _root: _UnmanagedHashNode @usableFromInline internal var _version: UInt @@ -29,7 +29,7 @@ extension TreeDictionary { @inlinable @inline(__always) internal init( - _root: _UnmanagedNode, version: UInt, path: _UnsafePath + _root: _UnmanagedHashNode, version: UInt, path: _UnsafePath ) { self._root = _root self._version = version diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Debugging.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Debugging.swift index 17a6c52a..51ec6531 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Debugging.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Debugging.swift @@ -32,7 +32,7 @@ extension TreeDictionary { } public static var _maxDepth: Int { - _Level.limit + _HashLevel.limit } public var _statistics: _HashTreeStatistics { diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift index 8098cbf2..d714afaa 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift @@ -16,7 +16,7 @@ extension TreeDictionary { @frozen public struct Keys { @usableFromInline - internal typealias _Node = HashTreeCollections._Node + internal typealias _HashNode = HashTreeCollections._HashNode @usableFromInline internal var _base: TreeDictionary diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift index b3ef68b1..8f41384d 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift @@ -22,13 +22,13 @@ extension TreeDictionary: Sequence { // before any items within children. @usableFromInline - internal typealias _UnsafeHandle = _Node.UnsafeHandle + internal typealias _UnsafeHandle = _HashNode.UnsafeHandle @usableFromInline internal var _it: _HashTreeIterator @inlinable - internal init(_root: _RawNode) { + internal init(_root: _RawHashNode) { self._it = _HashTreeIterator(root: _root) } } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift index cb0c6a3b..67d80fb5 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift @@ -16,10 +16,10 @@ extension TreeDictionary { @frozen public struct Values { @usableFromInline - internal typealias _Node = HashTreeCollections._Node + internal typealias _HashNode = HashTreeCollections._HashNode @usableFromInline - internal typealias _UnsafeHandle = _Node.UnsafeHandle + internal typealias _UnsafeHandle = _HashNode.UnsafeHandle @usableFromInline internal var _base: TreeDictionary diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift index 7b4c5611..99e287ad 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift @@ -65,13 +65,13 @@ @frozen // Not really -- this package is not at all ABI stable public struct TreeDictionary { @usableFromInline - internal typealias _Node = HashTreeCollections._Node + internal typealias _HashNode = HashTreeCollections._HashNode @usableFromInline - internal typealias _UnsafeHandle = _Node.UnsafeHandle + internal typealias _UnsafeHandle = _HashNode.UnsafeHandle @usableFromInline - var _root: _Node + var _root: _HashNode /// The version number of this instance, used for quick index validation. /// This is initialized to a (very weakly) random value and it gets @@ -80,13 +80,13 @@ public struct TreeDictionary { var _version: UInt @inlinable - internal init(_root: _Node, version: UInt) { + internal init(_root: _HashNode, version: UInt) { self._root = _root self._version = version } @inlinable - internal init(_new: _Node) { + internal init(_new: _HashNode) { self.init(_root: _new, version: _new.initialVersionNumber) } } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift index 7817af25..ad45426a 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift @@ -19,7 +19,7 @@ extension TreeSet { @frozen public struct Index { @usableFromInline - internal let _root: _UnmanagedNode + internal let _root: _UnmanagedHashNode @usableFromInline internal var _version: UInt @@ -29,7 +29,7 @@ extension TreeSet { @inlinable @inline(__always) internal init( - _root: _UnmanagedNode, version: UInt, path: _UnsafePath + _root: _UnmanagedHashNode, version: UInt, path: _UnsafePath ) { self._root = _root self._version = version diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Debugging.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Debugging.swift index 14d69fa0..27467db0 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Debugging.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Debugging.swift @@ -32,7 +32,7 @@ extension TreeSet { } public static var _maxDepth: Int { - _Level.limit + _HashLevel.limit } public var _statistics: _HashTreeStatistics { diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift index cd0e3fdf..aff2c0ce 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift @@ -14,13 +14,13 @@ extension TreeSet: Sequence { @frozen public struct Iterator: IteratorProtocol { @usableFromInline - internal typealias _UnsafeHandle = _Node.UnsafeHandle + internal typealias _UnsafeHandle = _HashNode.UnsafeHandle @usableFromInline internal var _it: _HashTreeIterator @inlinable - internal init(_root: _RawNode) { + internal init(_root: _RawHashNode) { _it = _HashTreeIterator(root: _root) } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift index f90000f9..ab052d27 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift @@ -62,7 +62,7 @@ extension TreeSet { @inlinable internal func _intersection( - _ other: HashTreeCollections._Node + _ other: HashTreeCollections._HashNode ) -> Self { guard let r = _root.intersection(.top, other) else { return self } return Self(_new: r) @@ -97,7 +97,7 @@ extension TreeSet { return self.filter { other.contains($0) } } - var result: _Node = ._emptyNode() + var result: _HashNode = ._emptyNode() for item in other { let hash = _Hash(item) if let r = self._root.lookup(.top, item, hash) { diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift index 50876252..61066ac8 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift @@ -102,7 +102,7 @@ extension TreeSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node? = ._emptyNode() + var seen: _HashNode? = ._emptyNode() var it = other.makeIterator() while let item = it.next() { let hash = _Hash(item) diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift index be71ea6b..eddd4319 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift @@ -111,7 +111,7 @@ extension TreeSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node = ._emptyNode() + var seen: _HashNode = ._emptyNode() var doneCollecting = false var isStrict = false var it = other.makeIterator() diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift index 8a1633ca..551e2c44 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift @@ -108,7 +108,7 @@ extension TreeSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node = ._emptyNode() + var seen: _HashNode = ._emptyNode() for item in other { let hash = _Hash(item) guard self._root.containsKey(.top, item, hash) else { return false } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift index fb0d216b..345a53e4 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift @@ -99,7 +99,7 @@ extension TreeSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _Node = ._emptyNode() + var seen: _HashNode = ._emptyNode() for item in other { let hash = _Hash(item) guard _root.containsKey(.top, item, hash) else { continue } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift index 78fba0d0..c9e39e43 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift @@ -54,7 +54,7 @@ extension TreeSet { @inlinable internal __consuming func _subtracting( - _ other: HashTreeCollections._Node + _ other: HashTreeCollections._HashNode ) -> Self { guard let r = _root.subtracting(.top, other) else { return self } return Self(_new: r) diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet.swift b/Sources/HashTreeCollections/TreeSet/TreeSet.swift index 8ca4c6e4..3c9d4c00 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet.swift @@ -60,25 +60,25 @@ @frozen // Not really -- this package is not at all ABI stable public struct TreeSet { @usableFromInline - internal typealias _Node = HashTreeCollections._Node + internal typealias _HashNode = HashTreeCollections._HashNode @usableFromInline - internal typealias _UnsafeHandle = _Node.UnsafeHandle + internal typealias _UnsafeHandle = _HashNode.UnsafeHandle @usableFromInline - internal var _root: _Node + internal var _root: _HashNode @usableFromInline internal var _version: UInt @inlinable - internal init(_root: _Node, version: UInt) { + internal init(_root: _HashNode, version: UInt) { self._root = _root self._version = version } @inlinable - internal init(_new: _Node) { + internal init(_new: _HashNode) { self.init(_root: _new, version: _new.initialVersionNumber) } } From cc181a3bce5a14d51e5b388f7c1e44245b0a9438 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 16:39:03 -0700 Subject: [PATCH 081/113] =?UTF-8?q?HeapModule:=20=5FNode=20=E2=86=92=20=5F?= =?UTF-8?q?HeapNode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes this name unique throughout the package, allowing this code to be built as a single, huge module. --- Sources/HeapModule/CMakeLists.txt | 2 +- Sources/HeapModule/Heap+Invariants.swift | 2 +- Sources/HeapModule/Heap+UnsafeHandle.swift | 76 +++++++++---------- Sources/HeapModule/Heap.swift | 6 +- .../{_Node.swift => _HeapNode.swift} | 26 +++---- 5 files changed, 56 insertions(+), 56 deletions(-) rename Sources/HeapModule/{_Node.swift => _HeapNode.swift} (86%) diff --git a/Sources/HeapModule/CMakeLists.txt b/Sources/HeapModule/CMakeLists.txt index 9e0bb6da..2249aa47 100644 --- a/Sources/HeapModule/CMakeLists.txt +++ b/Sources/HeapModule/CMakeLists.txt @@ -8,7 +8,7 @@ See https://swift.org/LICENSE.txt for license information #]] add_library(HeapModule - "_Node.swift" + "_HeapNode.swift" "Heap.swift" "Heap+Descriptions.swift" "Heap+ExpressibleByArrayLiteral.swift" diff --git a/Sources/HeapModule/Heap+Invariants.swift b/Sources/HeapModule/Heap+Invariants.swift index 12e9192a..a78b4dc9 100644 --- a/Sources/HeapModule/Heap+Invariants.swift +++ b/Sources/HeapModule/Heap+Invariants.swift @@ -33,7 +33,7 @@ extension Heap { } @inlinable - internal func _checkInvariants(node: _Node, min: Element?, max: Element?) { + internal func _checkInvariants(node: _HeapNode, min: Element?, max: Element?) { let value = _storage[node.offset] if let min = min { precondition(value >= min, diff --git a/Sources/HeapModule/Heap+UnsafeHandle.swift b/Sources/HeapModule/Heap+UnsafeHandle.swift index 601a5ec6..709d7dc9 100644 --- a/Sources/HeapModule/Heap+UnsafeHandle.swift +++ b/Sources/HeapModule/Heap+UnsafeHandle.swift @@ -36,7 +36,7 @@ extension Heap._UnsafeHandle { } @inlinable - subscript(node: _Node) -> Element { + subscript(node: _HeapNode) -> Element { @inline(__always) get { buffer[node.offset] @@ -48,7 +48,7 @@ extension Heap._UnsafeHandle { } @inlinable @inline(__always) - internal func ptr(to node: _Node) -> UnsafeMutablePointer { + internal func ptr(to node: _HeapNode) -> UnsafeMutablePointer { assert(node.offset < count) return buffer.baseAddress! + node.offset } @@ -56,43 +56,43 @@ extension Heap._UnsafeHandle { /// Move the value at the specified node out of the buffer, leaving it /// uninitialized. @inlinable @inline(__always) - internal func extract(_ node: _Node) -> Element { + internal func extract(_ node: _HeapNode) -> Element { ptr(to: node).move() } @inlinable @inline(__always) - internal func initialize(_ node: _Node, to value: __owned Element) { + internal func initialize(_ node: _HeapNode, to value: __owned Element) { ptr(to: node).initialize(to: value) } /// Swaps the elements in the heap at the given indices. @inlinable @inline(__always) - internal func swapAt(_ i: _Node, _ j: _Node) { + internal func swapAt(_ i: _HeapNode, _ j: _HeapNode) { buffer.swapAt(i.offset, j.offset) } /// Swaps the element at the given node with the supplied value. @inlinable @inline(__always) - internal func swapAt(_ i: _Node, with value: inout Element) { + internal func swapAt(_ i: _HeapNode, with value: inout Element) { let p = buffer.baseAddress.unsafelyUnwrapped + i.offset swap(&p.pointee, &value) } @inlinable @inline(__always) - internal func minValue(_ a: _Node, _ b: _Node) -> _Node { + internal func minValue(_ a: _HeapNode, _ b: _HeapNode) -> _HeapNode { self[a] < self[b] ? a : b } @inlinable @inline(__always) - internal func maxValue(_ a: _Node, _ b: _Node) -> _Node { + internal func maxValue(_ a: _HeapNode, _ b: _HeapNode) -> _HeapNode { self[a] < self[b] ? b : a } } extension Heap._UnsafeHandle { @inlinable - internal func bubbleUp(_ node: _Node) { + internal func bubbleUp(_ node: _HeapNode) { guard !node.isRoot else { return } let parent = node.parent() @@ -124,7 +124,7 @@ extension Heap._UnsafeHandle { /// Sink the item at `node` to its correct position in the heap. /// The given node must be minimum-ordered. @inlinable - internal func trickleDownMin(_ node: _Node) { + internal func trickleDownMin(_ node: _HeapNode) { assert(node.isMinLevel) var node = node var value = extract(node) @@ -133,11 +133,11 @@ extension Heap._UnsafeHandle { } @inlinable @inline(__always) - internal func _trickleDownMin(node: inout _Node, value: inout Element) { - // Note: `_Node` is quite the useless abstraction here, as we don't need + internal func _trickleDownMin(node: inout _HeapNode, value: inout Element) { + // Note: `_HeapNode` is quite the useless abstraction here, as we don't need // to look at its `level` property, and we need to move sideways amongst // siblings/cousins in the tree, for which we don't have direct operations. - // Luckily, all the `_Node` business gets optimized away, so this only + // Luckily, all the `_HeapNode` business gets optimized away, so this only // affects the readability of the code, not its performance. // The alternative would be to reintroduce offset-based parent/child // navigation methods, which seems less palatable. @@ -147,11 +147,11 @@ extension Heap._UnsafeHandle { // Invariant: buffer slot at `node` is uninitialized // We have four grandchildren, so we don't need to compare children. - let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level) + let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) let minA = minValue(gc0, gc1) - let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level) - let gc3 = _Node(offset: gc0.offset &+ 3, level: gc0.level) + let gc2 = _HeapNode(offset: gc0.offset &+ 2, level: gc0.level) + let gc3 = _HeapNode(offset: gc0.offset &+ 3, level: gc0.level) let minB = minValue(gc2, gc3) let min = minValue(minA, minB) @@ -205,23 +205,23 @@ extension Heap._UnsafeHandle { /// This method is an implementation detail of `trickleDownMin`. Do not call /// it directly. @inlinable - internal func _minDescendant(c0: _Node, gc0: _Node) -> _Node { + internal func _minDescendant(c0: _HeapNode, gc0: _HeapNode) -> _HeapNode { assert(c0.offset < count) assert(gc0.offset + 3 >= count) if gc0.offset < count { if gc0.offset &+ 2 < count { // We have three grandchildren. We don't need to compare direct children. - let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level) - let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level) + let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) + let gc2 = _HeapNode(offset: gc0.offset &+ 2, level: gc0.level) return minValue(minValue(gc0, gc1), gc2) } - let c1 = _Node(offset: c0.offset &+ 1, level: c0.level) + let c1 = _HeapNode(offset: c0.offset &+ 1, level: c0.level) let m = minValue(c1, gc0) if gc0.offset &+ 1 < count { // Two grandchildren. - let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level) + let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) return minValue(m, gc1) } @@ -229,7 +229,7 @@ extension Heap._UnsafeHandle { return m } - let c1 = _Node(offset: c0.offset &+ 1, level: c0.level) + let c1 = _HeapNode(offset: c0.offset &+ 1, level: c0.level) if c1.offset < count { return minValue(c0, c1) } @@ -240,7 +240,7 @@ extension Heap._UnsafeHandle { /// Sink the item at `node` to its correct position in the heap. /// The given node must be maximum-ordered. @inlinable - internal func trickleDownMax(_ node: _Node) { + internal func trickleDownMax(_ node: _HeapNode) { assert(!node.isMinLevel) var node = node var value = extract(node) @@ -250,19 +250,19 @@ extension Heap._UnsafeHandle { } @inlinable @inline(__always) - internal func _trickleDownMax(node: inout _Node, value: inout Element) { - // See note on `_Node` in `_trickleDownMin` above. + internal func _trickleDownMax(node: inout _HeapNode, value: inout Element) { + // See note on `_HeapNode` in `_trickleDownMin` above. var gc0 = node.firstGrandchild() while gc0.offset &+ 3 < count { // Invariant: buffer slot at `node` is uninitialized // We have four grandchildren, so we don't need to compare children. - let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level) + let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) let maxA = maxValue(gc0, gc1) - let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level) - let gc3 = _Node(offset: gc0.offset &+ 3, level: gc0.level) + let gc2 = _HeapNode(offset: gc0.offset &+ 2, level: gc0.level) + let gc3 = _HeapNode(offset: gc0.offset &+ 3, level: gc0.level) let maxB = maxValue(gc2, gc3) let max = maxValue(maxA, maxB) @@ -316,23 +316,23 @@ extension Heap._UnsafeHandle { /// This method is an implementation detail of `trickleDownMax`. Do not call /// it directly. @inlinable - internal func _maxDescendant(c0: _Node, gc0: _Node) -> _Node { + internal func _maxDescendant(c0: _HeapNode, gc0: _HeapNode) -> _HeapNode { assert(c0.offset < count) assert(gc0.offset + 3 >= count) if gc0.offset < count { if gc0.offset &+ 2 < count { // We have three grandchildren. We don't need to compare direct children. - let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level) - let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level) + let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) + let gc2 = _HeapNode(offset: gc0.offset &+ 2, level: gc0.level) return maxValue(maxValue(gc0, gc1), gc2) } - let c1 = _Node(offset: c0.offset &+ 1, level: c0.level) + let c1 = _HeapNode(offset: c0.offset &+ 1, level: c0.level) let m = maxValue(c1, gc0) if gc0.offset &+ 1 < count { // Two grandchildren. - let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level) + let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) return maxValue(m, gc1) } @@ -340,7 +340,7 @@ extension Heap._UnsafeHandle { return m } - let c1 = _Node(offset: c0.offset &+ 1, level: c0.level) + let c1 = _HeapNode(offset: c0.offset &+ 1, level: c0.level) if c1.offset < count { return maxValue(c0, c1) } @@ -358,18 +358,18 @@ extension Heap._UnsafeHandle { // FIXME: See if a more cache friendly algorithm would be faster. let limit = count / 2 // The first offset without a left child - var level = _Node.level(forOffset: limit &- 1) + var level = _HeapNode.level(forOffset: limit &- 1) while level >= 0 { - let nodes = _Node.allNodes(onLevel: level, limit: limit) + let nodes = _HeapNode.allNodes(onLevel: level, limit: limit) _heapify(level, nodes) level &-= 1 } } @inlinable - internal func _heapify(_ level: Int, _ nodes: ClosedRange<_Node>?) { + internal func _heapify(_ level: Int, _ nodes: ClosedRange<_HeapNode>?) { guard let nodes = nodes else { return } - if _Node.isMinLevel(level) { + if _HeapNode.isMinLevel(level) { nodes._forEach { node in trickleDownMin(node) } diff --git a/Sources/HeapModule/Heap.swift b/Sources/HeapModule/Heap.swift index 995c3208..d63017e1 100644 --- a/Sources/HeapModule/Heap.swift +++ b/Sources/HeapModule/Heap.swift @@ -76,7 +76,7 @@ extension Heap { _storage.append(element) _update { handle in - handle.bubbleUp(_Node(offset: handle.count - 1)) + handle.bubbleUp(_HeapNode(offset: handle.count - 1)) } _checkInvariants() } @@ -119,7 +119,7 @@ extension Heap { if _storage.count > 0 { _update { handle in - let minNode = _Node.root + let minNode = _HeapNode.root handle.swapAt(minNode, with: &removed) handle.trickleDownMin(minNode) } @@ -191,7 +191,7 @@ extension Heap { var removed = replacement _update { handle in - let minNode = _Node.root + let minNode = _HeapNode.root handle.swapAt(minNode, with: &removed) handle.trickleDownMin(minNode) } diff --git a/Sources/HeapModule/_Node.swift b/Sources/HeapModule/_HeapNode.swift similarity index 86% rename from Sources/HeapModule/_Node.swift rename to Sources/HeapModule/_HeapNode.swift index a6763960..e3044c67 100644 --- a/Sources/HeapModule/_Node.swift +++ b/Sources/HeapModule/_HeapNode.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// @usableFromInline @frozen -internal struct _Node { +internal struct _HeapNode { @usableFromInline internal var offset: Int @@ -33,7 +33,7 @@ internal struct _Node { } } -extension _Node: Comparable { +extension _HeapNode: Comparable { @inlinable @inline(__always) internal static func ==(left: Self, right: Self) -> Bool { left.offset == right.offset @@ -45,29 +45,29 @@ extension _Node: Comparable { } } -extension _Node: CustomStringConvertible { +extension _HeapNode: CustomStringConvertible { @usableFromInline internal var description: String { "(offset: \(offset), level: \(level))" } } -extension _Node { +extension _HeapNode { @inlinable @inline(__always) internal static func level(forOffset offset: Int) -> Int { (offset &+ 1)._binaryLogarithm() } @inlinable @inline(__always) - internal static func firstNode(onLevel level: Int) -> _Node { + internal static func firstNode(onLevel level: Int) -> _HeapNode { assert(level >= 0) - return _Node(offset: (1 &<< level) &- 1, level: level) + return _HeapNode(offset: (1 &<< level) &- 1, level: level) } @inlinable @inline(__always) - internal static func lastNode(onLevel level: Int) -> _Node { + internal static func lastNode(onLevel level: Int) -> _HeapNode { assert(level >= 0) - return _Node(offset: (1 &<< (level &+ 1)) &- 2, level: level) + return _HeapNode(offset: (1 &<< (level &+ 1)) &- 2, level: level) } @inlinable @inline(__always) @@ -76,7 +76,7 @@ extension _Node { } } -extension _Node { +extension _HeapNode { /// The root node in the heap. @inlinable @inline(__always) internal static var root: Self { @@ -106,7 +106,7 @@ extension _Node { } } -extension _Node { +extension _HeapNode { /// Returns the parent of this index, or `nil` if the index has no parent /// (i.e. when this is the root index). @inlinable @inline(__always) @@ -160,11 +160,11 @@ extension _Node { } } -extension ClosedRange where Bound == _Node { +extension ClosedRange where Bound == _HeapNode { @inlinable @inline(__always) - internal func _forEach(_ body: (_Node) -> Void) { + internal func _forEach(_ body: (_HeapNode) -> Void) { assert( - isEmpty || _Node.level(forOffset: upperBound.offset) == lowerBound.level) + isEmpty || _HeapNode.level(forOffset: upperBound.offset) == lowerBound.level) var node = self.lowerBound while node.offset <= self.upperBound.offset { body(node) From cbab9e3737241d89cbec63a7ae04d89bb618870c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 17:20:33 -0700 Subject: [PATCH 082/113] Introduce COLLECTIONS_SINGLE_MODULE condition --- Package.swift | 5 +++ .../BitArray+ChunkedBitsIterators.swift | 2 ++ .../BitArray/BitArray+Copy.swift | 2 ++ .../BitArray/BitArray+Invariants.swift | 2 ++ .../BitArray/BitArray._UnsafeHandle.swift | 2 ++ .../BitCollections/BitArray/BitArray.swift | 2 ++ .../BitCollections/BitSet/BitSet+Extras.swift | 2 ++ .../BitSet/BitSet+Initializers.swift | 2 ++ .../BitSet/BitSet+Invariants.swift | 2 ++ .../BitSet/BitSet+SetAlgebra isEqualSet.swift | 2 ++ .../BitSet+SetAlgebra isStrictSubset.swift | 2 ++ .../BitSet+SetAlgebra isStrictSuperset.swift | 2 ++ .../BitSet+Sorted Collection APIs.swift | 2 ++ .../BitSet/BitSet.Counted.swift | 2 ++ .../BitCollections/BitSet/BitSet.Index.swift | 2 ++ .../BitSet/BitSet._UnsafeHandle.swift | 2 ++ Sources/BitCollections/BitSet/BitSet.swift | 2 ++ .../BitCollections/Shared/UInt+Tricks.swift | 2 ++ Sources/BitCollections/Shared/_Word.swift | 2 ++ Sources/DequeModule/Deque+Collection.swift | 2 ++ Sources/DequeModule/Deque+Descriptions.swift | 2 ++ Sources/DequeModule/Deque+Extras.swift | 2 ++ Sources/DequeModule/Deque+Testing.swift | 2 ++ .../DequeModule/_UnsafeWrappedBuffer.swift | 2 ++ .../HashNode/_Bitmap.swift | 2 ++ .../HashNode/_HashNode+Debugging.swift | 2 ++ .../HashNode/_HashNode+Initializers.swift | 2 ++ .../HashNode/_HashNode+Storage.swift | 2 ++ .../_HashNode+Structural mapValues.swift | 2 ++ .../_HashNode+Subtree Insertions.swift | 2 ++ .../HashNode/_UnmanagedHashNode.swift | 2 ++ .../TreeDictionary+Debugging.swift | 2 ++ .../TreeDictionary+Descriptions.swift | 2 ++ .../TreeDictionary/TreeDictionary+Keys.swift | 2 ++ .../TreeDictionary+Values.swift | 2 ++ .../TreeSet/TreeSet+Debugging.swift | 2 ++ .../TreeSet/TreeSet+Descriptions.swift | 2 ++ .../TreeSet/TreeSet+Equatable.swift | 2 ++ .../TreeSet/TreeSet+Extras.swift | 2 ++ .../TreeSet/TreeSet+SetAlgebra basics.swift | 2 ++ .../TreeSet+SetAlgebra isEqualSet.swift | 2 ++ .../TreeSet+SetAlgebra isStrictSubset.swift | 2 ++ .../TreeSet+SetAlgebra isStrictSuperset.swift | 2 ++ .../TreeSet/TreeSet+SetAlgebra isSubset.swift | 2 ++ ...eeSet+SetAlgebra symmetricDifference.swift | 2 ++ Sources/HeapModule/Heap+Invariants.swift | 2 ++ .../HashTable/_HashTable+UnsafeHandle.swift | 2 ++ .../OrderedDictionary+Descriptions.swift | 2 ++ ...deredDictionary+Elements.SubSequence.swift | 2 ++ .../OrderedDictionary+Elements.swift | 2 ++ .../OrderedDictionary+Invariants.swift | 2 ++ .../OrderedDictionary+Values.swift | 2 ++ .../OrderedSet/OrderedSet+Descriptions.swift | 2 ++ .../OrderedSet/OrderedSet+Initializers.swift | 2 ++ .../OrderedSet/OrderedSet+Invariants.swift | 2 ++ ...OrderedSet+Partial MutableCollection.swift | 2 ++ ...dSet+Partial SetAlgebra intersection.swift | 2 ++ ...redSet+Partial SetAlgebra isDisjoint.swift | 2 ++ ...redSet+Partial SetAlgebra isEqualSet.swift | 2 ++ ...et+Partial SetAlgebra isStrictSubset.swift | 2 ++ ...+Partial SetAlgebra isStrictSuperset.swift | 2 ++ ...deredSet+Partial SetAlgebra isSubset.swift | 2 ++ ...edSet+Partial SetAlgebra subtracting.swift | 2 ++ ...rtial SetAlgebra symmetricDifference.swift | 2 ++ .../OrderedSet+RandomAccessCollection.swift | 2 ++ .../OrderedSet/OrderedSet+SubSequence.swift | 2 ++ .../OrderedSet/OrderedSet+Testing.swift | 2 ++ .../OrderedSet/OrderedSet+UnorderedView.swift | 2 ++ .../OrderedSet/OrderedSet.swift | 2 ++ .../Utilities/_UnsafeBitset.swift | 3 +- .../Rope/Basics/Rope+Debugging.swift | 15 ++------- .../RopeModule/Rope/Basics/Rope+_Node.swift | 2 +- .../Utilities/_CharacterRecognizer.swift | 4 --- .../SortedCollectionAPIChecker.swift | 2 ++ Tests/BitCollectionsTests/BitArrayTests.swift | 4 +++ .../BitSet.Counted Tests.swift | 4 +++ Tests/BitCollectionsTests/BitSetTests.swift | 4 +++ .../CombinatoricsChecks.swift | 2 ++ .../IndexRangeCollectionTests.swift | 2 ++ .../MinimalTypeConformances.swift | 2 ++ Tests/DequeTests/DequeInternals.swift | 4 +++ Tests/DequeTests/DequeTests.swift | 4 +++ Tests/DequeTests/MutableCollectionTests.swift | 4 +++ .../RangeReplaceableCollectionTests.swift | 4 +++ .../TreeDictionary Smoke Tests.swift | 4 +++ .../TreeDictionary Tests.swift | 4 +++ .../TreeDictionary.Keys Tests.swift | 4 +++ .../TreeDictionary.Values Tests.swift | 4 +++ .../TreeHashedCollections Fixtures.swift | 4 +++ .../TreeSet Tests.swift | 4 +++ .../HashTreeCollectionsTests/Utilities.swift | 4 +++ Tests/HeapTests/HeapTests.swift | 4 +++ .../OrderedDictionary Tests.swift | 5 ++- .../OrderedDictionary Utils.swift | 4 +++ .../OrderedDictionary+Elements Tests.swift | 5 ++- .../OrderedDictionary+Values Tests.swift | 5 ++- .../OrderedSet/OrderedSet Diffing Tests.swift | 4 +++ .../OrderedSet.UnorderedView Tests.swift | 4 +++ .../OrderedSet/OrderedSetInternals.swift | 4 +++ .../OrderedSet/OrderedSetTests.swift | 4 +++ Tests/RopeModuleTests/SampleStrings.swift | 33 ++++++++++--------- Tests/RopeModuleTests/TestBigString.swift | 6 +++- Tests/RopeModuleTests/TestRope.swift | 7 +++- 103 files changed, 276 insertions(+), 38 deletions(-) diff --git a/Package.swift b/Package.swift index 13d3f242..93e3430c 100644 --- a/Package.swift +++ b/Package.swift @@ -47,6 +47,11 @@ var defines: [String] = [ // Enable modules that aren't source stable yet, and aren't ready for general use. // "COLLECTIONS_ENABLE_UNSTABLE_MODULES", + + // Enable this to allow building the sources as a single, large module. + // Note: this setting isn't a supported package configuration, but it's listed + // here for completeness. +// "COLLECTIONS_SINGLE_MODULE", ] var _modules: [String] = [] diff --git a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift index 2f50b921..8017b676 100644 --- a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift +++ b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif internal struct _ChunkedBitsForwardIterator { internal typealias _BitPosition = _UnsafeBitSet.Index diff --git a/Sources/BitCollections/BitArray/BitArray+Copy.swift b/Sources/BitCollections/BitArray/BitArray+Copy.swift index 1f339c33..50858e3e 100644 --- a/Sources/BitCollections/BitArray/BitArray+Copy.swift +++ b/Sources/BitCollections/BitArray/BitArray+Copy.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitArray { internal mutating func _copy( diff --git a/Sources/BitCollections/BitArray/BitArray+Invariants.swift b/Sources/BitCollections/BitArray/BitArray+Invariants.swift index d194ea0b..00de5625 100644 --- a/Sources/BitCollections/BitArray/BitArray+Invariants.swift +++ b/Sources/BitCollections/BitArray/BitArray+Invariants.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitArray { /// True if consistency checking is enabled in the implementation of this diff --git a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift index ba69f1e7..9b716b55 100644 --- a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift +++ b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitArray { /// An unsafe-unowned bitarray view over `UInt` storage, providing bit array diff --git a/Sources/BitCollections/BitArray/BitArray.swift b/Sources/BitCollections/BitArray/BitArray.swift index e40cc0e2..6b15f924 100644 --- a/Sources/BitCollections/BitArray/BitArray.swift +++ b/Sources/BitCollections/BitArray/BitArray.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif /// An ordered, random-access collection of `Bool` values, implemented as an /// uncompressed bitmap of as many bits as the count of the array. diff --git a/Sources/BitCollections/BitSet/BitSet+Extras.swift b/Sources/BitCollections/BitSet/BitSet+Extras.swift index 5a6ba9d7..67503b40 100644 --- a/Sources/BitCollections/BitSet/BitSet+Extras.swift +++ b/Sources/BitCollections/BitSet/BitSet+Extras.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitSet: _UniqueCollection {} diff --git a/Sources/BitCollections/BitSet/BitSet+Initializers.swift b/Sources/BitCollections/BitSet/BitSet+Initializers.swift index 4508d40f..cf8b9987 100644 --- a/Sources/BitCollections/BitSet/BitSet+Initializers.swift +++ b/Sources/BitCollections/BitSet/BitSet+Initializers.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitSet { /// Initializes a new, empty bit set. diff --git a/Sources/BitCollections/BitSet/BitSet+Invariants.swift b/Sources/BitCollections/BitSet/BitSet+Invariants.swift index c11ecf2b..1d9811c6 100644 --- a/Sources/BitCollections/BitSet/BitSet+Invariants.swift +++ b/Sources/BitCollections/BitSet/BitSet+Invariants.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitSet { /// True if consistency checking is enabled in the implementation of this diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift index 3c85b2c2..e0f4e2bc 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // FIXME: These are non-standard extensions generalizing ==. extension BitSet { diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift index 4fb251a9..fdfa7db9 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitSet { /// Returns a Boolean value that indicates whether this bit set is a strict diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift index 936dc8d9..c84f8f18 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitSet { /// Returns a Boolean value that indicates whether this set is a strict diff --git a/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift b/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift index 191afcf7..4b3720fd 100644 --- a/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift +++ b/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitSet: _SortedCollection { /// Returns the current set (already sorted). diff --git a/Sources/BitCollections/BitSet/BitSet.Counted.swift b/Sources/BitCollections/BitSet/BitSet.Counted.swift index 061e0e95..9acfc731 100644 --- a/Sources/BitCollections/BitSet/BitSet.Counted.swift +++ b/Sources/BitCollections/BitSet/BitSet.Counted.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitSet { public struct Counted { diff --git a/Sources/BitCollections/BitSet/BitSet.Index.swift b/Sources/BitCollections/BitSet/BitSet.Index.swift index 5c06411c..a0518d30 100644 --- a/Sources/BitCollections/BitSet/BitSet.Index.swift +++ b/Sources/BitCollections/BitSet/BitSet.Index.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitSet { /// An opaque type that represents a position in a bit set. diff --git a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift index 545c8fe8..06d48e0e 100644 --- a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift +++ b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension BitSet { @usableFromInline diff --git a/Sources/BitCollections/BitSet/BitSet.swift b/Sources/BitCollections/BitSet/BitSet.swift index 9c16064d..26cf01b0 100644 --- a/Sources/BitCollections/BitSet/BitSet.swift +++ b/Sources/BitCollections/BitSet/BitSet.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif /// A sorted collection of small nonnegative integers, implemented as an /// uncompressed bitmap of as many bits as the value of the largest member. diff --git a/Sources/BitCollections/Shared/UInt+Tricks.swift b/Sources/BitCollections/Shared/UInt+Tricks.swift index 5ef5fc72..09a46b98 100644 --- a/Sources/BitCollections/Shared/UInt+Tricks.swift +++ b/Sources/BitCollections/Shared/UInt+Tricks.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension UInt { /// Returns the position of the `n`th set bit in `self`. diff --git a/Sources/BitCollections/Shared/_Word.swift b/Sources/BitCollections/Shared/_Word.swift index 9b856c07..82d731ef 100644 --- a/Sources/BitCollections/Shared/_Word.swift +++ b/Sources/BitCollections/Shared/_Word.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif @usableFromInline internal typealias _Word = _UnsafeBitSet._Word diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index bb4c29f7..8212a293 100644 --- a/Sources/DequeModule/Deque+Collection.swift +++ b/Sources/DequeModule/Deque+Collection.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension Deque: Sequence { // Implementation note: we could also use the default `IndexingIterator` here. diff --git a/Sources/DequeModule/Deque+Descriptions.swift b/Sources/DequeModule/Deque+Descriptions.swift index 532d5912..9e27a2f6 100644 --- a/Sources/DequeModule/Deque+Descriptions.swift +++ b/Sources/DequeModule/Deque+Descriptions.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension Deque: CustomStringConvertible { /// A textual representation of this instance. diff --git a/Sources/DequeModule/Deque+Extras.swift b/Sources/DequeModule/Deque+Extras.swift index 93d64cc4..8467f8a3 100644 --- a/Sources/DequeModule/Deque+Extras.swift +++ b/Sources/DequeModule/Deque+Extras.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension Deque { /// Creates a deque with the specified capacity, then calls the given diff --git a/Sources/DequeModule/Deque+Testing.swift b/Sources/DequeModule/Deque+Testing.swift index bbc1fbf9..7575472c 100644 --- a/Sources/DequeModule/Deque+Testing.swift +++ b/Sources/DequeModule/Deque+Testing.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // This file contains exported but non-public entry points to support clear box // testing. diff --git a/Sources/DequeModule/_UnsafeWrappedBuffer.swift b/Sources/DequeModule/_UnsafeWrappedBuffer.swift index cf86b293..a798642b 100644 --- a/Sources/DequeModule/_UnsafeWrappedBuffer.swift +++ b/Sources/DequeModule/_UnsafeWrappedBuffer.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif @frozen @usableFromInline diff --git a/Sources/HashTreeCollections/HashNode/_Bitmap.swift b/Sources/HashTreeCollections/HashNode/_Bitmap.swift index 3f366e5c..9b789178 100644 --- a/Sources/HashTreeCollections/HashNode/_Bitmap.swift +++ b/Sources/HashTreeCollections/HashNode/_Bitmap.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif /// A set of `_Bucket` values, represented by a 32-bit wide bitset. @usableFromInline diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift index 75d7c1bf..3bbf6efc 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension _HashNode { @usableFromInline diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift index f01a3bd2..6dc9663e 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension _HashNode { @inlinable @inline(__always) diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift index 00299cd0..82d9646a 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif /// A base representation of a hash tree node, capturing functionality /// independent of the `Key` and `Value` types. diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift index d4a6b727..9c82114c 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension _HashNode { @inlinable diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift index a3457f19..915ed6d9 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension _HashNode { @inlinable diff --git a/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift b/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift index e007ad18..31d22346 100644 --- a/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift +++ b/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif /// An unsafe, unowned, type-erased reference to a hash tree node; essentially /// just a lightweight wrapper around `Unmanaged<_RawHashStorage>`. diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Debugging.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Debugging.swift index 51ec6531..eeb26b00 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Debugging.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Debugging.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeDictionary { /// True if consistency checking is enabled in the implementation of this diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Descriptions.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Descriptions.swift index e0c1eca6..d0e8f6aa 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Descriptions.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Descriptions.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeDictionary: CustomStringConvertible { // A textual representation of this instance. diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift index d714afaa..039e1947 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeDictionary { /// A view of a persistent dictionary’s keys, as a standalone collection. diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift index 67d80fb5..8d01aa49 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeDictionary { /// A view of a dictionary’s values. diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Debugging.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Debugging.swift index 27467db0..22567864 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Debugging.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Debugging.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeSet { /// True if consistency checking is enabled in the implementation of this diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Descriptions.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Descriptions.swift index f32127f1..13d7b419 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Descriptions.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Descriptions.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeSet: CustomStringConvertible { /// A textual representation of this instance. diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Equatable.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Equatable.swift index 9e238299..70130a20 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Equatable.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Equatable.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeSet: Equatable { /// Returns a Boolean value indicating whether two values are equal. diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift index 788187ef..70ac8c69 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeSet: _UniqueCollection {} diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift index da97d142..e6e58204 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeSet: SetAlgebra { /// Returns a Boolean value that indicates whether the given element exists diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift index 61066ac8..0cf2ba8c 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // FIXME: These are non-standard extensions generalizing ==. extension TreeSet { diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift index eddd4319..7badeb90 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeSet { /// Returns a Boolean value that indicates whether the set is a strict subset diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift index 551e2c44..97578bcd 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeSet { /// Returns a Boolean value that indicates whether the set is a strict diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift index 345a53e4..2314c355 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeSet { /// Returns a Boolean value that indicates whether this set is a subset of diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra symmetricDifference.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra symmetricDifference.swift index 9d68d781..e00bbe24 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra symmetricDifference.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra symmetricDifference.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension TreeSet { /// Returns a new set with the elements that are either in this set or in diff --git a/Sources/HeapModule/Heap+Invariants.swift b/Sources/HeapModule/Heap+Invariants.swift index a78b4dc9..50f01583 100644 --- a/Sources/HeapModule/Heap+Invariants.swift +++ b/Sources/HeapModule/Heap+Invariants.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension Heap { /// True if consistency checking is enabled in the implementation of this diff --git a/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift b/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift index 699a5ec8..205a2af5 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif @usableFromInline internal typealias _UnsafeHashTable = _HashTable.UnsafeHandle diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift index fede81ec..9188f615 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedDictionary: CustomStringConvertible { /// A textual representation of this instance. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift index 64313fea..5f3b7b71 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedDictionary.Elements { /// A collection that represents a contiguous slice of an ordered dictionary. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index 39c4fb1d..403d01b2 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedDictionary { /// A view of the contents of an ordered dictionary as a random-access diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift index 58964d22..ae383038 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedDictionary { /// True if consistency checking is enabled in the implementation of this diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift index 013badd9..1bafecee 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedDictionary { /// A view of an ordered dictionary's values as a standalone collection. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift index 3e405668..fa023ffc 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedSet: CustomStringConvertible { /// A textual representation of this instance. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift index ab24de09..12d6fc47 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedSet { /// Creates a set with the contents of the given sequence, which diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift index 53de455e..467a4377 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Invariants.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedSet { /// True if consistency checking is enabled in the implementation of this diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift index bbc139bb..b917e04c 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift @@ -11,7 +11,9 @@ // The parts of MutableCollection that OrderedSet is able to implement. +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedSet { /// Exchanges the values at the specified indices of the set. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift index 7535c14b..c71061a1 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // `OrderedSet` does not directly conform to `SetAlgebra` because its definition // of equality conflicts with `SetAlgebra` requirements. However, it still diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift index 8c2f1340..60ed2b96 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isDisjoint.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // `OrderedSet` does not directly conform to `SetAlgebra` because its definition // of equality conflicts with `SetAlgebra` requirements. However, it still diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqualSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqualSet.swift index bb77e59d..2f69d658 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqualSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqualSet.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedSet { /// Returns a Boolean value indicating whether two set values contain the diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift index 827b07f9..fcdbb951 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // `OrderedSet` does not directly conform to `SetAlgebra` because its definition // of equality conflicts with `SetAlgebra` requirements. However, it still diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift index 02fbb67d..61b70850 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // `OrderedSet` does not directly conform to `SetAlgebra` because its definition // of equality conflicts with `SetAlgebra` requirements. However, it still diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift index 9d35c0fc..0b1c64f8 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // `OrderedSet` does not directly conform to `SetAlgebra` because its definition // of equality conflicts with `SetAlgebra` requirements. However, it still diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift index ce4daf88..f5e54d52 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // `OrderedSet` does not directly conform to `SetAlgebra` because its definition // of equality conflicts with `SetAlgebra` requirements. However, it still diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift index d693c5a0..327d8096 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif // `OrderedSet` does not directly conform to `SetAlgebra` because its definition // of equality conflicts with `SetAlgebra` requirements. However, it still diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift index c8b5dc8b..d8d19444 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedSet: Sequence { /// The type that allows iteration over an ordered set's elements. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift index b21262d2..51079bfb 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedSet { /// A collection that represents a contiguous slice of an ordered set. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift index 84443339..96f81271 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedSet._UnstableInternals { @_spi(Testing) public var capacity: Int { base._capacity } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift index 0611718d..783840f3 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif extension OrderedSet { /// An unordered view into an ordered set, providing `SetAlgebra` diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index 761b7d11..0b733a27 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif /// An ordered collection of unique elements. /// diff --git a/Sources/OrderedCollections/Utilities/_UnsafeBitset.swift b/Sources/OrderedCollections/Utilities/_UnsafeBitset.swift index 5fe05fcd..10a8aee5 100644 --- a/Sources/OrderedCollections/Utilities/_UnsafeBitset.swift +++ b/Sources/OrderedCollections/Utilities/_UnsafeBitset.swift @@ -9,8 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities @usableFromInline internal typealias _UnsafeBitSet = _CollectionsUtilities._UnsafeBitSet - +#endif diff --git a/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift b/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift index 2e69c780..7149f66e 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift @@ -9,18 +9,9 @@ // //===----------------------------------------------------------------------===// -private func _addressString(for pointer: UnsafeRawPointer) -> String { - let address = UInt(bitPattern: pointer) - return "0x\(String(address, radix: 16))" -} - -private func _addressString(for object: AnyObject) -> String { - _addressString(for: Unmanaged.passUnretained(object).toOpaque()) -} - -private func _addressString(for object: Unmanaged) -> String { - _addressString(for: object.toOpaque()) -} +#if !COLLECTIONS_SINGLE_MODULE +import _CollectionsUtilities +#endif extension Rope._UnmanagedLeaf: CustomStringConvertible { var description: String { diff --git a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift index 3da01fab..c2748e25 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -#if swift(<5.8) +#if swift(<5.8) && !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities // for 5.8 polyfills #endif diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift index 6da6fead..447f686c 100644 --- a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -17,7 +17,6 @@ internal typealias _CharacterRecognizer = Unicode._CharacterRecognizer @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) extension _CharacterRecognizer { internal func _isKnownEqual(to other: Self) -> Bool { -#if SWIFT_PACKAGE // FIXME: Enable when Swift 5.9 ships. // #if swift(>=5.9) // if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { // SwiftStdlib 5.9 @@ -25,9 +24,6 @@ extension _CharacterRecognizer { // } // #endif return false -#else // !SWIFT_PACKAGE - return self == other -#endif } } diff --git a/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift b/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift index 97cd75a4..07c223a5 100644 --- a/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift +++ b/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsUtilities +#endif /// This protocol simply lists Collection/Sequence extensions that ought to be /// customized for sorted collections. diff --git a/Tests/BitCollectionsTests/BitArrayTests.swift b/Tests/BitCollectionsTests/BitArrayTests.swift index 303ec8b4..4fb29798 100644 --- a/Tests/BitCollectionsTests/BitArrayTests.swift +++ b/Tests/BitCollectionsTests/BitArrayTests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else import _CollectionsTestSupport @_spi(Testing) import BitCollections +#endif extension BitArray { static func _fromSequence( diff --git a/Tests/BitCollectionsTests/BitSet.Counted Tests.swift b/Tests/BitCollectionsTests/BitSet.Counted Tests.swift index bb7d86d7..f07d8000 100644 --- a/Tests/BitCollectionsTests/BitSet.Counted Tests.swift +++ b/Tests/BitCollectionsTests/BitSet.Counted Tests.swift @@ -10,9 +10,13 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import BitCollections import OrderedCollections +#endif extension BitSet.Counted: SetAPIExtras { public mutating func update(_ member: Int, at index: Index) -> Int { diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index 5a9becf2..0851a368 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -10,9 +10,13 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import BitCollections import OrderedCollections +#endif extension BitSet: SetAPIExtras { public mutating func update(_ member: Int, at index: Index) -> Int { diff --git a/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift b/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift index 3309fa0a..dca5da2b 100644 --- a/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift +++ b/Tests/CollectionsTestSupportTests/CombinatoricsChecks.swift @@ -10,7 +10,9 @@ //===----------------------------------------------------------------------===// import XCTest +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsTestSupport +#endif class CombinatoricsTests: CollectionTestCase { func testEverySubset_smoke() { diff --git a/Tests/CollectionsTestSupportTests/IndexRangeCollectionTests.swift b/Tests/CollectionsTestSupportTests/IndexRangeCollectionTests.swift index 339f6db8..f3bac6e0 100644 --- a/Tests/CollectionsTestSupportTests/IndexRangeCollectionTests.swift +++ b/Tests/CollectionsTestSupportTests/IndexRangeCollectionTests.swift @@ -10,7 +10,9 @@ //===----------------------------------------------------------------------===// import XCTest +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsTestSupport +#endif final class IndexRangeCollectionTests: CollectionTestCase { func testCollection() { diff --git a/Tests/CollectionsTestSupportTests/MinimalTypeConformances.swift b/Tests/CollectionsTestSupportTests/MinimalTypeConformances.swift index 394e3817..d74b1198 100644 --- a/Tests/CollectionsTestSupportTests/MinimalTypeConformances.swift +++ b/Tests/CollectionsTestSupportTests/MinimalTypeConformances.swift @@ -10,7 +10,9 @@ //===----------------------------------------------------------------------===// import XCTest +#if !COLLECTIONS_SINGLE_MODULE import _CollectionsTestSupport +#endif final class MinimalTypeTests: CollectionTestCase { func testMinimalSequence() { diff --git a/Tests/DequeTests/DequeInternals.swift b/Tests/DequeTests/DequeInternals.swift index 1f4e165e..cc533e0d 100644 --- a/Tests/DequeTests/DequeInternals.swift +++ b/Tests/DequeTests/DequeInternals.swift @@ -9,8 +9,12 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else import _CollectionsTestSupport @_spi(Testing) import DequeModule +#endif internal struct DequeLayout: CustomStringConvertible { let capacity: Int diff --git a/Tests/DequeTests/DequeTests.swift b/Tests/DequeTests/DequeTests.swift index 22227a6f..7c191e4d 100644 --- a/Tests/DequeTests/DequeTests.swift +++ b/Tests/DequeTests/DequeTests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else import _CollectionsTestSupport @_spi(Testing) import DequeModule +#endif final class DequeTests: CollectionTestCase { func test_testingSPIs() { diff --git a/Tests/DequeTests/MutableCollectionTests.swift b/Tests/DequeTests/MutableCollectionTests.swift index 1d5ea85d..330d7c2a 100644 --- a/Tests/DequeTests/MutableCollectionTests.swift +++ b/Tests/DequeTests/MutableCollectionTests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport @_spi(Testing) import DequeModule +#endif final class MutableCollectiontests: CollectionTestCase { // Note: Most of the test below are exhaustively testing the behavior diff --git a/Tests/DequeTests/RangeReplaceableCollectionTests.swift b/Tests/DequeTests/RangeReplaceableCollectionTests.swift index e6271019..6731d75e 100644 --- a/Tests/DequeTests/RangeReplaceableCollectionTests.swift +++ b/Tests/DequeTests/RangeReplaceableCollectionTests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else import _CollectionsTestSupport @_spi(Testing) import DequeModule +#endif /// Exhaustive tests for `Deque`'s implementations for `RangeReplaceableCollection` /// requirements. diff --git a/Tests/HashTreeCollectionsTests/TreeDictionary Smoke Tests.swift b/Tests/HashTreeCollectionsTests/TreeDictionary Smoke Tests.swift index ed6e32a4..f9981d81 100644 --- a/Tests/HashTreeCollectionsTests/TreeDictionary Smoke Tests.swift +++ b/Tests/HashTreeCollectionsTests/TreeDictionary Smoke Tests.swift @@ -9,8 +9,12 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import HashTreeCollections +#endif extension TreeDictionary { fileprivate func contains(_ key: Key) -> Bool { diff --git a/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift b/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift index 8674350f..aae5e315 100644 --- a/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift +++ b/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift @@ -9,8 +9,12 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import HashTreeCollections +#endif extension TreeDictionary: DictionaryAPIExtras {} diff --git a/Tests/HashTreeCollectionsTests/TreeDictionary.Keys Tests.swift b/Tests/HashTreeCollectionsTests/TreeDictionary.Keys Tests.swift index c714b187..9dc06a27 100644 --- a/Tests/HashTreeCollectionsTests/TreeDictionary.Keys Tests.swift +++ b/Tests/HashTreeCollectionsTests/TreeDictionary.Keys Tests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import HashTreeCollections +#endif class TreeDictionaryKeysTests: CollectionTestCase { func test_BidirectionalCollection_fixtures() { diff --git a/Tests/HashTreeCollectionsTests/TreeDictionary.Values Tests.swift b/Tests/HashTreeCollectionsTests/TreeDictionary.Values Tests.swift index b64f8ef4..8547ccaa 100644 --- a/Tests/HashTreeCollectionsTests/TreeDictionary.Values Tests.swift +++ b/Tests/HashTreeCollectionsTests/TreeDictionary.Values Tests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import HashTreeCollections +#endif class TreeDictionaryValuesTests: CollectionTestCase { func test_BidirectionalCollection_fixtures() { diff --git a/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift b/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift index 5b792306..58333c84 100644 --- a/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift +++ b/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift @@ -9,8 +9,12 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import HashTreeCollections +#endif /// A set of items whose subsets will produce a bunch of interesting test /// cases. diff --git a/Tests/HashTreeCollectionsTests/TreeSet Tests.swift b/Tests/HashTreeCollectionsTests/TreeSet Tests.swift index 9ea87177..5ce7cc88 100644 --- a/Tests/HashTreeCollectionsTests/TreeSet Tests.swift +++ b/Tests/HashTreeCollectionsTests/TreeSet Tests.swift @@ -9,8 +9,12 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import HashTreeCollections +#endif extension TreeSet: SetAPIExtras {} diff --git a/Tests/HashTreeCollectionsTests/Utilities.swift b/Tests/HashTreeCollectionsTests/Utilities.swift index bb13dcc7..216b4fcd 100644 --- a/Tests/HashTreeCollectionsTests/Utilities.swift +++ b/Tests/HashTreeCollectionsTests/Utilities.swift @@ -9,8 +9,12 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import HashTreeCollections +#endif extension LifetimeTracker { func shareableDictionary( diff --git a/Tests/HeapTests/HeapTests.swift b/Tests/HeapTests/HeapTests.swift index 85d1f762..af580364 100644 --- a/Tests/HeapTests/HeapTests.swift +++ b/Tests/HeapTests/HeapTests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import HeapModule +#endif extension Heap { func itemsInAscendingOrder() -> [Element] { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index d4d34293..57c7516e 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -10,9 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else @_spi(Testing) import OrderedCollections - import _CollectionsTestSupport +#endif extension OrderedDictionary: DictionaryAPIExtras {} diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift index a79c993b..5e1ae1a8 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift @@ -9,8 +9,12 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import OrderedCollections +#endif extension LifetimeTracker { func orderedDictionary( diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift index 8ac1c4b1..0ea74f77 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -10,9 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else @_spi(Testing) import OrderedCollections - import _CollectionsTestSupport +#endif class OrderedDictionaryElementsTests: CollectionTestCase { func test_elements_getter() { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift index d45e8059..ea2a739f 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift @@ -10,9 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else @_spi(Testing) import OrderedCollections - import _CollectionsTestSupport +#endif class OrderedDictionaryValueTests: CollectionTestCase { func test_values_getter() { diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift index 1f06a148..9d79968f 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import OrderedCollections import _CollectionsTestSupport +#endif class MeasuringHashable: Hashable { static var equalityChecks = 0 diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift index 4d166253..bf8aa88f 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet.UnorderedView Tests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else @_spi(Testing) import OrderedCollections import _CollectionsTestSupport +#endif // Note: This cannot really work unless `UnorderedView` becomes a Collection. // extension OrderedSet.UnorderedView: SetAPIChecker {} diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetInternals.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetInternals.swift index 397db56d..b0279c40 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetInternals.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetInternals.swift @@ -9,8 +9,12 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else import _CollectionsTestSupport @_spi(Testing) import OrderedCollections +#endif struct OrderedSetLayout: Hashable, CustomStringConvertible { let scale: Int diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index 361078c1..c745ea79 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -10,8 +10,12 @@ //===----------------------------------------------------------------------===// import XCTest +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else @_spi(Testing) import OrderedCollections import _CollectionsTestSupport +#endif extension OrderedSet: SetAPIExtras {} diff --git a/Tests/RopeModuleTests/SampleStrings.swift b/Tests/RopeModuleTests/SampleStrings.swift index 92965b03..1f93619d 100644 --- a/Tests/RopeModuleTests/SampleStrings.swift +++ b/Tests/RopeModuleTests/SampleStrings.swift @@ -9,6 +9,24 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import _CollectionsTestSupport +#endif + +func randomStride( + from start: Int, + to end: Int, + by maxStep: Int, + seed: Int +) -> UnfoldSequence { + var rng = RepeatableRandomNumberGenerator(seed: seed) + return sequence(state: start, next: { + $0 += Int.random(in: 1 ... maxStep, using: &rng) + guard $0 < end else { return nil } + return $0 + }) +} + let sampleString = #""" The powerful programming language that is also easy to learn. Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, \# @@ -57,21 +75,6 @@ let shortSample = #""" Swift 👨‍👨‍👧‍👧 简洁 c̴̭̈͘ǫ̷̯͋̊d̸͖̩̈̈́ḛ̴́ 🇺🇸🇨🇦🇺🇸 코드 """# -func randomStride( - from start: Int, - to end: Int, - by maxStep: Int, - seed: Int -) -> UnfoldSequence { - var rng = RepeatableRandomNumberGenerator(seed: seed) - return sequence(state: start, next: { - $0 += Int.random(in: 1 ... maxStep, using: &rng) - guard $0 < end else { return nil } - return $0 - }) -} - - let sampleString2 = #""" The powerful programming language that is also easy to learn. diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index c7bc5b94..1b10622b 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -10,9 +10,13 @@ //===----------------------------------------------------------------------===// #if swift(>=5.8) +import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsTestSupport import _RopeModule -import XCTest +#endif @available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) class TestBigString: CollectionTestCase { diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index 0c3f40e3..d0b429b9 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -9,8 +9,13 @@ // //===----------------------------------------------------------------------===// -import _RopeModule import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import _RopeModule +import _CollectionsTestSupport +#endif struct Chunk: RopeElement, Equatable, CustomStringConvertible { var length: Int From ea60d293b4635e2a9d560251752ebb950959b113 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 18:43:46 -0700 Subject: [PATCH 083/113] Fix test issues with single-module variant --- .../AssertionContexts/Assertions.swift | 2 +- .../RepeatableRandomNumberGenerator.swift | 28 ++++++------- .../SeedableRandomNumberGenerator.swift | 40 ------------------- .../HashTreeCollectionsTests/Utilities.swift | 16 -------- .../{NodeTests.swift => HeapNodeTests.swift} | 8 +++- ...ft => RandomAccessCollection+Extras.swift} | 19 ++------- Tests/RopeModuleTests/TestBigString.swift | 2 +- Tests/RopeModuleTests/TestRope.swift | 2 +- 8 files changed, 27 insertions(+), 90 deletions(-) rename Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift => Sources/_CollectionsTestSupport/Utilities/RepeatableRandomNumberGenerator.swift (88%) delete mode 100644 Sources/_CollectionsTestSupport/Utilities/SeedableRandomNumberGenerator.swift rename Tests/HeapTests/{NodeTests.swift => HeapNodeTests.swift} (86%) rename Tests/OrderedCollectionsTests/OrderedSet/{RandomAccessCollection+Offsets.swift => RandomAccessCollection+Extras.swift} (81%) diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift b/Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift index 76db2377..a1ccca5c 100644 --- a/Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift +++ b/Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift @@ -27,7 +27,7 @@ public func expectFailure( } } -internal func _expectFailure( +public func _expectFailure( _ diagnostic: String, _ message: () -> String, trapping: Bool, diff --git a/Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift b/Sources/_CollectionsTestSupport/Utilities/RepeatableRandomNumberGenerator.swift similarity index 88% rename from Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift rename to Sources/_CollectionsTestSupport/Utilities/RepeatableRandomNumberGenerator.swift index 4d415f4e..3e285d0d 100644 --- a/Tests/RopeModuleTests/SeedableRandomNumberGenerator.swift +++ b/Sources/_CollectionsTestSupport/Utilities/RepeatableRandomNumberGenerator.swift @@ -9,40 +9,40 @@ // //===----------------------------------------------------------------------===// -var globalSeed: Int { - #if COLLECTIONS_RANDOMIZED_TESTING - 42.hashValue - #else - 0 - #endif -} - public struct RepeatableRandomNumberGenerator: RandomNumberGenerator { + public static var globalSeed: Int { +#if COLLECTIONS_RANDOMIZED_TESTING + 42.hashValue +#else + 0 +#endif + } + // This uses the same linear congruential generator as rand48. // FIXME: Replace with something better. internal static let _m: UInt64 = 1 << 48 internal static let _a: UInt64 = 25214903917 internal static let _c: UInt64 = 11 - + internal var _state: UInt64 - + public init(seed: Int) { self.init(seed: UInt64(truncatingIfNeeded: seed)) } - + public init(seed: UInt64) { // Perturb the seed a little so that the sequence doesn't start with a // zero value in the common case of seed == 0. (Using a zero seed is a // rather silly thing to do, but it's the easy thing.) - let global = UInt64(truncatingIfNeeded: globalSeed) + let global = UInt64(truncatingIfNeeded: Self.globalSeed) _state = seed ^ global ^ 0x536f52616e646f6d // "SoRandom" } - + private mutating func _next() -> UInt64 { _state = (Self._a &* _state &+ Self._c) & (Self._m - 1) return _state &>> 16 } - + public mutating func next() -> UInt64 { return (_next() &<< 32) | _next() } diff --git a/Sources/_CollectionsTestSupport/Utilities/SeedableRandomNumberGenerator.swift b/Sources/_CollectionsTestSupport/Utilities/SeedableRandomNumberGenerator.swift deleted file mode 100644 index f09b89eb..00000000 --- a/Sources/_CollectionsTestSupport/Utilities/SeedableRandomNumberGenerator.swift +++ /dev/null @@ -1,40 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 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 -// -//===----------------------------------------------------------------------===// - -public struct RepeatableRandomNumberGenerator: RandomNumberGenerator { - // This uses the same linear congruential generator as rand48. - // FIXME: Replace with something better. - internal static let _m: UInt64 = 1 << 48 - internal static let _a: UInt64 = 25214903917 - internal static let _c: UInt64 = 11 - - internal var _state: UInt64 - - public init(seed: Int) { - self.init(seed: UInt64(truncatingIfNeeded: seed)) - } - - public init(seed: UInt64) { - // Perturb the seed a little so that the sequence doesn't start with a - // zero value in the common case of seed == 0. (Using a zero seed is a - // rather silly thing to do, but it's the easy thing.) - _state = seed ^ 0x536f52616e646f6d // "SoRandom" - } - - private mutating func _next() -> UInt64 { - _state = (Self._a &* _state &+ Self._c) & (Self._m - 1) - return _state &>> 16 - } - - public mutating func next() -> UInt64 { - return (_next() &<< 32) | _next() - } -} diff --git a/Tests/HashTreeCollectionsTests/Utilities.swift b/Tests/HashTreeCollectionsTests/Utilities.swift index 216b4fcd..9d0b8d71 100644 --- a/Tests/HashTreeCollectionsTests/Utilities.swift +++ b/Tests/HashTreeCollectionsTests/Utilities.swift @@ -118,22 +118,6 @@ extension LifetimeTracker { } } -func _expectFailure( - _ diagnostic: String, - _ message: () -> String, - trapping: Bool, - file: StaticString, - line: UInt -) { - expectFailure( - """ - \(diagnostic) - \(message()) - """, - trapping: trapping, - file: file, line: line) -} - func expectEqualSets( _ set: TreeSet, _ ref: [Element], diff --git a/Tests/HeapTests/NodeTests.swift b/Tests/HeapTests/HeapNodeTests.swift similarity index 86% rename from Tests/HeapTests/NodeTests.swift rename to Tests/HeapTests/HeapNodeTests.swift index 753e454e..9380ae38 100644 --- a/Tests/HeapTests/NodeTests.swift +++ b/Tests/HeapTests/HeapNodeTests.swift @@ -11,16 +11,20 @@ #if DEBUG // These unit tests need access to HeapModule internals import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else @testable import HeapModule +#endif -class NodeTests: XCTestCase { +class HeapNodeTests: XCTestCase { func test_levelCalculation() { // Check alternating min and max levels in the heap var isMin = true for exp in 0...12 { // Check [2^exp, 2^(exp + 1)) for offset in Int(pow(2, Double(exp)) - 1).. Index { - index(startIndex, offsetBy: offset) - } - - @inline(__always) - internal func _offset(of index: Index) -> Int { - distance(from: startIndex, to: index) - } - @inline(__always) internal func _indexRange(at offsets: Range) -> Range { _index(at: offsets.lowerBound) ..< _index(at: offsets.upperBound) @@ -42,11 +36,6 @@ extension RandomAccessCollection { return _offsetRange(of: range.relative(to: self)) } - @inline(__always) - internal subscript(_offset offset: Int) -> Element { - self[_index(at: offset)] - } - @inline(__always) internal subscript(_offsets range: Range) -> SubSequence { self[_indexRange(at: range)] diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index 1b10622b..fd0f6306 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -30,7 +30,7 @@ class TestBigString: CollectionTestCase { } override func setUp() { - print("Global seed: \(globalSeed)") + print("Global seed: \(RepeatableRandomNumberGenerator.globalSeed)") super.setUp() } diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index d0b429b9..471b2944 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -116,7 +116,7 @@ struct Chunk: RopeElement, Equatable, CustomStringConvertible { class TestRope: XCTestCase { override func setUp() { - print("Global seed: \(globalSeed)") + print("Global seed: \(RepeatableRandomNumberGenerator.globalSeed)") } func test_empty() { From e1ef053615ad20fb518fabb47c9c097d0eb82d83 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Mar 2023 18:46:10 -0700 Subject: [PATCH 084/113] =?UTF-8?q?Stop=20mentioning=20the=20enclosing=20m?= =?UTF-8?q?odule=E2=80=99s=20name?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TreeDictionary/TreeDictionary+Keys.swift | 2 +- .../TreeDictionary/TreeDictionary+Sequence.swift | 2 +- .../TreeDictionary/TreeDictionary+Values.swift | 4 ++-- .../TreeDictionary/TreeDictionary.swift | 10 +++++----- .../HashTreeCollections/TreeSet/TreeSet+Sequence.swift | 2 +- .../TreeSet/TreeSet+SetAlgebra intersection.swift | 6 ++---- .../TreeSet/TreeSet+SetAlgebra isEqualSet.swift | 2 +- .../TreeSet/TreeSet+SetAlgebra isStrictSubset.swift | 2 +- .../TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift | 2 +- .../TreeSet/TreeSet+SetAlgebra isSubset.swift | 2 +- .../TreeSet/TreeSet+SetAlgebra subtracting.swift | 2 +- Sources/HashTreeCollections/TreeSet/TreeSet.swift | 10 +++++----- 12 files changed, 22 insertions(+), 24 deletions(-) diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift index 039e1947..84fb7001 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift @@ -18,7 +18,7 @@ extension TreeDictionary { @frozen public struct Keys { @usableFromInline - internal typealias _HashNode = HashTreeCollections._HashNode + internal typealias _Node = _HashNode @usableFromInline internal var _base: TreeDictionary diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift index 8f41384d..f504404c 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift @@ -22,7 +22,7 @@ extension TreeDictionary: Sequence { // before any items within children. @usableFromInline - internal typealias _UnsafeHandle = _HashNode.UnsafeHandle + internal typealias _UnsafeHandle = _Node.UnsafeHandle @usableFromInline internal var _it: _HashTreeIterator diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift index 8d01aa49..7384ed79 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift @@ -18,10 +18,10 @@ extension TreeDictionary { @frozen public struct Values { @usableFromInline - internal typealias _HashNode = HashTreeCollections._HashNode + internal typealias _Node = TreeDictionary._Node @usableFromInline - internal typealias _UnsafeHandle = _HashNode.UnsafeHandle + internal typealias _UnsafeHandle = _Node.UnsafeHandle @usableFromInline internal var _base: TreeDictionary diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift index 99e287ad..75b16e03 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift @@ -65,13 +65,13 @@ @frozen // Not really -- this package is not at all ABI stable public struct TreeDictionary { @usableFromInline - internal typealias _HashNode = HashTreeCollections._HashNode + internal typealias _Node = _HashNode @usableFromInline - internal typealias _UnsafeHandle = _HashNode.UnsafeHandle + internal typealias _UnsafeHandle = _Node.UnsafeHandle @usableFromInline - var _root: _HashNode + var _root: _Node /// The version number of this instance, used for quick index validation. /// This is initialized to a (very weakly) random value and it gets @@ -80,13 +80,13 @@ public struct TreeDictionary { var _version: UInt @inlinable - internal init(_root: _HashNode, version: UInt) { + internal init(_root: _Node, version: UInt) { self._root = _root self._version = version } @inlinable - internal init(_new: _HashNode) { + internal init(_new: _Node) { self.init(_root: _new, version: _new.initialVersionNumber) } } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift index aff2c0ce..00e8fe66 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift @@ -14,7 +14,7 @@ extension TreeSet: Sequence { @frozen public struct Iterator: IteratorProtocol { @usableFromInline - internal typealias _UnsafeHandle = _HashNode.UnsafeHandle + internal typealias _UnsafeHandle = _Node.UnsafeHandle @usableFromInline internal var _it: _HashTreeIterator diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift index ab052d27..c76205aa 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift @@ -61,9 +61,7 @@ extension TreeSet { } @inlinable - internal func _intersection( - _ other: HashTreeCollections._HashNode - ) -> Self { + internal func _intersection(_ other: _HashNode) -> Self { guard let r = _root.intersection(.top, other) else { return self } return Self(_new: r) } @@ -97,7 +95,7 @@ extension TreeSet { return self.filter { other.contains($0) } } - var result: _HashNode = ._emptyNode() + var result: _Node = ._emptyNode() for item in other { let hash = _Hash(item) if let r = self._root.lookup(.top, item, hash) { diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift index 0cf2ba8c..ba1e906c 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift @@ -104,7 +104,7 @@ extension TreeSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _HashNode? = ._emptyNode() + var seen: _Node? = ._emptyNode() var it = other.makeIterator() while let item = it.next() { let hash = _Hash(item) diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift index 7badeb90..b75ea452 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift @@ -113,7 +113,7 @@ extension TreeSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _HashNode = ._emptyNode() + var seen: _Node = ._emptyNode() var doneCollecting = false var isStrict = false var it = other.makeIterator() diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift index 97578bcd..ba7eb0a0 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift @@ -110,7 +110,7 @@ extension TreeSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _HashNode = ._emptyNode() + var seen: _Node = ._emptyNode() for item in other { let hash = _Hash(item) guard self._root.containsKey(.top, item, hash) else { return false } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift index 2314c355..29bf895a 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift @@ -101,7 +101,7 @@ extension TreeSet { } // FIXME: Would making this a BitSet of seen positions be better? - var seen: _HashNode = ._emptyNode() + var seen: _Node = ._emptyNode() for item in other { let hash = _Hash(item) guard _root.containsKey(.top, item, hash) else { continue } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift index c9e39e43..3bcb7b7d 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift @@ -54,7 +54,7 @@ extension TreeSet { @inlinable internal __consuming func _subtracting( - _ other: HashTreeCollections._HashNode + _ other: _HashNode ) -> Self { guard let r = _root.subtracting(.top, other) else { return self } return Self(_new: r) diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet.swift b/Sources/HashTreeCollections/TreeSet/TreeSet.swift index 3c9d4c00..096a3846 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet.swift @@ -60,25 +60,25 @@ @frozen // Not really -- this package is not at all ABI stable public struct TreeSet { @usableFromInline - internal typealias _HashNode = HashTreeCollections._HashNode + internal typealias _Node = _HashNode @usableFromInline - internal typealias _UnsafeHandle = _HashNode.UnsafeHandle + internal typealias _UnsafeHandle = _Node.UnsafeHandle @usableFromInline - internal var _root: _HashNode + internal var _root: _Node @usableFromInline internal var _version: UInt @inlinable - internal init(_root: _HashNode, version: UInt) { + internal init(_root: _Node, version: UInt) { self._root = _root self._version = version } @inlinable - internal init(_new: _HashNode) { + internal init(_new: _Node) { self.init(_root: _new, version: _new.initialVersionNumber) } } From 688dbdf5c791689f7cb7056b61f7e40a8c670b1f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 22 Mar 2023 18:14:00 -0700 Subject: [PATCH 085/113] =?UTF-8?q?Add=20gyb=20=F0=9F=98=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + Utils/generate-sources.sh | 62 ++ Utils/gyb | 3 + Utils/gyb.py | 1247 +++++++++++++++++++++++++++++++++++++ Utils/gyb_utils.py | 34 + 5 files changed, 1347 insertions(+) create mode 100755 Utils/generate-sources.sh create mode 100755 Utils/gyb create mode 100755 Utils/gyb.py create mode 100644 Utils/gyb_utils.py diff --git a/.gitignore b/.gitignore index 397ae000..cb33e5fe 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ xcuserdata/ /Benchmarks/.swiftpm /Benchmarks/.build .docc-build +__pycache__ diff --git a/Utils/generate-sources.sh b/Utils/generate-sources.sh new file mode 100755 index 00000000..00d34fc2 --- /dev/null +++ b/Utils/generate-sources.sh @@ -0,0 +1,62 @@ +#!/bin/sh +#===----------------------------------------------------------------------===// +# +# This source file is part of the Swift.org open source project +# +# Copyright (c) 2020 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 +# +#===----------------------------------------------------------------------===// + +set -eu + +srcroot="$(dirname "$0")/.." +cd "$srcroot" + +gyb="./Utils/gyb" + +# Disable line directives in gyb output. We commit generated sources +# into the package repository, so we do not want absolute file names +# in them. +lineDirective='' + +# Uncomment the following line to enable #sourceLocation directives. +# This is useful for local development. +#lineDirective='#sourceLocation(file: "%(file)s", line: %(line)d)' + + +# Create a temporary directory; remove it on exit. +tmpdir="$(mktemp -d "${TMPDIR:-/tmp}/$(basename "$0").XXXXXXXX")" +trap "rm -rf \"$tmpdir\"" EXIT + +# Run gyb on each gyb file in the source tree and put results in +# subdirectories named 'autogenerated'. +find ./Sources ./Tests -name "*.gyb" | while read input; do + basename="$(basename "$input")" + targetdir="$(dirname "$input")/autogenerated" + output="$targetdir/"${basename%.gyb} + tmpfile="$tmpdir/${basename%.gyb}" + + # Make sure the output directory exists. + mkdir -p "$targetdir" + + # Run gyb, making sure to only update files when they change. + "$gyb" --line-directive "$lineDirective" -o "$tmpfile" "$input" + if [ -e "$output" ] && cmp -s "$tmpfile" "$output"; then + : Ignore unchanged file + else + echo "Updated $output" + cp "$tmpfile" "$output" + fi + echo "$output" >> "$tmpdir/generated-files.txt" +done + +# Remove autogenerated files without a corresponding gyb. +find . -path '*/autogenerated/*.swift' >> "$tmpdir/generated-files.txt" +sort "$tmpdir/generated-files.txt" | uniq -u | while read obsolete; do + echo "Removing $obsolete" + rm "$obsolete" +done diff --git a/Utils/gyb b/Utils/gyb new file mode 100755 index 00000000..8206bd8a --- /dev/null +++ b/Utils/gyb @@ -0,0 +1,3 @@ +#!/usr/bin/env python3 +import gyb +gyb.main() diff --git a/Utils/gyb.py b/Utils/gyb.py new file mode 100755 index 00000000..e3af0b7d --- /dev/null +++ b/Utils/gyb.py @@ -0,0 +1,1247 @@ +#!/usr/bin/env python +# GYB: Generate Your Boilerplate (improved names welcome; at least +# this one's short). See -h output for instructions + +import os +import re +import sys +import textwrap +import tokenize +from bisect import bisect +from io import StringIO + + +def get_line_starts(s): + """Return a list containing the start index of each line in s. + + The list also contains a sentinel index for the end of the string, + so there will be one more element in the list than there are lines + in the string + """ + starts = [0] + + for line in s.split('\n'): + starts.append(starts[-1] + len(line) + 1) + + starts[-1] -= 1 + return starts + + +def strip_trailing_nl(s): + """If s ends with a newline, drop it; else return s intact""" + return s[:-1] if s.endswith('\n') else s + + +def split_lines(s): + """Split s into a list of lines, each of which has a trailing newline + + If the lines are later concatenated, the result is s, possibly + with a single appended newline. + """ + return [l + '\n' for l in s.split('\n')] + + +# text on a line up to the first '$$', '${', or '%%' +literalText = r'(?: [^$\n%] | \$(?![${]) | %(?!%) )*' + +# The part of an '%end' line that follows the '%' sign +linesClose = r'[\ \t]* end [\ \t]* (?: \# .* )? $' + +# Note: Where "# Absorb" appears below, the regexp attempts to eat up +# through the end of ${...} and %{...}% constructs. In reality we +# handle this with the Python tokenizer, which avoids mis-detections +# due to nesting, comments and strings. This extra absorption in the +# regexp facilitates testing the regexp on its own, by preventing the +# interior of some of these constructs from being treated as literal +# text. +tokenize_re = re.compile( + r''' +# %-lines and %{...}-blocks + # \n? # absorb one preceding newline + ^ + (?: + (?P + (?P<_indent> [\ \t]* % (?! [{%] ) [\ \t]* ) (?! [\ \t] | ''' + + linesClose + r''' ) .* + ( \n (?P=_indent) (?! ''' + linesClose + r''' ) .* ) * + ) + | (?P [\ \t]* % [ \t]* ''' + linesClose + r''' ) + | [\ \t]* (?P %\{ ) + (?: [^}]| \} (?!%) )* \}% # Absorb + ) + \n? # absorb one trailing newline + +# Substitutions +| (?P \$\{ ) + [^}]* \} # Absorb + +# %% and $$ are literal % and $ respectively +| (?P[$%]) (?P=symbol) + +# Literal text +| (?P ''' + literalText + r''' + (?: + # newline that doesn't precede space+% + (?: \n (?! [\ \t]* %[^%] ) ) + ''' + literalText + r''' + )* + \n? + ) +''', re.VERBOSE | re.MULTILINE) + +gyb_block_close = re.compile(r'\}%[ \t]*\n?') + + +def token_pos_to_index(token_pos, start, line_starts): + """Translate a tokenize (line, column) pair into an absolute + position in source text given the position where we started + tokenizing and a list that maps lines onto their starting + character indexes. + """ + relative_token_line_plus1, token_col = token_pos + + # line number where we started tokenizing + start_line_num = bisect(line_starts, start) - 1 + + # line number of the token in the whole text + abs_token_line = relative_token_line_plus1 - 1 + start_line_num + + # if found in the first line, adjust the end column to account + # for the extra text + if relative_token_line_plus1 == 1: + token_col += start - line_starts[start_line_num] + + # Sometimes tokenizer errors report a line beyond the last one + if abs_token_line >= len(line_starts): + return line_starts[-1] + + return line_starts[abs_token_line] + token_col + + +def tokenize_python_to_unmatched_close_curly(source_text, start, line_starts): + """Apply Python's tokenize to source_text starting at index start + while matching open and close curly braces. When an unmatched + close curly brace is found, return its index. If not found, + return len(source_text). If there's a tokenization error, return + the position of the error. + """ + stream = StringIO(source_text) + stream.seek(start) + nesting = 0 + + try: + for kind, text, token_start, token_end, line_text \ + in tokenize.generate_tokens(stream.readline): + + if text == '{': + nesting += 1 + elif text == '}': + nesting -= 1 + if nesting < 0: + return token_pos_to_index(token_start, start, line_starts) + + except tokenize.TokenError as error: + (message, error_pos) = error.args + return token_pos_to_index(error_pos, start, line_starts) + + return len(source_text) + + +def tokenize_template(template_text): + r"""Given the text of a template, returns an iterator over + (tokenType, token, match) tuples. + + **Note**: this is template syntax tokenization, not Python + tokenization. + + When a non-literal token is matched, a client may call + iter.send(pos) on the iterator to reset the position in + template_text at which scanning will resume. + + This function provides a base level of tokenization which is + then refined by ParseContext.token_generator. + + >>> from pprint import * + >>> pprint(list((kind, text) for kind, text, _ in tokenize_template( + ... '%for x in range(10):\n% print x\n%end\njuicebox'))) + [('gybLines', '%for x in range(10):\n% print x'), + ('gybLinesClose', '%end'), + ('literal', 'juicebox')] + + >>> pprint(list((kind, text) for kind, text, _ in tokenize_template( + ... '''Nothing + ... % if x: + ... % for i in range(3): + ... ${i} + ... % end + ... % else: + ... THIS SHOULD NOT APPEAR IN THE OUTPUT + ... '''))) + [('literal', 'Nothing\n'), + ('gybLines', '% if x:\n% for i in range(3):'), + ('substitutionOpen', '${'), + ('literal', '\n'), + ('gybLinesClose', '% end'), + ('gybLines', '% else:'), + ('literal', 'THIS SHOULD NOT APPEAR IN THE OUTPUT\n')] + + >>> for kind, text, _ in tokenize_template(''' + ... This is $some$ literal stuff containing a ${substitution} + ... followed by a %{...} block: + ... %{ + ... # Python code + ... }% + ... and here $${are} some %-lines: + ... % x = 1 + ... % y = 2 + ... % if z == 3: + ... % print '${hello}' + ... % end + ... % for x in zz: + ... % print x + ... % # different indentation + ... % twice + ... and some lines that literally start with a %% token + ... %% first line + ... %% second line + ... '''): + ... print((kind, text.strip().split('\n',1)[0])) + ('literal', 'This is $some$ literal stuff containing a') + ('substitutionOpen', '${') + ('literal', 'followed by a %{...} block:') + ('gybBlockOpen', '%{') + ('literal', 'and here ${are} some %-lines:') + ('gybLines', '% x = 1') + ('gybLinesClose', '% end') + ('gybLines', '% for x in zz:') + ('gybLines', '% # different indentation') + ('gybLines', '% twice') + ('literal', 'and some lines that literally start with a % token') + """ + pos = 0 + end = len(template_text) + + saved_literal = [] + literal_first_match = None + + while pos < end: + m = tokenize_re.match(template_text, pos, end) + + # pull out the one matched key (ignoring internal patterns starting + # with _) + ((kind, text), ) = ( + (kind, text) for (kind, text) in list(m.groupdict().items()) + if text is not None and kind[0] != '_') + + if kind in ('literal', 'symbol'): + if len(saved_literal) == 0: + literal_first_match = m + # literals and symbols get batched together + saved_literal.append(text) + pos = None + else: + # found a non-literal. First yield any literal we've accumulated + if saved_literal != []: + yield 'literal', ''.join(saved_literal), literal_first_match + saved_literal = [] + + # Then yield the thing we found. If we get a reply, it's + # the place to resume tokenizing + pos = yield kind, text, m + + # If we were not sent a new position by our client, resume + # tokenizing at the end of this match. + if pos is None: + pos = m.end(0) + else: + # Client is not yet ready to process next token + yield + + if saved_literal != []: + yield 'literal', ''.join(saved_literal), literal_first_match + + +def split_gyb_lines(source_lines): + r"""Return a list of lines at which to split the incoming source + + These positions represent the beginnings of python line groups that + will require a matching %end construct if they are to be closed. + + >>> src = split_lines('''\ + ... if x: + ... print x + ... if y: # trailing comment + ... print z + ... if z: # another comment\ + ... ''') + >>> s = split_gyb_lines(src) + >>> len(s) + 2 + >>> src[s[0]] + ' print z\n' + >>> s[1] - len(src) + 0 + + >>> src = split_lines('''\ + ... if x: + ... if y: print 1 + ... if z: + ... print 2 + ... pass\ + ... ''') + >>> s = split_gyb_lines(src) + >>> len(s) + 1 + >>> src[s[0]] + ' if y: print 1\n' + + >>> src = split_lines('''\ + ... if x: + ... if y: + ... print 1 + ... print 2 + ... ''') + >>> s = split_gyb_lines(src) + >>> len(s) + 2 + >>> src[s[0]] + ' if y:\n' + >>> src[s[1]] + ' print 1\n' + """ + last_token_text, last_token_kind = None, None + unmatched_indents = [] + + dedents = 0 + try: + for token_kind, token_text, token_start, \ + (token_end_line, token_end_col), line_text \ + in tokenize.generate_tokens(lambda i=iter(source_lines): + next(i)): + + if token_kind in (tokenize.COMMENT, tokenize.ENDMARKER): + continue + + if token_text == '\n' and last_token_text == ':': + unmatched_indents.append(token_end_line) + + # The tokenizer appends dedents at EOF; don't consider + # those as matching indentations. Instead just save them + # up... + if last_token_kind == tokenize.DEDENT: + dedents += 1 + # And count them later, when we see something real. + if token_kind != tokenize.DEDENT and dedents > 0: + unmatched_indents = unmatched_indents[:-dedents] + dedents = 0 + + last_token_text, last_token_kind = token_text, token_kind + + except tokenize.TokenError: + # Let the later compile() call report the error + return [] + + if last_token_text == ':': + unmatched_indents.append(len(source_lines)) + + return unmatched_indents + + +def code_starts_with_dedent_keyword(source_lines): + r"""Return True iff the incoming Python source_lines begin with "else", + "elif", "except", or "finally". + + Initial comments and whitespace are ignored. + + >>> code_starts_with_dedent_keyword(split_lines('if x in y: pass')) + False + >>> code_starts_with_dedent_keyword(split_lines('except ifSomethingElse:')) + True + >>> code_starts_with_dedent_keyword( + ... split_lines('\n# comment\nelse: # yes')) + True + """ + token_text = None + for token_kind, token_text, _, _, _ \ + in tokenize.generate_tokens(lambda i=iter(source_lines): next(i)): + + if token_kind != tokenize.COMMENT and token_text.strip() != '': + break + + return token_text in ('else', 'elif', 'except', 'finally') + + +class ParseContext(object): + + """State carried through a parse of a template""" + + filename = '' + template = '' + line_starts = [] + code_start_line = -1 + code_text = None + tokens = None # The rest of the tokens + close_lines = False + + def __init__(self, filename, template=None): + self.filename = os.path.abspath(filename) + if sys.platform == 'win32': + self.filename = self.filename.replace('\\', '/') + if template is None: + with open(filename) as f: + self.template = f.read() + else: + self.template = template + self.line_starts = get_line_starts(self.template) + self.tokens = self.token_generator(tokenize_template(self.template)) + self.next_token() + + def pos_to_line(self, pos): + return bisect(self.line_starts, pos) - 1 + + def token_generator(self, base_tokens): + r"""Given an iterator over (kind, text, match) triples (see + tokenize_template above), return a refined iterator over + token_kinds. + + Among other adjustments to the elements found by base_tokens, + this refined iterator tokenizes python code embedded in + template text to help determine its true extent. The + expression "base_tokens.send(pos)" is used to reset the index at + which base_tokens resumes scanning the underlying text. + + >>> ctx = ParseContext('dummy', ''' + ... %for x in y: + ... % print x + ... % end + ... literally + ... ''') + >>> while ctx.token_kind: + ... print((ctx.token_kind, ctx.code_text or ctx.token_text)) + ... ignored = ctx.next_token() + ('literal', '\n') + ('gybLinesOpen', 'for x in y:\n') + ('gybLines', ' print x\n') + ('gybLinesClose', '% end') + ('literal', 'literally\n') + + >>> ctx = ParseContext('dummy', + ... '''Nothing + ... % if x: + ... % for i in range(3): + ... ${i} + ... % end + ... % else: + ... THIS SHOULD NOT APPEAR IN THE OUTPUT + ... ''') + >>> while ctx.token_kind: + ... print((ctx.token_kind, ctx.code_text or ctx.token_text)) + ... ignored = ctx.next_token() + ('literal', 'Nothing\n') + ('gybLinesOpen', 'if x:\n') + ('gybLinesOpen', ' for i in range(3):\n') + ('substitutionOpen', 'i') + ('literal', '\n') + ('gybLinesClose', '% end') + ('gybLinesOpen', 'else:\n') + ('literal', 'THIS SHOULD NOT APPEAR IN THE OUTPUT\n') + + >>> ctx = ParseContext('dummy', + ... '''% for x in [1, 2, 3]: + ... % if x == 1: + ... literal1 + ... % elif x > 1: # add output line here to fix bug + ... % if x == 2: + ... literal2 + ... % end + ... % end + ... % end + ... ''') + >>> while ctx.token_kind: + ... print((ctx.token_kind, ctx.code_text or ctx.token_text)) + ... ignored = ctx.next_token() + ('gybLinesOpen', 'for x in [1, 2, 3]:\n') + ('gybLinesOpen', ' if x == 1:\n') + ('literal', 'literal1\n') + ('gybLinesOpen', 'elif x > 1: # add output line here to fix bug\n') + ('gybLinesOpen', ' if x == 2:\n') + ('literal', 'literal2\n') + ('gybLinesClose', '% end') + ('gybLinesClose', '% end') + ('gybLinesClose', '% end') + """ + for self.token_kind, self.token_text, self.token_match in base_tokens: + kind = self.token_kind + self.code_text = None + + # Do we need to close the current lines? + self.close_lines = kind == 'gybLinesClose' + + # %{...}% and ${...} constructs + if kind.endswith('Open'): + + # Tokenize text that follows as Python up to an unmatched '}' + code_start = self.token_match.end(kind) + self.code_start_line = self.pos_to_line(code_start) + + close_pos = tokenize_python_to_unmatched_close_curly( + self.template, code_start, self.line_starts) + self.code_text = self.template[code_start:close_pos] + yield kind + + if (kind == 'gybBlockOpen'): + # Absorb any '}% \n' + m2 = gyb_block_close.match(self.template, close_pos) + if not m2: + raise ValueError("Invalid block closure") + next_pos = m2.end(0) + else: + assert kind == 'substitutionOpen' + # skip past the closing '}' + next_pos = close_pos + 1 + + # Resume tokenizing after the end of the code. + base_tokens.send(next_pos) + + elif kind == 'gybLines': + + self.code_start_line = self.pos_to_line( + self.token_match.start('gybLines')) + indentation = self.token_match.group('_indent') + + # Strip off the leading indentation and %-sign + source_lines = re.split( + '^' + re.escape(indentation), + self.token_match.group('gybLines') + '\n', + flags=re.MULTILINE)[1:] + + if code_starts_with_dedent_keyword(source_lines): + self.close_lines = True + + last_split = 0 + for line in split_gyb_lines(source_lines): + self.token_kind = 'gybLinesOpen' + self.code_text = ''.join(source_lines[last_split:line]) + yield self.token_kind + last_split = line + self.code_start_line += line - last_split + self.close_lines = False + + self.code_text = ''.join(source_lines[last_split:]) + if self.code_text: + self.token_kind = 'gybLines' + yield self.token_kind + else: + yield self.token_kind + + def next_token(self): + """Move to the next token""" + for kind in self.tokens: + return self.token_kind + + self.token_kind = None + + +_default_line_directive = \ + '// ###sourceLocation(file: "%(file)s", line: %(line)d)' + + +class ExecutionContext(object): + + """State we pass around during execution of a template""" + + def __init__(self, line_directive=_default_line_directive, + **local_bindings): + self.local_bindings = local_bindings + self.line_directive = line_directive + self.local_bindings['__context__'] = self + self.result_text = [] + self.last_file_line = None + + def append_text(self, text, file, line): + # see if we need to inject a line marker + if self.line_directive: + if (file, line) != self.last_file_line: + # We can only insert the line directive at a line break + if len(self.result_text) == 0 \ + or self.result_text[-1].endswith('\n'): + substitutions = {'file': file, 'line': line + 1} + format_str = self.line_directive + '\n' + self.result_text.append(format_str % substitutions) + # But if the new text contains any line breaks, we can create + # one + elif '\n' in text: + i = text.find('\n') + self.result_text.append(text[:i + 1]) + # and try again + self.append_text(text[i + 1:], file, line + 1) + return + + self.result_text.append(text) + self.last_file_line = (file, line + text.count('\n')) + + +class ASTNode(object): + + """Abstract base class for template AST nodes""" + + def __init__(self): + raise NotImplementedError("ASTNode.__init__ is not implemented.") + + def execute(self, context): + raise NotImplementedError("ASTNode.execute is not implemented.") + + def __str__(self, indent=''): + raise NotImplementedError("ASTNode.__str__ is not implemented.") + + def format_children(self, indent): + if not self.children: + return ' []' + + return '\n'.join( + ['', indent + '['] + + [x.__str__(indent + 4 * ' ') for x in self.children] + + [indent + ']']) + + +class Block(ASTNode): + + """A sequence of other AST nodes, to be executed in order""" + + children = [] + + def __init__(self, context): + self.children = [] + + while context.token_kind and not context.close_lines: + if context.token_kind == 'literal': + node = Literal + else: + node = Code + self.children.append(node(context)) + + def execute(self, context): + for x in self.children: + x.execute(context) + + def __str__(self, indent=''): + return indent + 'Block:' + self.format_children(indent) + + +class Literal(ASTNode): + + """An AST node that generates literal text""" + + def __init__(self, context): + self.text = context.token_text + start_position = context.token_match.start(context.token_kind) + self.start_line_number = context.pos_to_line(start_position) + self.filename = context.filename + context.next_token() + + def execute(self, context): + context.append_text(self.text, self.filename, self.start_line_number) + + def __str__(self, indent=''): + return '\n'.join( + [indent + x for x in ['Literal:'] + + strip_trailing_nl(self.text).split('\n')]) + + +class Code(ASTNode): + + """An AST node that is evaluated as Python""" + + code = None + children = () + kind = None + + def __init__(self, context): + + source = '' + source_line_count = 0 + + def accumulate_code(): + s = source + (context.code_start_line - source_line_count) * '\n' \ + + textwrap.dedent(context.code_text) + line_count = context.code_start_line + \ + context.code_text.count('\n') + context.next_token() + return s, line_count + + eval_exec = 'exec' + if context.token_kind.startswith('substitution'): + eval_exec = 'eval' + source, source_line_count = accumulate_code() + source = '(' + source.strip() + ')' + + else: + while context.token_kind == 'gybLinesOpen': + source, source_line_count = accumulate_code() + source += ' __children__[%d].execute(__context__)\n' % len( + self.children) + source_line_count += 1 + + self.children += (Block(context),) + + if context.token_kind == 'gybLinesClose': + context.next_token() + + if context.token_kind == 'gybLines': + source, source_line_count = accumulate_code() + + # Only handle a substitution as part of this code block if + # we don't already have some %-lines. + elif context.token_kind == 'gybBlockOpen': + + # Opening ${...} and %{...}% constructs + source, source_line_count = accumulate_code() + + self.filename = context.filename + self.start_line_number = context.code_start_line + self.code = compile(source, context.filename, eval_exec) + self.source = source + + def execute(self, context): + # Save __children__ from the local bindings + save_children = context.local_bindings.get('__children__') + # Execute the code with our __children__ in scope + context.local_bindings['__children__'] = self.children + context.local_bindings['__file__'] = self.filename + result = eval(self.code, context.local_bindings) + + if context.local_bindings['__children__'] is not self.children: + raise ValueError("The code is not allowed to mutate __children__") + # Restore the bindings + context.local_bindings['__children__'] = save_children + + # If we got a result, the code was an expression, so append + # its value + if result is not None \ + or (isinstance(result, str) and result != ''): + from numbers import Number, Integral + result_string = None + if isinstance(result, Number) and not isinstance(result, Integral): + result_string = repr(result) + else: + result_string = str(result) + context.append_text( + result_string, self.filename, self.start_line_number) + + def __str__(self, indent=''): + source_lines = re.sub(r'^\n', '', strip_trailing_nl( + self.source), flags=re.MULTILINE).split('\n') + if len(source_lines) == 1: + s = indent + 'Code: {' + source_lines[0] + '}' + else: + s = indent + 'Code:\n' + indent + '{\n' + '\n'.join( + indent + 4 * ' ' + l for l in source_lines + ) + '\n' + indent + '}' + return s + self.format_children(indent) + + +def expand(filename, line_directive=_default_line_directive, **local_bindings): + r"""Return the contents of the given template file, executed with the given + local bindings. + + >>> from tempfile import NamedTemporaryFile + >>> # On Windows, the name of a NamedTemporaryFile cannot be used to open + >>> # the file for a second time if delete=True. Therefore, we have to + >>> # manually handle closing and deleting this file to allow us to open + >>> # the file by its name across all platforms. + >>> f = NamedTemporaryFile(delete=False) + >>> f.write( + ... r'''--- + ... % for i in range(int(x)): + ... a pox on ${i} for epoxy + ... % end + ... ${120 + + ... + ... 3} + ... abc + ... ${"w\nx\nX\ny"} + ... z + ... ''') + >>> f.flush() + >>> result = expand( + ... f.name, + ... line_directive='//#sourceLocation(file: "%(file)s", ' + \ + ... 'line: %(line)d)', + ... x=2 + ... ).replace( + ... '"%s"' % f.name.replace('\\', '/'), '"dummy.file"') + >>> print(result, end='') + //#sourceLocation(file: "dummy.file", line: 1) + --- + //#sourceLocation(file: "dummy.file", line: 3) + a pox on 0 for epoxy + //#sourceLocation(file: "dummy.file", line: 3) + a pox on 1 for epoxy + //#sourceLocation(file: "dummy.file", line: 5) + 123 + //#sourceLocation(file: "dummy.file", line: 8) + abc + w + x + X + y + //#sourceLocation(file: "dummy.file", line: 10) + z + >>> f.close() + >>> os.remove(f.name) + """ + with open(filename) as f: + t = parse_template(filename, f.read()) + d = os.getcwd() + os.chdir(os.path.dirname(os.path.abspath(filename))) + try: + return execute_template( + t, line_directive=line_directive, **local_bindings) + finally: + os.chdir(d) + + +def parse_template(filename, text=None): + r"""Return an AST corresponding to the given template file. + + If text is supplied, it is assumed to be the contents of the file, + as a string. + + >>> print(parse_template('dummy.file', text= + ... '''% for x in [1, 2, 3]: + ... % if x == 1: + ... literal1 + ... % elif x > 1: # add output line after this line to fix bug + ... % if x == 2: + ... literal2 + ... % end + ... % end + ... % end + ... ''')) + Block: + [ + Code: + { + for x in [1, 2, 3]: + __children__[0].execute(__context__) + } + [ + Block: + [ + Code: + { + if x == 1: + __children__[0].execute(__context__) + elif x > 1: # add output line after this line to fix bug + __children__[1].execute(__context__) + } + [ + Block: + [ + Literal: + literal1 + ] + Block: + [ + Code: + { + if x == 2: + __children__[0].execute(__context__) + } + [ + Block: + [ + Literal: + literal2 + ] + ] + ] + ] + ] + ] + ] + + >>> print(parse_template( + ... 'dummy.file', + ... text='%for x in range(10):\n% print(x)\n%end\njuicebox')) + Block: + [ + Code: + { + for x in range(10): + __children__[0].execute(__context__) + } + [ + Block: + [ + Code: {print(x)} [] + ] + ] + Literal: + juicebox + ] + + >>> print(parse_template('/dummy.file', text= + ... '''Nothing + ... % if x: + ... % for i in range(3): + ... ${i} + ... % end + ... % else: + ... THIS SHOULD NOT APPEAR IN THE OUTPUT + ... ''')) + Block: + [ + Literal: + Nothing + Code: + { + if x: + __children__[0].execute(__context__) + else: + __children__[1].execute(__context__) + } + [ + Block: + [ + Code: + { + for i in range(3): + __children__[0].execute(__context__) + } + [ + Block: + [ + Code: {(i)} [] + Literal: + + ] + ] + ] + Block: + [ + Literal: + THIS SHOULD NOT APPEAR IN THE OUTPUT + ] + ] + ] + + >>> print(parse_template('dummy.file', text='''% + ... %for x in y: + ... % print(y) + ... ''')) + Block: + [ + Code: + { + for x in y: + __children__[0].execute(__context__) + } + [ + Block: + [ + Code: {print(y)} [] + ] + ] + ] + + >>> print(parse_template('dummy.file', text='''% + ... %if x: + ... % print(y) + ... AAAA + ... %else: + ... BBBB + ... ''')) + Block: + [ + Code: + { + if x: + __children__[0].execute(__context__) + else: + __children__[1].execute(__context__) + } + [ + Block: + [ + Code: {print(y)} [] + Literal: + AAAA + ] + Block: + [ + Literal: + BBBB + ] + ] + ] + + >>> print(parse_template('dummy.file', text='''% + ... %if x: + ... % print(y) + ... AAAA + ... %# This is a comment + ... %else: + ... BBBB + ... ''')) + Block: + [ + Code: + { + if x: + __children__[0].execute(__context__) + # This is a comment + else: + __children__[1].execute(__context__) + } + [ + Block: + [ + Code: {print(y)} [] + Literal: + AAAA + ] + Block: + [ + Literal: + BBBB + ] + ] + ] + + >>> print(parse_template('dummy.file', text='''\ + ... %for x in y: + ... AAAA + ... %if x: + ... BBBB + ... %end + ... CCCC + ... ''')) + Block: + [ + Code: + { + for x in y: + __children__[0].execute(__context__) + } + [ + Block: + [ + Literal: + AAAA + Code: + { + if x: + __children__[0].execute(__context__) + } + [ + Block: + [ + Literal: + BBBB + ] + ] + Literal: + CCCC + ] + ] + ] + """ + return Block(ParseContext(filename, text)) + + +def execute_template( + ast, line_directive=_default_line_directive, **local_bindings): + r"""Return the text generated by executing the given template AST. + + Keyword arguments become local variable bindings in the execution context + + >>> root_directory = os.path.abspath('/') + >>> file_name = (root_directory + 'dummy.file').replace('\\', '/') + >>> ast = parse_template(file_name, text= + ... '''Nothing + ... % if x: + ... % for i in range(3): + ... ${i} + ... % end + ... % else: + ... THIS SHOULD NOT APPEAR IN THE OUTPUT + ... ''') + >>> out = execute_template(ast, + ... line_directive='//#sourceLocation(file: "%(file)s", line: %(line)d)', + ... x=1) + >>> out = out.replace(file_name, "DUMMY-FILE") + >>> print(out, end="") + //#sourceLocation(file: "DUMMY-FILE", line: 1) + Nothing + //#sourceLocation(file: "DUMMY-FILE", line: 4) + 0 + //#sourceLocation(file: "DUMMY-FILE", line: 4) + 1 + //#sourceLocation(file: "DUMMY-FILE", line: 4) + 2 + + >>> ast = parse_template(file_name, text= + ... '''Nothing + ... % a = [] + ... % for x in range(3): + ... % a.append(x) + ... % end + ... ${a} + ... ''') + >>> out = execute_template(ast, + ... line_directive='//#sourceLocation(file: "%(file)s", line: %(line)d)', + ... x=1) + >>> out = out.replace(file_name, "DUMMY-FILE") + >>> print(out, end="") + //#sourceLocation(file: "DUMMY-FILE", line: 1) + Nothing + //#sourceLocation(file: "DUMMY-FILE", line: 6) + [0, 1, 2] + + >>> ast = parse_template(file_name, text= + ... '''Nothing + ... % a = [] + ... % for x in range(3): + ... % a.append(x) + ... % end + ... ${a} + ... ''') + >>> out = execute_template(ast, + ... line_directive='#line %(line)d "%(file)s"', x=1) + >>> out = out.replace(file_name, "DUMMY-FILE") + >>> print(out, end="") + #line 1 "DUMMY-FILE" + Nothing + #line 6 "DUMMY-FILE" + [0, 1, 2] + """ + execution_context = ExecutionContext( + line_directive=line_directive, **local_bindings) + ast.execute(execution_context) + return ''.join(execution_context.result_text) + + +def main(): + import argparse + import sys + + parser = argparse.ArgumentParser( + formatter_class=argparse.RawDescriptionHelpFormatter, + description='Generate Your Boilerplate!', epilog=''' + A GYB template consists of the following elements: + + - Literal text which is inserted directly into the output + + - %% or $$ in literal text, which insert literal '%' and '$' + symbols respectively. + + - Substitutions of the form ${}. The Python + expression is converted to a string and the result is inserted + into the output. + + - Python code delimited by %{...}%. Typically used to inject + definitions (functions, classes, variable bindings) into the + evaluation context of the template. Common indentation is + stripped, so you can add as much indentation to the beginning + of this code as you like + + - Lines beginning with optional whitespace followed by a single + '%' and Python code. %-lines allow you to nest other + constructs inside them. To close a level of nesting, use the + "%end" construct. + + - Lines beginning with optional whitespace and followed by a + single '%' and the token "end", which close open constructs in + %-lines. + + Example template: + + - Hello - + %{ + x = 42 + def succ(a): + return a+1 + }% + + I can assure you that ${x} < ${succ(x)} + + % if int(y) > 7: + % for i in range(3): + y is greater than seven! + % end + % else: + y is less than or equal to seven + % end + + - The End. - + + When run with "gyb -Dy=9", the output is + + - Hello - + + I can assure you that 42 < 43 + + y is greater than seven! + y is greater than seven! + y is greater than seven! + + - The End. - +''' + ) + parser.add_argument( + '-D', action='append', dest='defines', metavar='NAME=VALUE', + default=[], + help='''Bindings to be set in the template's execution context''') + + parser.add_argument( + 'file', type=argparse.FileType(), + help='Path to GYB template file (defaults to stdin)', nargs='?', + default=sys.stdin) + parser.add_argument( + '-o', dest='target', type=argparse.FileType('w'), + help='Output file (defaults to stdout)', default=sys.stdout) + parser.add_argument( + '--test', action='store_true', + default=False, help='Run a self-test') + parser.add_argument( + '--verbose-test', action='store_true', + default=False, help='Run a verbose self-test') + parser.add_argument( + '--dump', action='store_true', + default=False, help='Dump the parsed template to stdout') + parser.add_argument( + '--line-directive', + default=_default_line_directive, + help=''' + Line directive format string, which will be + provided 2 substitutions, `%%(line)d` and `%%(file)s`. + + Example: `#sourceLocation(file: "%%(file)s", line: %%(line)d)` + + The default works automatically with the `line-directive` tool, + which see for more information. + ''') + + args = parser.parse_args(sys.argv[1:]) + + if args.test or args.verbose_test: + import doctest + selfmod = sys.modules[__name__] + if doctest.testmod(selfmod, verbose=args.verbose_test or None).failed: + sys.exit(1) + + bindings = dict(x.split('=', 1) for x in args.defines) + ast = parse_template(args.file.name, args.file.read()) + if args.dump: + print(ast) + # Allow the template to open files and import .py files relative to its own + # directory + os.chdir(os.path.dirname(os.path.abspath(args.file.name))) + sys.path = ['.'] + sys.path + + args.target.write(execute_template(ast, args.line_directive, **bindings)) + + +if __name__ == '__main__': + main() diff --git a/Utils/gyb_utils.py b/Utils/gyb_utils.py new file mode 100644 index 00000000..a7eff165 --- /dev/null +++ b/Utils/gyb_utils.py @@ -0,0 +1,34 @@ +#===-----------------------------------------------------------------------===// +# +# This source file is part of the Swift.org 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 +# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +# +#===-----------------------------------------------------------------------===// + +def autogenerated_warning(): + return """ +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# +""" + +visibility_levels = ["internal", "public"] +def visibility_boilerplate(part): + if part == "internal": + return """ +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE""" + + if part == "public": + return "#else // !COLLECTIONS_SINGLE_MODULE" + if part == "end": + return "#endif // COLLECTIONS_SINGLE_MODULE" From c287334a9b77841eb17c7bc8ce6cc4297734c4b7 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 22 Mar 2023 18:56:05 -0700 Subject: [PATCH 086/113] _CollectionsUtilities: Use gyb to allow defining these helpers as internal or public depending on COLLECTIONS_SINGLE_MODULE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is a thoroughly disgusting solution, but needs must. 😞 Hopefully macros will let us eventually replace this mess. --- ...ContiguousStorage Compatibility.swift.gyb} | 13 +- ...afeMutableBufferPointer+SE-0370.swift.gyb} | 39 +- ...=> UnsafeMutablePointer+SE-0370.swift.gyb} | 13 +- ... => UnsafeRawPointer extensions.swift.gyb} | 19 +- ...+WithContiguousStorage Compatibility.swift | 98 ++ .../UnsafeMutableBufferPointer+SE-0370.swift | 832 ++++++++++++++++ .../UnsafeMutablePointer+SE-0370.swift | 72 ++ .../UnsafeRawPointer extensions.swift | 164 +++ .../{Debugging.swift => Debugging.swift.gyb} | 13 +- ...criptions.swift => Descriptions.swift.gyb} | 22 +- ...idthInteger+roundUpToPowerOfTwo.swift.gyb} | 13 +- ...eger rank.swift => Integer rank.swift.gyb} | 18 +- ... => UInt+first and last set bit.swift.gyb} | 15 +- ...reversed.swift => UInt+reversed.swift.gyb} | 13 +- ...ixedWidthInteger+roundUpToPowerOfTwo.swift | 46 + .../autogenerated/Integer rank.swift | 292 ++++++ .../UInt+first and last set bit.swift | 54 + .../autogenerated/UInt+reversed.swift | 58 ++ ... RandomAccessCollection+Offsets.swift.gyb} | 17 +- ...ex.swift => _UnsafeBitSet+Index.swift.gyb} | 35 +- ...rd.swift => _UnsafeBitSet+_Word.swift.gyb} | 82 +- ...feBitSet.swift => _UnsafeBitSet.swift.gyb} | 81 +- .../autogenerated/_UnsafeBitSet+Index.swift | 182 ++++ .../autogenerated/_UnsafeBitSet+_Word.swift | 639 ++++++++++++ .../autogenerated/_UnsafeBitSet.swift | 936 ++++++++++++++++++ ...t => UnsafeBufferPointer+Extras.swift.gyb} | 13 +- ...safeMutableBufferPointer+Extras.swift.gyb} | 11 +- .../autogenerated/Debugging.swift | 54 + .../autogenerated/Descriptions.swift | 190 ++++ .../RandomAccessCollection+Offsets.swift | 58 ++ .../UnsafeBufferPointer+Extras.swift | 42 + .../UnsafeMutableBufferPointer+Extras.swift | 278 ++++++ 32 files changed, 4276 insertions(+), 136 deletions(-) rename Sources/_CollectionsUtilities/Compatibility/{Array+WithContiguousStorage Compatibility.swift => Array+WithContiguousStorage Compatibility.swift.gyb} (88%) rename Sources/_CollectionsUtilities/Compatibility/{UnsafeMutableBufferPointer+SE-0370.swift => UnsafeMutableBufferPointer+SE-0370.swift.gyb} (93%) rename Sources/_CollectionsUtilities/Compatibility/{UnsafeMutablePointer+SE-0370.swift => UnsafeMutablePointer+SE-0370.swift.gyb} (79%) rename Sources/_CollectionsUtilities/Compatibility/{UnsafeRawPointer extensions.swift => UnsafeRawPointer extensions.swift.gyb} (84%) create mode 100644 Sources/_CollectionsUtilities/Compatibility/autogenerated/Array+WithContiguousStorage Compatibility.swift create mode 100644 Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeMutableBufferPointer+SE-0370.swift create mode 100644 Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeMutablePointer+SE-0370.swift create mode 100644 Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeRawPointer extensions.swift rename Sources/_CollectionsUtilities/{Debugging.swift => Debugging.swift.gyb} (72%) rename Sources/_CollectionsUtilities/{Descriptions.swift => Descriptions.swift.gyb} (75%) rename Sources/_CollectionsUtilities/IntegerTricks/{FixedWidthInteger+roundUpToPowerOfTwo.swift => FixedWidthInteger+roundUpToPowerOfTwo.swift.gyb} (69%) rename Sources/_CollectionsUtilities/IntegerTricks/{Integer rank.swift => Integer rank.swift.gyb} (88%) rename Sources/_CollectionsUtilities/IntegerTricks/{UInt+first and last set bit.swift => UInt+first and last set bit.swift.gyb} (68%) rename Sources/_CollectionsUtilities/IntegerTricks/{UInt+reversed.swift => UInt+reversed.swift.gyb} (73%) create mode 100644 Sources/_CollectionsUtilities/IntegerTricks/autogenerated/FixedWidthInteger+roundUpToPowerOfTwo.swift create mode 100644 Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift create mode 100644 Sources/_CollectionsUtilities/IntegerTricks/autogenerated/UInt+first and last set bit.swift create mode 100644 Sources/_CollectionsUtilities/IntegerTricks/autogenerated/UInt+reversed.swift rename Sources/_CollectionsUtilities/{RandomAccessCollection+Offsets.swift => RandomAccessCollection+Offsets.swift.gyb} (62%) rename Sources/_CollectionsUtilities/UnsafeBitSet/{_UnsafeBitSet+Index.swift => _UnsafeBitSet+Index.swift.gyb} (66%) rename Sources/_CollectionsUtilities/UnsafeBitSet/{_UnsafeBitSet+_Word.swift => _UnsafeBitSet+_Word.swift.gyb} (75%) rename Sources/_CollectionsUtilities/UnsafeBitSet/{_UnsafeBitSet.swift => _UnsafeBitSet.swift.gyb} (84%) create mode 100644 Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+Index.swift create mode 100644 Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+_Word.swift create mode 100644 Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet.swift rename Sources/_CollectionsUtilities/{UnsafeBufferPointer+Extras.swift => UnsafeBufferPointer+Extras.swift.gyb} (63%) rename Sources/_CollectionsUtilities/{UnsafeMutableBufferPointer+Extras.swift => UnsafeMutableBufferPointer+Extras.swift.gyb} (94%) create mode 100644 Sources/_CollectionsUtilities/autogenerated/Debugging.swift create mode 100644 Sources/_CollectionsUtilities/autogenerated/Descriptions.swift create mode 100644 Sources/_CollectionsUtilities/autogenerated/RandomAccessCollection+Offsets.swift create mode 100644 Sources/_CollectionsUtilities/autogenerated/UnsafeBufferPointer+Extras.swift create mode 100644 Sources/_CollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift diff --git a/Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift b/Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift.gyb similarity index 88% rename from Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift rename to Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift.gyb index c6d565ca..332305e1 100644 --- a/Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift +++ b/Sources/_CollectionsUtilities/Compatibility/Array+WithContiguousStorage Compatibility.swift.gyb @@ -2,13 +2,18 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + extension Array { /// Returns true if `Array.withContiguousStorageIfAvailable` is broken /// in the stdlib we're currently running on. @@ -53,11 +58,13 @@ extension Array { } } +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension Sequence { // An adjusted version of the standard `withContiguousStorageIfAvailable` // method that works around https://bugs.swift.org/browse/SR-14663. @inlinable @inline(__always) - public func _withContiguousStorageIfAvailable_SR14663( + ${modifier} func _withContiguousStorageIfAvailable_SR14663( _ body: (UnsafeBufferPointer) throws -> R ) rethrows -> R? { if Self.self == Array.self && Array._isWCSIABroken() { @@ -67,3 +74,5 @@ extension Sequence { return try self.withContiguousStorageIfAvailable(body) } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift b/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift.gyb similarity index 93% rename from Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift rename to Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift.gyb index 70766b4f..867f276e 100644 --- a/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift +++ b/Sources/_CollectionsUtilities/Compatibility/UnsafeMutableBufferPointer+SE-0370.swift.gyb @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022-2023 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 @@ -11,6 +11,13 @@ // Note: These are adapted from SE-0370 in the Swift 5.8 Standard Library. +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} #if swift(<5.8) extension UnsafeMutableBufferPointer { /// Deinitializes every instance in this buffer. @@ -25,7 +32,7 @@ extension UnsafeMutableBufferPointer { /// The range of memory is still bound to `Element`. @discardableResult @inlinable - public func deinitialize() -> UnsafeMutableRawBufferPointer { + ${modifier} func deinitialize() -> UnsafeMutableRawBufferPointer { guard let start = baseAddress else { return .init(start: nil, count: 0) } start.deinitialize(count: count) return .init(start: UnsafeMutableRawPointer(start), @@ -63,7 +70,7 @@ extension UnsafeMutableBufferPointer { /// - Returns: The index one past the last element of the buffer initialized /// by this function. @inlinable - public func initialize( + ${modifier} func initialize( fromContentsOf source: C ) -> Index where C.Element == Element { @@ -123,7 +130,7 @@ extension UnsafeMutableBufferPointer { /// by this function. @inlinable @_alwaysEmitIntoClient - public func moveInitialize(fromContentsOf source: Self) -> Index { + ${modifier} func moveInitialize(fromContentsOf source: Self) -> Index { guard let sourceAddress = source.baseAddress, !source.isEmpty else { return startIndex } @@ -165,7 +172,7 @@ extension UnsafeMutableBufferPointer { /// by this function. @inlinable @_alwaysEmitIntoClient - public func moveInitialize(fromContentsOf source: Slice) -> Index { + ${modifier} func moveInitialize(fromContentsOf source: Slice) -> Index { return moveInitialize(fromContentsOf: Self(rebasing: source)) } @@ -180,7 +187,7 @@ extension UnsafeMutableBufferPointer { /// - index: The index of the element to initialize @inlinable @_alwaysEmitIntoClient - public func initializeElement(at index: Index, to value: Element) { + ${modifier} func initializeElement(at index: Index, to value: Element) { assert(startIndex <= index && index < endIndex) let p = baseAddress.unsafelyUnwrapped.advanced(by: index) p.initialize(to: value) @@ -198,7 +205,7 @@ extension UnsafeMutableBufferPointer { /// - Returns: The instance referenced by this index in this buffer. @inlinable @_alwaysEmitIntoClient - public func moveElement(from index: Index) -> Element { + ${modifier} func moveElement(from index: Index) -> Element { assert(startIndex <= index && index < endIndex) return baseAddress.unsafelyUnwrapped.advanced(by: index).move() } @@ -213,7 +220,7 @@ extension UnsafeMutableBufferPointer { /// - index: The index of the buffer element to deinitialize. @inlinable @_alwaysEmitIntoClient - public func deinitializeElement(at index: Index) { + ${modifier} func deinitializeElement(at index: Index) { assert(startIndex <= index && index < endIndex) let p = baseAddress.unsafelyUnwrapped.advanced(by: index) p.deinitialize(count: 1) @@ -252,7 +259,7 @@ extension Slice { /// initialized by this function. @inlinable @_alwaysEmitIntoClient - public func initialize( + ${modifier} func initialize( fromContentsOf source: C ) -> Index where Base == UnsafeMutableBufferPointer { let buffer = Base(rebasing: self) @@ -291,7 +298,7 @@ extension Slice { /// initialized by this function. @inlinable @_alwaysEmitIntoClient - public func moveInitialize( + ${modifier} func moveInitialize( fromContentsOf source: UnsafeMutableBufferPointer ) -> Index where Base == UnsafeMutableBufferPointer { let buffer = Base(rebasing: self) @@ -330,7 +337,7 @@ extension Slice { /// initialized by this function. @inlinable @_alwaysEmitIntoClient - public func moveInitialize( + ${modifier} func moveInitialize( fromContentsOf source: Slice> ) -> Index where Base == UnsafeMutableBufferPointer { let buffer = Base(rebasing: self) @@ -352,7 +359,7 @@ extension Slice { @discardableResult @inlinable @_alwaysEmitIntoClient - public func deinitialize() -> UnsafeMutableRawBufferPointer + ${modifier} func deinitialize() -> UnsafeMutableRawBufferPointer where Base == UnsafeMutableBufferPointer { Base(rebasing: self).deinitialize() } @@ -368,7 +375,7 @@ extension Slice { /// - index: The index of the element to initialize @inlinable @_alwaysEmitIntoClient - public func initializeElement(at index: Int, to value: Element) + ${modifier} func initializeElement(at index: Int, to value: Element) where Base == UnsafeMutableBufferPointer { assert(startIndex <= index && index < endIndex) base.baseAddress.unsafelyUnwrapped.advanced(by: index).initialize(to: value) @@ -388,7 +395,7 @@ extension UnsafeMutableBufferPointer { /// - Parameters: /// - repeatedValue: The value used when updating this pointer's memory. @_alwaysEmitIntoClient - public func update(repeating repeatedValue: Element) { + ${modifier} func update(repeating repeatedValue: Element) { guard let dstBase = baseAddress else { return } dstBase.update(repeating: repeatedValue, count: count) } @@ -407,9 +414,11 @@ extension Slice { /// - Parameters: /// - repeatedValue: The value used when updating this pointer's memory. @_alwaysEmitIntoClient - public func update(repeating repeatedValue: Element) + ${modifier} func update(repeating repeatedValue: Element) where Base == UnsafeMutableBufferPointer { Base(rebasing: self).update(repeating: repeatedValue) } } #endif +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/Compatibility/UnsafeMutablePointer+SE-0370.swift b/Sources/_CollectionsUtilities/Compatibility/UnsafeMutablePointer+SE-0370.swift.gyb similarity index 79% rename from Sources/_CollectionsUtilities/Compatibility/UnsafeMutablePointer+SE-0370.swift rename to Sources/_CollectionsUtilities/Compatibility/UnsafeMutablePointer+SE-0370.swift.gyb index 6f32ffe7..0a90384a 100644 --- a/Sources/_CollectionsUtilities/Compatibility/UnsafeMutablePointer+SE-0370.swift +++ b/Sources/_CollectionsUtilities/Compatibility/UnsafeMutablePointer+SE-0370.swift.gyb @@ -2,13 +2,20 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} #if swift(<5.8) extension UnsafeMutablePointer { /// Update this pointer's initialized memory with the specified number of @@ -24,7 +31,7 @@ extension UnsafeMutablePointer { /// - count: The number of consecutive elements to update. /// `count` must not be negative. @_alwaysEmitIntoClient - public func update(repeating repeatedValue: Pointee, count: Int) { + ${modifier} func update(repeating repeatedValue: Pointee, count: Int) { assert(count >= 0, "UnsafeMutablePointer.update(repeating:count:) with negative count") for i in 0 ..< count { self[i] = repeatedValue @@ -32,3 +39,5 @@ extension UnsafeMutablePointer { } } #endif +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/Compatibility/UnsafeRawPointer extensions.swift b/Sources/_CollectionsUtilities/Compatibility/UnsafeRawPointer extensions.swift.gyb similarity index 84% rename from Sources/_CollectionsUtilities/Compatibility/UnsafeRawPointer extensions.swift rename to Sources/_CollectionsUtilities/Compatibility/UnsafeRawPointer extensions.swift.gyb index dfd4f455..7810e0e8 100644 --- a/Sources/_CollectionsUtilities/Compatibility/UnsafeRawPointer extensions.swift +++ b/Sources/_CollectionsUtilities/Compatibility/UnsafeRawPointer extensions.swift.gyb @@ -2,13 +2,20 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} #if compiler(<5.7) || (os(macOS) && compiler(<5.8)) // SE-0334 extension UnsafeRawPointer { /// Obtain the next pointer properly aligned to store a value of type `T`. @@ -21,7 +28,7 @@ extension UnsafeRawPointer { /// - Returns: a pointer properly aligned to store a value of type `T`. @inlinable @_alwaysEmitIntoClient - public func alignedUp(for type: T.Type) -> Self { + ${modifier} func alignedUp(for type: T.Type) -> Self { let mask = UInt(MemoryLayout.alignment) &- 1 let bits = (UInt(bitPattern: self) &+ mask) & ~mask return Self(bitPattern: bits)! @@ -37,7 +44,7 @@ extension UnsafeRawPointer { /// - Returns: a pointer properly aligned to store a value of type `T`. @inlinable @_alwaysEmitIntoClient - public func alignedDown(for type: T.Type) -> Self { + ${modifier} func alignedDown(for type: T.Type) -> Self { let mask = UInt(MemoryLayout.alignment) &- 1 let bits = UInt(bitPattern: self) & ~mask return Self(bitPattern: bits)! @@ -55,7 +62,7 @@ extension UnsafeMutableRawPointer { /// - Returns: a pointer properly aligned to store a value of type `T`. @inlinable @_alwaysEmitIntoClient - public func alignedUp(for type: T.Type) -> Self { + ${modifier} func alignedUp(for type: T.Type) -> Self { let mask = UInt(MemoryLayout.alignment) &- 1 let bits = (UInt(bitPattern: self) &+ mask) & ~mask return Self(bitPattern: bits)! @@ -71,10 +78,12 @@ extension UnsafeMutableRawPointer { /// - Returns: a pointer properly aligned to store a value of type `T`. @inlinable @_alwaysEmitIntoClient - public func alignedDown(for type: T.Type) -> Self { + ${modifier} func alignedDown(for type: T.Type) -> Self { let mask = UInt(MemoryLayout.alignment) &- 1 let bits = UInt(bitPattern: self) & ~mask return Self(bitPattern: bits)! } } #endif +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/Compatibility/autogenerated/Array+WithContiguousStorage Compatibility.swift b/Sources/_CollectionsUtilities/Compatibility/autogenerated/Array+WithContiguousStorage Compatibility.swift new file mode 100644 index 00000000..f91a9088 --- /dev/null +++ b/Sources/_CollectionsUtilities/Compatibility/autogenerated/Array+WithContiguousStorage Compatibility.swift @@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + +extension Array { + /// Returns true if `Array.withContiguousStorageIfAvailable` is broken + /// in the stdlib we're currently running on. + /// + /// See https://bugs.swift.org/browse/SR-14663. + @inlinable @inline(__always) + internal static func _isWCSIABroken() -> Bool { + #if _runtime(_ObjC) + guard _isBridgedVerbatimToObjectiveC(Element.self) else { + // SR-14663 only triggers on array values that are verbatim bridged + // from Objective-C, so it cannot ever trigger for element types + // that aren't verbatim bridged. + return false + } + + // SR-14663 was introduced in Swift 5.1, and it was resolved in Swift 5.5. + // Check if we have a broken stdlib. + + // The bug is caused by a bogus precondition inside a non-inlinable stdlib + // method, so to determine if we're affected, we need to check the currently + // running OS version. + #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) + if #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) { + // The OS is too new to be affected by this bug. (>= 5.5 stdlib) + return false + } +// guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13, *) else { +// // The OS is too old to be affected by this bug. (< 5.1 stdlib) +// return false +// } + return true + #else + // Assume that other platforms aren't affected. + return false + #endif + + #else + // Platforms that don't have an Objective-C runtime don't have verbatim + // bridged array values, so the bug doesn't apply to them. + return false + #endif + } +} + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension Sequence { + // An adjusted version of the standard `withContiguousStorageIfAvailable` + // method that works around https://bugs.swift.org/browse/SR-14663. + @inlinable @inline(__always) + internal func _withContiguousStorageIfAvailable_SR14663( + _ body: (UnsafeBufferPointer) throws -> R + ) rethrows -> R? { + if Self.self == Array.self && Array._isWCSIABroken() { + return nil + } + + return try self.withContiguousStorageIfAvailable(body) + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension Sequence { + // An adjusted version of the standard `withContiguousStorageIfAvailable` + // method that works around https://bugs.swift.org/browse/SR-14663. + @inlinable @inline(__always) + public func _withContiguousStorageIfAvailable_SR14663( + _ body: (UnsafeBufferPointer) throws -> R + ) rethrows -> R? { + if Self.self == Array.self && Array._isWCSIABroken() { + return nil + } + + return try self.withContiguousStorageIfAvailable(body) + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeMutableBufferPointer+SE-0370.swift b/Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeMutableBufferPointer+SE-0370.swift new file mode 100644 index 00000000..267c5608 --- /dev/null +++ b/Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeMutableBufferPointer+SE-0370.swift @@ -0,0 +1,832 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + +// Note: These are adapted from SE-0370 in the Swift 5.8 Standard Library. + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +#if swift(<5.8) +extension UnsafeMutableBufferPointer { + /// Deinitializes every instance in this buffer. + /// + /// The region of memory underlying this buffer must be fully initialized. + /// After calling `deinitialize(count:)`, the memory is uninitialized, + /// but still bound to the `Element` type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Returns: A raw buffer to the same range of memory as this buffer. + /// The range of memory is still bound to `Element`. + @discardableResult + @inlinable + internal func deinitialize() -> UnsafeMutableRawBufferPointer { + guard let start = baseAddress else { return .init(start: nil, count: 0) } + start.deinitialize(count: count) + return .init(start: UnsafeMutableRawPointer(start), + count: count * MemoryLayout.stride) + } +} +#endif + +// Note: this is left unconditionally enabled because we need the SR14663 workaround. :-( +extension UnsafeMutableBufferPointer { + /// Initializes the buffer's memory with + /// every element of the source. + /// + /// Prior to calling the `initialize(fromContentsOf:)` method on a buffer, + /// the memory referenced by the buffer must be uninitialized, + /// or the `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer up to, but not including, + /// the returned index is initialized. + /// The buffer must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// buffer's `startIndex`. If `source` contains as many elements as the buffer + /// can hold, the returned index is equal to the buffer's `endIndex`. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Note: The memory regions referenced by `source` and this buffer + /// must not overlap. + /// + /// - Parameter source: A collection of elements to be used to + /// initialize the buffer's storage. + /// - Returns: The index one past the last element of the buffer initialized + /// by this function. + @inlinable + internal func initialize( + fromContentsOf source: C + ) -> Index + where C.Element == Element { + let count: Int? = source._withContiguousStorageIfAvailable_SR14663 { + guard let sourceAddress = $0.baseAddress, !$0.isEmpty else { + return 0 + } + precondition( + $0.count <= self.count, + "buffer cannot contain every element from source." + ) + baseAddress?.initialize(from: sourceAddress, count: $0.count) + return $0.count + } + if let count = count { + return startIndex.advanced(by: count) + } + + var (iterator, copied) = source._copyContents(initializing: self) + precondition( + iterator.next() == nil, + "buffer cannot contain every element from source." + ) + return startIndex.advanced(by: copied) + } +} + +#if swift(<5.8) +extension UnsafeMutableBufferPointer { + /// Moves every element of an initialized source buffer into the + /// uninitialized memory referenced by this buffer, leaving the source memory + /// uninitialized and this buffer's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a buffer, + /// the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// buffer's `startIndex`. If `source` contains as many elements as the buffer + /// can hold, the returned index is equal to the buffer's `endIndex`. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Note: The memory regions referenced by `source` and this buffer + /// may overlap. + /// + /// - Parameter source: A buffer containing the values to copy. The memory + /// region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer initialized + /// by this function. + @inlinable + @_alwaysEmitIntoClient + internal func moveInitialize(fromContentsOf source: Self) -> Index { + guard let sourceAddress = source.baseAddress, !source.isEmpty else { + return startIndex + } + precondition( + source.count <= self.count, + "buffer cannot contain every element from source." + ) + baseAddress?.moveInitialize(from: sourceAddress, count: source.count) + return startIndex.advanced(by: source.count) + } + + /// Moves every element of an initialized source buffer into the + /// uninitialized memory referenced by this buffer, leaving the source memory + /// uninitialized and this buffer's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a buffer, + /// the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// buffer's `startIndex`. If `source` contains as many elements as the buffer + /// can hold, the returned index is equal to the buffer's `endIndex`. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Note: The memory regions referenced by `source` and this buffer + /// may overlap. + /// + /// - Parameter source: A buffer containing the values to copy. The memory + /// region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer initialized + /// by this function. + @inlinable + @_alwaysEmitIntoClient + internal func moveInitialize(fromContentsOf source: Slice) -> Index { + return moveInitialize(fromContentsOf: Self(rebasing: source)) + } + + /// Initializes the element at `index` to the given value. + /// + /// The memory underlying the destination element must be uninitialized, + /// or `Element` must be a trivial type. After a call to `initialize(to:)`, + /// the memory underlying this element of the buffer is initialized. + /// + /// - Parameters: + /// - value: The value used to initialize the buffer element's memory. + /// - index: The index of the element to initialize + @inlinable + @_alwaysEmitIntoClient + internal func initializeElement(at index: Index, to value: Element) { + assert(startIndex <= index && index < endIndex) + let p = baseAddress.unsafelyUnwrapped.advanced(by: index) + p.initialize(to: value) + } + + /// Retrieves and returns the element at `index`, + /// leaving that element's underlying memory uninitialized. + /// + /// The memory underlying the element at `index` must be initialized. + /// After calling `moveElement(from:)`, the memory underlying this element + /// of the buffer is uninitialized, and still bound to type `Element`. + /// + /// - Parameters: + /// - index: The index of the buffer element to retrieve and deinitialize. + /// - Returns: The instance referenced by this index in this buffer. + @inlinable + @_alwaysEmitIntoClient + internal func moveElement(from index: Index) -> Element { + assert(startIndex <= index && index < endIndex) + return baseAddress.unsafelyUnwrapped.advanced(by: index).move() + } + + /// Deinitializes the memory underlying the element at `index`. + /// + /// The memory underlying the element at `index` must be initialized. + /// After calling `deinitializeElement()`, the memory underlying this element + /// of the buffer is uninitialized, and still bound to type `Element`. + /// + /// - Parameters: + /// - index: The index of the buffer element to deinitialize. + @inlinable + @_alwaysEmitIntoClient + internal func deinitializeElement(at index: Index) { + assert(startIndex <= index && index < endIndex) + let p = baseAddress.unsafelyUnwrapped.advanced(by: index) + p.deinitialize(count: 1) + } +} +#endif + +#if swift(<5.8) +extension Slice { + /// Initializes the buffer slice's memory with with + /// every element of the source. + /// + /// Prior to calling the `initialize(fromContentsOf:)` method + /// on a buffer slice, the memory it references must be uninitialized, + /// or the `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer slice up to, but not including, + /// the returned index is initialized. + /// The buffer slice must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the index of the next uninitialized element + /// in the buffer slice, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to + /// the buffer slice's `startIndex`. If `source` contains as many elements + /// as the buffer slice can hold, the returned index is equal to + /// to the slice's `endIndex`. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Note: The memory regions referenced by `source` and this buffer slice + /// must not overlap. + /// + /// - Parameter source: A collection of elements to be used to + /// initialize the buffer slice's storage. + /// - Returns: The index one past the last element of the buffer slice + /// initialized by this function. + @inlinable + @_alwaysEmitIntoClient + internal func initialize( + fromContentsOf source: C + ) -> Index where Base == UnsafeMutableBufferPointer { + let buffer = Base(rebasing: self) + let index = buffer.initialize(fromContentsOf: source) + let distance = buffer.distance(from: buffer.startIndex, to: index) + return startIndex.advanced(by: distance) + } + + /// Moves every element of an initialized source buffer into the + /// uninitialized memory referenced by this buffer slice, leaving the + /// source memory uninitialized and this buffer slice's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a + /// buffer slice, the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer slice up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer slice must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer slice, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// slice's `startIndex`. If `source` contains as many elements as the slice + /// can hold, the returned index is equal to the slice's `endIndex`. + /// + /// - Note: The memory regions referenced by `source` and this buffer slice + /// may overlap. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Parameter source: A buffer containing the values to copy. + /// The memory region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer slice + /// initialized by this function. + @inlinable + @_alwaysEmitIntoClient + internal func moveInitialize( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Index where Base == UnsafeMutableBufferPointer { + let buffer = Base(rebasing: self) + let index = buffer.moveInitialize(fromContentsOf: source) + let distance = buffer.distance(from: buffer.startIndex, to: index) + return startIndex.advanced(by: distance) + } + + /// Moves every element of an initialized source buffer slice into the + /// uninitialized memory referenced by this buffer slice, leaving the + /// source memory uninitialized and this buffer slice's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a + /// buffer slice, the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer slice up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer slice must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer slice, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// slice's `startIndex`. If `source` contains as many elements as the slice + /// can hold, the returned index is equal to the slice's `endIndex`. + /// + /// - Note: The memory regions referenced by `source` and this buffer slice + /// may overlap. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Parameter source: A buffer slice containing the values to copy. + /// The memory region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer slice + /// initialized by this function. + @inlinable + @_alwaysEmitIntoClient + internal func moveInitialize( + fromContentsOf source: Slice> + ) -> Index where Base == UnsafeMutableBufferPointer { + let buffer = Base(rebasing: self) + let index = buffer.moveInitialize(fromContentsOf: source) + let distance = buffer.distance(from: buffer.startIndex, to: index) + return startIndex.advanced(by: distance) + } + + /// Deinitializes every instance in this buffer slice. + /// + /// The region of memory underlying this buffer slice must be fully + /// initialized. After calling `deinitialize(count:)`, the memory + /// is uninitialized, but still bound to the `Element` type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Returns: A raw buffer to the same range of memory as this buffer. + /// The range of memory is still bound to `Element`. + @discardableResult + @inlinable + @_alwaysEmitIntoClient + internal func deinitialize() -> UnsafeMutableRawBufferPointer + where Base == UnsafeMutableBufferPointer { + Base(rebasing: self).deinitialize() + } + + /// Initializes the element at `index` to the given value. + /// + /// The memory underlying the destination element must be uninitialized, + /// or `Element` must be a trivial type. After a call to `initialize(to:)`, + /// the memory underlying this element of the buffer slice is initialized. + /// + /// - Parameters: + /// - value: The value used to initialize the buffer element's memory. + /// - index: The index of the element to initialize + @inlinable + @_alwaysEmitIntoClient + internal func initializeElement(at index: Int, to value: Element) + where Base == UnsafeMutableBufferPointer { + assert(startIndex <= index && index < endIndex) + base.baseAddress.unsafelyUnwrapped.advanced(by: index).initialize(to: value) + } +} +#endif + +#if swift(<5.8) +extension UnsafeMutableBufferPointer { + /// Updates every element of this buffer's initialized memory. + /// + /// The buffer’s memory must be initialized or its `Element` type + /// must be a trivial type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Parameters: + /// - repeatedValue: The value used when updating this pointer's memory. + @_alwaysEmitIntoClient + internal func update(repeating repeatedValue: Element) { + guard let dstBase = baseAddress else { return } + dstBase.update(repeating: repeatedValue, count: count) + } +} +#endif + +#if swift(<5.8) +extension Slice { + /// Updates every element of this buffer slice's initialized memory. + /// + /// The buffer slice’s memory must be initialized or its `Element` + /// must be a trivial type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Parameters: + /// - repeatedValue: The value used when updating this pointer's memory. + @_alwaysEmitIntoClient + internal func update(repeating repeatedValue: Element) + where Base == UnsafeMutableBufferPointer { + Base(rebasing: self).update(repeating: repeatedValue) + } +} +#endif +#else // !COLLECTIONS_SINGLE_MODULE +#if swift(<5.8) +extension UnsafeMutableBufferPointer { + /// Deinitializes every instance in this buffer. + /// + /// The region of memory underlying this buffer must be fully initialized. + /// After calling `deinitialize(count:)`, the memory is uninitialized, + /// but still bound to the `Element` type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Returns: A raw buffer to the same range of memory as this buffer. + /// The range of memory is still bound to `Element`. + @discardableResult + @inlinable + public func deinitialize() -> UnsafeMutableRawBufferPointer { + guard let start = baseAddress else { return .init(start: nil, count: 0) } + start.deinitialize(count: count) + return .init(start: UnsafeMutableRawPointer(start), + count: count * MemoryLayout.stride) + } +} +#endif + +// Note: this is left unconditionally enabled because we need the SR14663 workaround. :-( +extension UnsafeMutableBufferPointer { + /// Initializes the buffer's memory with + /// every element of the source. + /// + /// Prior to calling the `initialize(fromContentsOf:)` method on a buffer, + /// the memory referenced by the buffer must be uninitialized, + /// or the `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer up to, but not including, + /// the returned index is initialized. + /// The buffer must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// buffer's `startIndex`. If `source` contains as many elements as the buffer + /// can hold, the returned index is equal to the buffer's `endIndex`. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Note: The memory regions referenced by `source` and this buffer + /// must not overlap. + /// + /// - Parameter source: A collection of elements to be used to + /// initialize the buffer's storage. + /// - Returns: The index one past the last element of the buffer initialized + /// by this function. + @inlinable + public func initialize( + fromContentsOf source: C + ) -> Index + where C.Element == Element { + let count: Int? = source._withContiguousStorageIfAvailable_SR14663 { + guard let sourceAddress = $0.baseAddress, !$0.isEmpty else { + return 0 + } + precondition( + $0.count <= self.count, + "buffer cannot contain every element from source." + ) + baseAddress?.initialize(from: sourceAddress, count: $0.count) + return $0.count + } + if let count = count { + return startIndex.advanced(by: count) + } + + var (iterator, copied) = source._copyContents(initializing: self) + precondition( + iterator.next() == nil, + "buffer cannot contain every element from source." + ) + return startIndex.advanced(by: copied) + } +} + +#if swift(<5.8) +extension UnsafeMutableBufferPointer { + /// Moves every element of an initialized source buffer into the + /// uninitialized memory referenced by this buffer, leaving the source memory + /// uninitialized and this buffer's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a buffer, + /// the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// buffer's `startIndex`. If `source` contains as many elements as the buffer + /// can hold, the returned index is equal to the buffer's `endIndex`. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Note: The memory regions referenced by `source` and this buffer + /// may overlap. + /// + /// - Parameter source: A buffer containing the values to copy. The memory + /// region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer initialized + /// by this function. + @inlinable + @_alwaysEmitIntoClient + public func moveInitialize(fromContentsOf source: Self) -> Index { + guard let sourceAddress = source.baseAddress, !source.isEmpty else { + return startIndex + } + precondition( + source.count <= self.count, + "buffer cannot contain every element from source." + ) + baseAddress?.moveInitialize(from: sourceAddress, count: source.count) + return startIndex.advanced(by: source.count) + } + + /// Moves every element of an initialized source buffer into the + /// uninitialized memory referenced by this buffer, leaving the source memory + /// uninitialized and this buffer's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a buffer, + /// the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// buffer's `startIndex`. If `source` contains as many elements as the buffer + /// can hold, the returned index is equal to the buffer's `endIndex`. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Note: The memory regions referenced by `source` and this buffer + /// may overlap. + /// + /// - Parameter source: A buffer containing the values to copy. The memory + /// region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer initialized + /// by this function. + @inlinable + @_alwaysEmitIntoClient + public func moveInitialize(fromContentsOf source: Slice) -> Index { + return moveInitialize(fromContentsOf: Self(rebasing: source)) + } + + /// Initializes the element at `index` to the given value. + /// + /// The memory underlying the destination element must be uninitialized, + /// or `Element` must be a trivial type. After a call to `initialize(to:)`, + /// the memory underlying this element of the buffer is initialized. + /// + /// - Parameters: + /// - value: The value used to initialize the buffer element's memory. + /// - index: The index of the element to initialize + @inlinable + @_alwaysEmitIntoClient + public func initializeElement(at index: Index, to value: Element) { + assert(startIndex <= index && index < endIndex) + let p = baseAddress.unsafelyUnwrapped.advanced(by: index) + p.initialize(to: value) + } + + /// Retrieves and returns the element at `index`, + /// leaving that element's underlying memory uninitialized. + /// + /// The memory underlying the element at `index` must be initialized. + /// After calling `moveElement(from:)`, the memory underlying this element + /// of the buffer is uninitialized, and still bound to type `Element`. + /// + /// - Parameters: + /// - index: The index of the buffer element to retrieve and deinitialize. + /// - Returns: The instance referenced by this index in this buffer. + @inlinable + @_alwaysEmitIntoClient + public func moveElement(from index: Index) -> Element { + assert(startIndex <= index && index < endIndex) + return baseAddress.unsafelyUnwrapped.advanced(by: index).move() + } + + /// Deinitializes the memory underlying the element at `index`. + /// + /// The memory underlying the element at `index` must be initialized. + /// After calling `deinitializeElement()`, the memory underlying this element + /// of the buffer is uninitialized, and still bound to type `Element`. + /// + /// - Parameters: + /// - index: The index of the buffer element to deinitialize. + @inlinable + @_alwaysEmitIntoClient + public func deinitializeElement(at index: Index) { + assert(startIndex <= index && index < endIndex) + let p = baseAddress.unsafelyUnwrapped.advanced(by: index) + p.deinitialize(count: 1) + } +} +#endif + +#if swift(<5.8) +extension Slice { + /// Initializes the buffer slice's memory with with + /// every element of the source. + /// + /// Prior to calling the `initialize(fromContentsOf:)` method + /// on a buffer slice, the memory it references must be uninitialized, + /// or the `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer slice up to, but not including, + /// the returned index is initialized. + /// The buffer slice must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the index of the next uninitialized element + /// in the buffer slice, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to + /// the buffer slice's `startIndex`. If `source` contains as many elements + /// as the buffer slice can hold, the returned index is equal to + /// to the slice's `endIndex`. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Note: The memory regions referenced by `source` and this buffer slice + /// must not overlap. + /// + /// - Parameter source: A collection of elements to be used to + /// initialize the buffer slice's storage. + /// - Returns: The index one past the last element of the buffer slice + /// initialized by this function. + @inlinable + @_alwaysEmitIntoClient + public func initialize( + fromContentsOf source: C + ) -> Index where Base == UnsafeMutableBufferPointer { + let buffer = Base(rebasing: self) + let index = buffer.initialize(fromContentsOf: source) + let distance = buffer.distance(from: buffer.startIndex, to: index) + return startIndex.advanced(by: distance) + } + + /// Moves every element of an initialized source buffer into the + /// uninitialized memory referenced by this buffer slice, leaving the + /// source memory uninitialized and this buffer slice's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a + /// buffer slice, the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer slice up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer slice must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer slice, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// slice's `startIndex`. If `source` contains as many elements as the slice + /// can hold, the returned index is equal to the slice's `endIndex`. + /// + /// - Note: The memory regions referenced by `source` and this buffer slice + /// may overlap. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Parameter source: A buffer containing the values to copy. + /// The memory region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer slice + /// initialized by this function. + @inlinable + @_alwaysEmitIntoClient + public func moveInitialize( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Index where Base == UnsafeMutableBufferPointer { + let buffer = Base(rebasing: self) + let index = buffer.moveInitialize(fromContentsOf: source) + let distance = buffer.distance(from: buffer.startIndex, to: index) + return startIndex.advanced(by: distance) + } + + /// Moves every element of an initialized source buffer slice into the + /// uninitialized memory referenced by this buffer slice, leaving the + /// source memory uninitialized and this buffer slice's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a + /// buffer slice, the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer slice up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer slice must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer slice, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// slice's `startIndex`. If `source` contains as many elements as the slice + /// can hold, the returned index is equal to the slice's `endIndex`. + /// + /// - Note: The memory regions referenced by `source` and this buffer slice + /// may overlap. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Parameter source: A buffer slice containing the values to copy. + /// The memory region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer slice + /// initialized by this function. + @inlinable + @_alwaysEmitIntoClient + public func moveInitialize( + fromContentsOf source: Slice> + ) -> Index where Base == UnsafeMutableBufferPointer { + let buffer = Base(rebasing: self) + let index = buffer.moveInitialize(fromContentsOf: source) + let distance = buffer.distance(from: buffer.startIndex, to: index) + return startIndex.advanced(by: distance) + } + + /// Deinitializes every instance in this buffer slice. + /// + /// The region of memory underlying this buffer slice must be fully + /// initialized. After calling `deinitialize(count:)`, the memory + /// is uninitialized, but still bound to the `Element` type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Returns: A raw buffer to the same range of memory as this buffer. + /// The range of memory is still bound to `Element`. + @discardableResult + @inlinable + @_alwaysEmitIntoClient + public func deinitialize() -> UnsafeMutableRawBufferPointer + where Base == UnsafeMutableBufferPointer { + Base(rebasing: self).deinitialize() + } + + /// Initializes the element at `index` to the given value. + /// + /// The memory underlying the destination element must be uninitialized, + /// or `Element` must be a trivial type. After a call to `initialize(to:)`, + /// the memory underlying this element of the buffer slice is initialized. + /// + /// - Parameters: + /// - value: The value used to initialize the buffer element's memory. + /// - index: The index of the element to initialize + @inlinable + @_alwaysEmitIntoClient + public func initializeElement(at index: Int, to value: Element) + where Base == UnsafeMutableBufferPointer { + assert(startIndex <= index && index < endIndex) + base.baseAddress.unsafelyUnwrapped.advanced(by: index).initialize(to: value) + } +} +#endif + +#if swift(<5.8) +extension UnsafeMutableBufferPointer { + /// Updates every element of this buffer's initialized memory. + /// + /// The buffer’s memory must be initialized or its `Element` type + /// must be a trivial type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Parameters: + /// - repeatedValue: The value used when updating this pointer's memory. + @_alwaysEmitIntoClient + public func update(repeating repeatedValue: Element) { + guard let dstBase = baseAddress else { return } + dstBase.update(repeating: repeatedValue, count: count) + } +} +#endif + +#if swift(<5.8) +extension Slice { + /// Updates every element of this buffer slice's initialized memory. + /// + /// The buffer slice’s memory must be initialized or its `Element` + /// must be a trivial type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Parameters: + /// - repeatedValue: The value used when updating this pointer's memory. + @_alwaysEmitIntoClient + public func update(repeating repeatedValue: Element) + where Base == UnsafeMutableBufferPointer { + Base(rebasing: self).update(repeating: repeatedValue) + } +} +#endif +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeMutablePointer+SE-0370.swift b/Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeMutablePointer+SE-0370.swift new file mode 100644 index 00000000..e7ea2d26 --- /dev/null +++ b/Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeMutablePointer+SE-0370.swift @@ -0,0 +1,72 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +#if swift(<5.8) +extension UnsafeMutablePointer { + /// Update this pointer's initialized memory with the specified number of + /// consecutive copies of the given value. + /// + /// The region of memory starting at this pointer and covering `count` + /// instances of the pointer's `Pointee` type must be initialized or + /// `Pointee` must be a trivial type. After calling + /// `update(repeating:count:)`, the region is initialized. + /// + /// - Parameters: + /// - repeatedValue: The value used when updating this pointer's memory. + /// - count: The number of consecutive elements to update. + /// `count` must not be negative. + @_alwaysEmitIntoClient + internal func update(repeating repeatedValue: Pointee, count: Int) { + assert(count >= 0, "UnsafeMutablePointer.update(repeating:count:) with negative count") + for i in 0 ..< count { + self[i] = repeatedValue + } + } +} +#endif +#else // !COLLECTIONS_SINGLE_MODULE +#if swift(<5.8) +extension UnsafeMutablePointer { + /// Update this pointer's initialized memory with the specified number of + /// consecutive copies of the given value. + /// + /// The region of memory starting at this pointer and covering `count` + /// instances of the pointer's `Pointee` type must be initialized or + /// `Pointee` must be a trivial type. After calling + /// `update(repeating:count:)`, the region is initialized. + /// + /// - Parameters: + /// - repeatedValue: The value used when updating this pointer's memory. + /// - count: The number of consecutive elements to update. + /// `count` must not be negative. + @_alwaysEmitIntoClient + public func update(repeating repeatedValue: Pointee, count: Int) { + assert(count >= 0, "UnsafeMutablePointer.update(repeating:count:) with negative count") + for i in 0 ..< count { + self[i] = repeatedValue + } + } +} +#endif +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeRawPointer extensions.swift b/Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeRawPointer extensions.swift new file mode 100644 index 00000000..f28f2915 --- /dev/null +++ b/Sources/_CollectionsUtilities/Compatibility/autogenerated/UnsafeRawPointer extensions.swift @@ -0,0 +1,164 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +#if compiler(<5.7) || (os(macOS) && compiler(<5.8)) // SE-0334 +extension UnsafeRawPointer { + /// Obtain the next pointer properly aligned to store a value of type `T`. + /// + /// If `self` is properly aligned for accessing `T`, + /// this function returns `self`. + /// + /// - Parameters: + /// - type: the type to be stored at the returned address. + /// - Returns: a pointer properly aligned to store a value of type `T`. + @inlinable + @_alwaysEmitIntoClient + internal func alignedUp(for type: T.Type) -> Self { + let mask = UInt(MemoryLayout.alignment) &- 1 + let bits = (UInt(bitPattern: self) &+ mask) & ~mask + return Self(bitPattern: bits)! + } + + /// Obtain the preceding pointer properly aligned to store a value of type `T`. + /// + /// If `self` is properly aligned for accessing `T`, + /// this function returns `self`. + /// + /// - Parameters: + /// - type: the type to be stored at the returned address. + /// - Returns: a pointer properly aligned to store a value of type `T`. + @inlinable + @_alwaysEmitIntoClient + internal func alignedDown(for type: T.Type) -> Self { + let mask = UInt(MemoryLayout.alignment) &- 1 + let bits = UInt(bitPattern: self) & ~mask + return Self(bitPattern: bits)! + } +} + +extension UnsafeMutableRawPointer { + /// Obtain the next pointer properly aligned to store a value of type `T`. + /// + /// If `self` is properly aligned for accessing `T`, + /// this function returns `self`. + /// + /// - Parameters: + /// - type: the type to be stored at the returned address. + /// - Returns: a pointer properly aligned to store a value of type `T`. + @inlinable + @_alwaysEmitIntoClient + internal func alignedUp(for type: T.Type) -> Self { + let mask = UInt(MemoryLayout.alignment) &- 1 + let bits = (UInt(bitPattern: self) &+ mask) & ~mask + return Self(bitPattern: bits)! + } + + /// Obtain the preceding pointer properly aligned to store a value of type `T`. + /// + /// If `self` is properly aligned for accessing `T`, + /// this function returns `self`. + /// + /// - Parameters: + /// - type: the type to be stored at the returned address. + /// - Returns: a pointer properly aligned to store a value of type `T`. + @inlinable + @_alwaysEmitIntoClient + internal func alignedDown(for type: T.Type) -> Self { + let mask = UInt(MemoryLayout.alignment) &- 1 + let bits = UInt(bitPattern: self) & ~mask + return Self(bitPattern: bits)! + } +} +#endif +#else // !COLLECTIONS_SINGLE_MODULE +#if compiler(<5.7) || (os(macOS) && compiler(<5.8)) // SE-0334 +extension UnsafeRawPointer { + /// Obtain the next pointer properly aligned to store a value of type `T`. + /// + /// If `self` is properly aligned for accessing `T`, + /// this function returns `self`. + /// + /// - Parameters: + /// - type: the type to be stored at the returned address. + /// - Returns: a pointer properly aligned to store a value of type `T`. + @inlinable + @_alwaysEmitIntoClient + public func alignedUp(for type: T.Type) -> Self { + let mask = UInt(MemoryLayout.alignment) &- 1 + let bits = (UInt(bitPattern: self) &+ mask) & ~mask + return Self(bitPattern: bits)! + } + + /// Obtain the preceding pointer properly aligned to store a value of type `T`. + /// + /// If `self` is properly aligned for accessing `T`, + /// this function returns `self`. + /// + /// - Parameters: + /// - type: the type to be stored at the returned address. + /// - Returns: a pointer properly aligned to store a value of type `T`. + @inlinable + @_alwaysEmitIntoClient + public func alignedDown(for type: T.Type) -> Self { + let mask = UInt(MemoryLayout.alignment) &- 1 + let bits = UInt(bitPattern: self) & ~mask + return Self(bitPattern: bits)! + } +} + +extension UnsafeMutableRawPointer { + /// Obtain the next pointer properly aligned to store a value of type `T`. + /// + /// If `self` is properly aligned for accessing `T`, + /// this function returns `self`. + /// + /// - Parameters: + /// - type: the type to be stored at the returned address. + /// - Returns: a pointer properly aligned to store a value of type `T`. + @inlinable + @_alwaysEmitIntoClient + public func alignedUp(for type: T.Type) -> Self { + let mask = UInt(MemoryLayout.alignment) &- 1 + let bits = (UInt(bitPattern: self) &+ mask) & ~mask + return Self(bitPattern: bits)! + } + + /// Obtain the preceding pointer properly aligned to store a value of type `T`. + /// + /// If `self` is properly aligned for accessing `T`, + /// this function returns `self`. + /// + /// - Parameters: + /// - type: the type to be stored at the returned address. + /// - Returns: a pointer properly aligned to store a value of type `T`. + @inlinable + @_alwaysEmitIntoClient + public func alignedDown(for type: T.Type) -> Self { + let mask = UInt(MemoryLayout.alignment) &- 1 + let bits = UInt(bitPattern: self) & ~mask + return Self(bitPattern: bits)! + } +} +#endif +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/Debugging.swift b/Sources/_CollectionsUtilities/Debugging.swift.gyb similarity index 72% rename from Sources/_CollectionsUtilities/Debugging.swift rename to Sources/_CollectionsUtilities/Debugging.swift.gyb index 90470b0d..09dc0e2e 100644 --- a/Sources/_CollectionsUtilities/Debugging.swift +++ b/Sources/_CollectionsUtilities/Debugging.swift.gyb @@ -2,13 +2,20 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} /// True if consistency checking is enabled in the implementation of the /// Swift Collections package, false otherwise. /// @@ -16,10 +23,12 @@ /// returns true -- for example, operations that are documented to take /// O(1) time might take O(*n*) time, or worse. @inlinable @inline(__always) -public var _isCollectionsInternalCheckingEnabled: Bool { +${modifier} var _isCollectionsInternalCheckingEnabled: Bool { #if COLLECTIONS_INTERNAL_CHECKS return true #else return false #endif } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/Descriptions.swift b/Sources/_CollectionsUtilities/Descriptions.swift.gyb similarity index 75% rename from Sources/_CollectionsUtilities/Descriptions.swift rename to Sources/_CollectionsUtilities/Descriptions.swift.gyb index 73f9ad99..d665d0d5 100644 --- a/Sources/_CollectionsUtilities/Descriptions.swift +++ b/Sources/_CollectionsUtilities/Descriptions.swift.gyb @@ -2,29 +2,37 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 // //===----------------------------------------------------------------------===// -public func _addressString(for pointer: UnsafeRawPointer) -> String { +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} + +${modifier} func _addressString(for pointer: UnsafeRawPointer) -> String { let address = UInt(bitPattern: pointer) return "0x\(String(address, radix: 16))" } -public func _addressString(for object: AnyObject) -> String { +${modifier} func _addressString(for object: AnyObject) -> String { _addressString(for: Unmanaged.passUnretained(object).toOpaque()) } @inlinable -public func _addressString(for object: Unmanaged) -> String { +${modifier} func _addressString(for object: Unmanaged) -> String { _addressString(for: object.toOpaque()) } @inlinable -public func _arrayDescription( +${modifier} func _arrayDescription( for elements: C, debug: Bool = false, typeName: String? = nil @@ -53,7 +61,7 @@ public func _arrayDescription( } @inlinable -public func _dictionaryDescription( +${modifier} func _dictionaryDescription( for elements: C, debug: Bool = false, typeName: String? = nil @@ -90,3 +98,5 @@ public func _dictionaryDescription( } return result } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift b/Sources/_CollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift.gyb similarity index 69% rename from Sources/_CollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift rename to Sources/_CollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift.gyb index 518e257e..7462a8a9 100644 --- a/Sources/_CollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift +++ b/Sources/_CollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift.gyb @@ -2,20 +2,29 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension FixedWidthInteger { /// Round up `self` to the nearest power of two, assuming it's representable. /// Returns 0 if `self` isn't positive. @inlinable - public func _roundUpToPowerOfTwo() -> Self { + ${modifier} func _roundUpToPowerOfTwo() -> Self { guard self > 0 else { return 0 } let l = Self.bitWidth - (self &- 1).leadingZeroBitCount return 1 << l } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift b/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb similarity index 88% rename from Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift rename to Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb index bd8e638f..c0a4dc16 100644 --- a/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift +++ b/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb @@ -2,14 +2,20 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension FixedWidthInteger { @inlinable @inline(__always) internal var _nonzeroBitCount: Self { @@ -17,7 +23,7 @@ extension FixedWidthInteger { } @inlinable @inline(__always) - public func _rank(ofBit bit: UInt) -> Int { + ${modifier} func _rank(ofBit bit: UInt) -> Int { assert(bit < Self.bitWidth) let mask: Self = (1 &<< bit) &- 1 return (self & mask).nonzeroBitCount @@ -26,7 +32,7 @@ extension FixedWidthInteger { extension UInt { @_effects(releasenone) - public func _bit(ranked n: Int) -> UInt? { + ${modifier} func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(UInt.bitWidth == 64 || UInt.bitWidth == 32, "Unsupported UInt bitWidth") @@ -75,7 +81,7 @@ extension UInt32 { // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) - public func _bit(ranked n: Int) -> UInt? { + ${modifier} func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) var shift: Self = 0 @@ -114,7 +120,7 @@ extension UInt16 { // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) - public func _bit(ranked n: Int) -> UInt? { + ${modifier} func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) var shift: Self = 0 @@ -143,3 +149,5 @@ extension UInt16 { return UInt(truncatingIfNeeded: shift) } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/IntegerTricks/UInt+first and last set bit.swift b/Sources/_CollectionsUtilities/IntegerTricks/UInt+first and last set bit.swift.gyb similarity index 68% rename from Sources/_CollectionsUtilities/IntegerTricks/UInt+first and last set bit.swift rename to Sources/_CollectionsUtilities/IntegerTricks/UInt+first and last set bit.swift.gyb index 4a0be877..86c46391 100644 --- a/Sources/_CollectionsUtilities/IntegerTricks/UInt+first and last set bit.swift +++ b/Sources/_CollectionsUtilities/IntegerTricks/UInt+first and last set bit.swift.gyb @@ -2,24 +2,33 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension UInt { @inlinable @inline(__always) - public var _firstSetBit: UInt? { + ${modifier} var _firstSetBit: UInt? { guard self != 0 else { return nil } let v = UInt.bitWidth &- 1 &- self.leadingZeroBitCount return UInt(truncatingIfNeeded: v) } @inlinable @inline(__always) - public var _lastSetBit: UInt? { + ${modifier} var _lastSetBit: UInt? { guard self != 0 else { return nil } return UInt(truncatingIfNeeded: self.trailingZeroBitCount) } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/IntegerTricks/UInt+reversed.swift b/Sources/_CollectionsUtilities/IntegerTricks/UInt+reversed.swift.gyb similarity index 73% rename from Sources/_CollectionsUtilities/IntegerTricks/UInt+reversed.swift rename to Sources/_CollectionsUtilities/IntegerTricks/UInt+reversed.swift.gyb index 4d48c501..c24bdffc 100644 --- a/Sources/_CollectionsUtilities/IntegerTricks/UInt+reversed.swift +++ b/Sources/_CollectionsUtilities/IntegerTricks/UInt+reversed.swift.gyb @@ -2,16 +2,23 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension UInt { @inlinable - public var _reversed: UInt { + ${modifier} var _reversed: UInt { // https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel var shift: UInt = UInt(UInt.bitWidth) var mask: UInt = ~0; @@ -25,3 +32,5 @@ extension UInt { return result } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/FixedWidthInteger+roundUpToPowerOfTwo.swift b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/FixedWidthInteger+roundUpToPowerOfTwo.swift new file mode 100644 index 00000000..a20e3806 --- /dev/null +++ b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/FixedWidthInteger+roundUpToPowerOfTwo.swift @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension FixedWidthInteger { + /// Round up `self` to the nearest power of two, assuming it's representable. + /// Returns 0 if `self` isn't positive. + @inlinable + internal func _roundUpToPowerOfTwo() -> Self { + guard self > 0 else { return 0 } + let l = Self.bitWidth - (self &- 1).leadingZeroBitCount + return 1 << l + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension FixedWidthInteger { + /// Round up `self` to the nearest power of two, assuming it's representable. + /// Returns 0 if `self` isn't positive. + @inlinable + public func _roundUpToPowerOfTwo() -> Self { + guard self > 0 else { return 0 } + let l = Self.bitWidth - (self &- 1).leadingZeroBitCount + return 1 << l + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift new file mode 100644 index 00000000..83bc1949 --- /dev/null +++ b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift @@ -0,0 +1,292 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension FixedWidthInteger { + @inlinable @inline(__always) + internal var _nonzeroBitCount: Self { + Self(truncatingIfNeeded: nonzeroBitCount) + } + + @inlinable @inline(__always) + internal func _rank(ofBit bit: UInt) -> Int { + assert(bit < Self.bitWidth) + let mask: Self = (1 &<< bit) &- 1 + return (self & mask).nonzeroBitCount + } +} + +extension UInt { + @_effects(releasenone) + internal func _bit(ranked n: Int) -> UInt? { + // FIXME: Use bit deposit instruction when available (PDEP on Intel). + assert(UInt.bitWidth == 64 || UInt.bitWidth == 32, + "Unsupported UInt bitWidth") + + var shift: Self = 0 + var n = Self(truncatingIfNeeded: n) + + if Self.bitWidth == 64 { + let c32 = (self & 0xFFFFFFFF)._nonzeroBitCount + if n >= c32 { + shift &+= 32 + n &-= c32 + } + } + let c16 = ((self &>> shift) & 0xFFFF)._nonzeroBitCount + if n >= c16 { + shift &+= 16 + n &-= c16 + } + let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount + if n >= c8 { + shift &+= 8 + n &-= c8 + } + let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount + if n >= c4 { + shift &+= 4 + n &-= c4 + } + let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount + if n >= c2 { + shift &+= 2 + n &-= c2 + } + let c1 = (self &>> shift) & 0x1 + if n >= c1 { + shift &+= 1 + n &-= c1 + } + guard n == 0 && (self &>> shift) & 0x1 == 1 else { return nil } + return shift + } +} + +extension UInt32 { + // Returns the position of the `n`th set bit in `self`, i.e., the bit with + // rank `n`. + @_effects(releasenone) + internal func _bit(ranked n: Int) -> UInt? { + // FIXME: Use bit deposit instruction when available (PDEP on Intel). + assert(n >= 0 && n < Self.bitWidth) + var shift: Self = 0 + var n = Self(truncatingIfNeeded: n) + let c16 = (self & 0xFFFF)._nonzeroBitCount + if n >= c16 { + shift = 16 + n -= c16 + } + let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount + if n >= c8 { + shift &+= 8 + n -= c8 + } + let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount + if n >= c4 { + shift &+= 4 + n -= c4 + } + let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount + if n >= c2 { + shift &+= 2 + n -= c2 + } + let c1 = (self &>> shift) & 0x1 + if n >= c1 { + shift &+= 1 + n -= c1 + } + guard n == 0, (self &>> shift) & 0x1 == 1 else { return nil } + return UInt(truncatingIfNeeded: shift) + } +} + +extension UInt16 { + // Returns the position of the `n`th set bit in `self`, i.e., the bit with + // rank `n`. + @_effects(releasenone) + internal func _bit(ranked n: Int) -> UInt? { + // FIXME: Use bit deposit instruction when available (PDEP on Intel). + assert(n >= 0 && n < Self.bitWidth) + var shift: Self = 0 + var n = Self(truncatingIfNeeded: n) + let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount + if n >= c8 { + shift &+= 8 + n -= c8 + } + let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount + if n >= c4 { + shift &+= 4 + n -= c4 + } + let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount + if n >= c2 { + shift &+= 2 + n -= c2 + } + let c1 = (self &>> shift) & 0x1 + if n >= c1 { + shift &+= 1 + n -= c1 + } + guard n == 0, (self &>> shift) & 0x1 == 1 else { return nil } + return UInt(truncatingIfNeeded: shift) + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension FixedWidthInteger { + @inlinable @inline(__always) + internal var _nonzeroBitCount: Self { + Self(truncatingIfNeeded: nonzeroBitCount) + } + + @inlinable @inline(__always) + public func _rank(ofBit bit: UInt) -> Int { + assert(bit < Self.bitWidth) + let mask: Self = (1 &<< bit) &- 1 + return (self & mask).nonzeroBitCount + } +} + +extension UInt { + @_effects(releasenone) + public func _bit(ranked n: Int) -> UInt? { + // FIXME: Use bit deposit instruction when available (PDEP on Intel). + assert(UInt.bitWidth == 64 || UInt.bitWidth == 32, + "Unsupported UInt bitWidth") + + var shift: Self = 0 + var n = Self(truncatingIfNeeded: n) + + if Self.bitWidth == 64 { + let c32 = (self & 0xFFFFFFFF)._nonzeroBitCount + if n >= c32 { + shift &+= 32 + n &-= c32 + } + } + let c16 = ((self &>> shift) & 0xFFFF)._nonzeroBitCount + if n >= c16 { + shift &+= 16 + n &-= c16 + } + let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount + if n >= c8 { + shift &+= 8 + n &-= c8 + } + let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount + if n >= c4 { + shift &+= 4 + n &-= c4 + } + let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount + if n >= c2 { + shift &+= 2 + n &-= c2 + } + let c1 = (self &>> shift) & 0x1 + if n >= c1 { + shift &+= 1 + n &-= c1 + } + guard n == 0 && (self &>> shift) & 0x1 == 1 else { return nil } + return shift + } +} + +extension UInt32 { + // Returns the position of the `n`th set bit in `self`, i.e., the bit with + // rank `n`. + @_effects(releasenone) + public func _bit(ranked n: Int) -> UInt? { + // FIXME: Use bit deposit instruction when available (PDEP on Intel). + assert(n >= 0 && n < Self.bitWidth) + var shift: Self = 0 + var n = Self(truncatingIfNeeded: n) + let c16 = (self & 0xFFFF)._nonzeroBitCount + if n >= c16 { + shift = 16 + n -= c16 + } + let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount + if n >= c8 { + shift &+= 8 + n -= c8 + } + let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount + if n >= c4 { + shift &+= 4 + n -= c4 + } + let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount + if n >= c2 { + shift &+= 2 + n -= c2 + } + let c1 = (self &>> shift) & 0x1 + if n >= c1 { + shift &+= 1 + n -= c1 + } + guard n == 0, (self &>> shift) & 0x1 == 1 else { return nil } + return UInt(truncatingIfNeeded: shift) + } +} + +extension UInt16 { + // Returns the position of the `n`th set bit in `self`, i.e., the bit with + // rank `n`. + @_effects(releasenone) + public func _bit(ranked n: Int) -> UInt? { + // FIXME: Use bit deposit instruction when available (PDEP on Intel). + assert(n >= 0 && n < Self.bitWidth) + var shift: Self = 0 + var n = Self(truncatingIfNeeded: n) + let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount + if n >= c8 { + shift &+= 8 + n -= c8 + } + let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount + if n >= c4 { + shift &+= 4 + n -= c4 + } + let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount + if n >= c2 { + shift &+= 2 + n -= c2 + } + let c1 = (self &>> shift) & 0x1 + if n >= c1 { + shift &+= 1 + n -= c1 + } + guard n == 0, (self &>> shift) & 0x1 == 1 else { return nil } + return UInt(truncatingIfNeeded: shift) + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/UInt+first and last set bit.swift b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/UInt+first and last set bit.swift new file mode 100644 index 00000000..349a772b --- /dev/null +++ b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/UInt+first and last set bit.swift @@ -0,0 +1,54 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension UInt { + @inlinable @inline(__always) + internal var _firstSetBit: UInt? { + guard self != 0 else { return nil } + let v = UInt.bitWidth &- 1 &- self.leadingZeroBitCount + return UInt(truncatingIfNeeded: v) + } + + @inlinable @inline(__always) + internal var _lastSetBit: UInt? { + guard self != 0 else { return nil } + return UInt(truncatingIfNeeded: self.trailingZeroBitCount) + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension UInt { + @inlinable @inline(__always) + public var _firstSetBit: UInt? { + guard self != 0 else { return nil } + let v = UInt.bitWidth &- 1 &- self.leadingZeroBitCount + return UInt(truncatingIfNeeded: v) + } + + @inlinable @inline(__always) + public var _lastSetBit: UInt? { + guard self != 0 else { return nil } + return UInt(truncatingIfNeeded: self.trailingZeroBitCount) + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/UInt+reversed.swift b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/UInt+reversed.swift new file mode 100644 index 00000000..ff90b619 --- /dev/null +++ b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/UInt+reversed.swift @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension UInt { + @inlinable + internal var _reversed: UInt { + // https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel + var shift: UInt = UInt(UInt.bitWidth) + var mask: UInt = ~0; + var result = self + while true { + shift &>>= 1 + guard shift > 0 else { break } + mask ^= mask &<< shift + result = ((result &>> shift) & mask) | ((result &<< shift) & ~mask) + } + return result + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension UInt { + @inlinable + public var _reversed: UInt { + // https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel + var shift: UInt = UInt(UInt.bitWidth) + var mask: UInt = ~0; + var result = self + while true { + shift &>>= 1 + guard shift > 0 else { break } + mask ^= mask &<< shift + result = ((result &>> shift) & mask) | ((result &<< shift) & ~mask) + } + return result + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/RandomAccessCollection+Offsets.swift b/Sources/_CollectionsUtilities/RandomAccessCollection+Offsets.swift.gyb similarity index 62% rename from Sources/_CollectionsUtilities/RandomAccessCollection+Offsets.swift rename to Sources/_CollectionsUtilities/RandomAccessCollection+Offsets.swift.gyb index c82c8238..1faa1452 100644 --- a/Sources/_CollectionsUtilities/RandomAccessCollection+Offsets.swift +++ b/Sources/_CollectionsUtilities/RandomAccessCollection+Offsets.swift.gyb @@ -2,26 +2,35 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension RandomAccessCollection { @_alwaysEmitIntoClient @inline(__always) - public func _index(at offset: Int) -> Index { + ${modifier} func _index(at offset: Int) -> Index { index(startIndex, offsetBy: offset) } @_alwaysEmitIntoClient @inline(__always) - public func _offset(of index: Index) -> Int { + ${modifier} func _offset(of index: Index) -> Int { distance(from: startIndex, to: index) } @_alwaysEmitIntoClient @inline(__always) - public subscript(_offset offset: Int) -> Element { + ${modifier} subscript(_offset offset: Int) -> Element { self[_index(at: offset)] } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift.gyb similarity index 66% rename from Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift rename to Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift.gyb index 712c524c..3cc4377b 100644 --- a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift.gyb @@ -2,33 +2,40 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension _UnsafeBitSet { @frozen - public struct Index: Comparable, Hashable { + ${modifier} struct Index: Comparable, Hashable { @usableFromInline internal typealias _Word = _UnsafeBitSet._Word - public var value: UInt + ${modifier} var value: UInt @inlinable - public init(_ value: UInt) { + ${modifier} init(_ value: UInt) { self.value = value } @inlinable - public init(_ value: Int) { + ${modifier} init(_ value: Int) { self.value = UInt(value) } @inlinable - public init(word: Int, bit: UInt) { + ${modifier} init(word: Int, bit: UInt) { assert(word >= 0 && word <= Int.max / _Word.capacity) assert(bit < _Word.capacity) self.value = UInt(word &* _Word.capacity) &+ bit @@ -38,24 +45,24 @@ extension _UnsafeBitSet { extension _UnsafeBitSet.Index { @inlinable - public var word: Int { + ${modifier} var word: Int { // Note: We perform on UInts to get faster unsigned math (shifts). Int(truncatingIfNeeded: value / UInt(bitPattern: _Word.capacity)) } @inlinable - public var bit: UInt { + ${modifier} var bit: UInt { // Note: We perform on UInts to get faster unsigned math (masking). value % UInt(bitPattern: _Word.capacity) } @inlinable - public var split: (word: Int, bit: UInt) { + ${modifier} var split: (word: Int, bit: UInt) { (word, bit) } @inlinable - public var endSplit: (word: Int, bit: UInt) { + ${modifier} var endSplit: (word: Int, bit: UInt) { let w = word let b = bit if w > 0, b == 0 { return (w &- 1, UInt(_Word.capacity)) } @@ -63,17 +70,17 @@ extension _UnsafeBitSet.Index { } @inlinable - public static func ==(left: Self, right: Self) -> Bool { + ${modifier} static func ==(left: Self, right: Self) -> Bool { left.value == right.value } @inlinable - public static func <(left: Self, right: Self) -> Bool { + ${modifier} static func <(left: Self, right: Self) -> Bool { left.value < right.value } @inlinable - public func hash(into hasher: inout Hasher) { + ${modifier} func hash(into hasher: inout Hasher) { hasher.combine(value) } @@ -87,3 +94,5 @@ extension _UnsafeBitSet.Index { Self(value - 1) } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift.gyb similarity index 75% rename from Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift rename to Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift.gyb index 3d465f6c..3d4d8c7d 100644 --- a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift.gyb @@ -2,34 +2,42 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension _UnsafeBitSet { @frozen - public struct _Word { - public var value: UInt + ${modifier} struct _Word { + ${modifier} var value: UInt @inlinable @inline(__always) - public init(_ value: UInt) { + ${modifier} init(_ value: UInt) { self.value = value } @inlinable @inline(__always) - public init(upTo bit: UInt) { + ${modifier} init(upTo bit: UInt) { assert(bit <= _Word.capacity) self.init((1 << bit) &- 1) } @inlinable @inline(__always) - public init(from start: UInt, to end: UInt) { + ${modifier} init(from start: UInt, to end: UInt) { assert(start <= end && end <= _Word.capacity) self = Self(upTo: end).symmetricDifference(Self(upTo: start)) } @@ -37,7 +45,7 @@ extension _UnsafeBitSet { } extension _UnsafeBitSet._Word: CustomStringConvertible { - public var description: String { + ${modifier} var description: String { String(value, radix: 16) } } @@ -79,7 +87,7 @@ extension _UnsafeBitSet._Word { extension _UnsafeBitSet._Word { @inlinable @inline(__always) - public static func wordCount(forBitCount count: UInt) -> Int { + ${modifier} static func wordCount(forBitCount count: UInt) -> Int { // Note: We perform on UInts to get faster unsigned math (shifts). let width = UInt(bitPattern: Self.capacity) return Int(bitPattern: (count + width - 1) / width) @@ -89,51 +97,51 @@ extension _UnsafeBitSet._Word { extension _UnsafeBitSet._Word { @inlinable @inline(__always) - public static var capacity: Int { + ${modifier} static var capacity: Int { return UInt.bitWidth } @inlinable @inline(__always) - public var count: Int { + ${modifier} var count: Int { value.nonzeroBitCount } @inlinable @inline(__always) - public var isEmpty: Bool { + ${modifier} var isEmpty: Bool { value == 0 } @inlinable @inline(__always) - public var isFull: Bool { + ${modifier} var isFull: Bool { value == UInt.max } @inlinable @inline(__always) - public func contains(_ bit: UInt) -> Bool { + ${modifier} func contains(_ bit: UInt) -> Bool { assert(bit >= 0 && bit < UInt.bitWidth) return value & (1 &<< bit) != 0 } @inlinable @inline(__always) - public var firstMember: UInt? { + ${modifier} var firstMember: UInt? { value._lastSetBit } @inlinable @inline(__always) - public var lastMember: UInt? { + ${modifier} var lastMember: UInt? { value._firstSetBit } @inlinable @inline(__always) @discardableResult - public mutating func insert(_ bit: UInt) -> Bool { + ${modifier} mutating func insert(_ bit: UInt) -> Bool { assert(bit < UInt.bitWidth) let mask: UInt = 1 &<< bit let inserted = value & mask == 0 @@ -144,7 +152,7 @@ extension _UnsafeBitSet._Word { @inlinable @inline(__always) @discardableResult - public mutating func remove(_ bit: UInt) -> Bool { + ${modifier} mutating func remove(_ bit: UInt) -> Bool { assert(bit < UInt.bitWidth) let mask: UInt = 1 &<< bit let removed = (value & mask) != 0 @@ -154,7 +162,7 @@ extension _UnsafeBitSet._Word { @inlinable @inline(__always) - public mutating func update(_ bit: UInt, to value: Bool) { + ${modifier} mutating func update(_ bit: UInt, to value: Bool) { assert(bit < UInt.bitWidth) let mask: UInt = 1 &<< bit if value { @@ -203,12 +211,12 @@ extension _UnsafeBitSet._Word { extension _UnsafeBitSet._Word { @inlinable @inline(__always) - public static var empty: Self { + ${modifier} static var empty: Self { Self(0) } @inline(__always) - public static var allBits: Self { + ${modifier} static var allBits: Self { Self(UInt.max) } } @@ -219,14 +227,14 @@ extension _UnsafeBitSet._Word { // iterator, not the original word. extension _UnsafeBitSet._Word: Sequence, IteratorProtocol { @inlinable @inline(__always) - public var underestimatedCount: Int { + ${modifier} var underestimatedCount: Int { count } /// Return the index of the lowest set bit in this word, /// and also destructively clear it. @inlinable - public mutating func next() -> UInt? { + ${modifier} mutating func next() -> UInt? { guard value != 0 else { return nil } let bit = UInt(truncatingIfNeeded: value.trailingZeroBitCount) value &= value &- 1 // Clear lowest nonzero bit. @@ -236,66 +244,66 @@ extension _UnsafeBitSet._Word: Sequence, IteratorProtocol { extension _UnsafeBitSet._Word: Equatable { @inlinable - public static func ==(left: Self, right: Self) -> Bool { + ${modifier} static func ==(left: Self, right: Self) -> Bool { left.value == right.value } } extension _UnsafeBitSet._Word: Hashable { @inlinable - public func hash(into hasher: inout Hasher) { + ${modifier} func hash(into hasher: inout Hasher) { hasher.combine(value) } } extension _UnsafeBitSet._Word { @inline(__always) - public func complement() -> Self { + ${modifier} func complement() -> Self { Self(~self.value) } @inline(__always) - public mutating func formComplement() { + ${modifier} mutating func formComplement() { self.value = ~self.value } @inline(__always) - public func union(_ other: Self) -> Self { + ${modifier} func union(_ other: Self) -> Self { Self(self.value | other.value) } @inline(__always) - public mutating func formUnion(_ other: Self) { + ${modifier} mutating func formUnion(_ other: Self) { self.value |= other.value } @inline(__always) - public func intersection(_ other: Self) -> Self { + ${modifier} func intersection(_ other: Self) -> Self { Self(self.value & other.value) } @inline(__always) - public mutating func formIntersection(_ other: Self) { + ${modifier} mutating func formIntersection(_ other: Self) { self.value &= other.value } @inline(__always) - public func symmetricDifference(_ other: Self) -> Self { + ${modifier} func symmetricDifference(_ other: Self) -> Self { Self(self.value ^ other.value) } @inline(__always) - public mutating func formSymmetricDifference(_ other: Self) { + ${modifier} mutating func formSymmetricDifference(_ other: Self) { self.value ^= other.value } @inline(__always) - public func subtracting(_ other: Self) -> Self { + ${modifier} func subtracting(_ other: Self) -> Self { Self(self.value & ~other.value) } @inline(__always) - public mutating func subtract(_ other: Self) { + ${modifier} mutating func subtract(_ other: Self) { self.value &= ~other.value } } @@ -303,15 +311,17 @@ extension _UnsafeBitSet._Word { extension _UnsafeBitSet._Word { @inlinable @inline(__always) - public func shiftedDown(by shift: UInt) -> Self { + ${modifier} func shiftedDown(by shift: UInt) -> Self { assert(shift >= 0 && shift < Self.capacity) return Self(self.value &>> shift) } @inlinable @inline(__always) - public func shiftedUp(by shift: UInt) -> Self { + ${modifier} func shiftedUp(by shift: UInt) -> Self { assert(shift >= 0 && shift < Self.capacity) return Self(self.value &<< shift) } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift.gyb similarity index 84% rename from Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift rename to Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift.gyb index 049f24ed..79dc9dc2 100644 --- a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift.gyb @@ -2,19 +2,26 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} /// An unsafe-unowned bitset view over `UInt` storage, providing bit set /// primitives. @frozen -public struct _UnsafeBitSet { +${modifier} struct _UnsafeBitSet { /// An unsafe-unowned storage view. - public let _words: UnsafeBufferPointer<_Word> + ${modifier} let _words: UnsafeBufferPointer<_Word> #if DEBUG /// True when this handle does not support table mutations. @@ -25,7 +32,7 @@ public struct _UnsafeBitSet { @inlinable @inline(__always) - public func ensureMutable() { + ${modifier} func ensureMutable() { #if DEBUG assert(_mutable) #endif @@ -33,14 +40,14 @@ public struct _UnsafeBitSet { @inlinable @inline(__always) - public var _mutableWords: UnsafeMutableBufferPointer<_Word> { + ${modifier} var _mutableWords: UnsafeMutableBufferPointer<_Word> { ensureMutable() return UnsafeMutableBufferPointer(mutating: _words) } @inlinable @inline(__always) - public init( + ${modifier} init( words: UnsafeBufferPointer<_Word>, mutable: Bool ) { @@ -53,7 +60,7 @@ public struct _UnsafeBitSet { @inlinable @inline(__always) - public init( + ${modifier} init( words: UnsafeMutableBufferPointer<_Word>, mutable: Bool ) { @@ -64,7 +71,7 @@ public struct _UnsafeBitSet { extension _UnsafeBitSet { @inlinable @inline(__always) - public var wordCount: Int { + ${modifier} var wordCount: Int { _words.count } } @@ -72,7 +79,7 @@ extension _UnsafeBitSet { extension _UnsafeBitSet { @inlinable @inline(__always) - public static func withTemporaryBitSet( + ${modifier} static func withTemporaryBitSet( capacity: Int, run body: (inout _UnsafeBitSet) throws -> R ) rethrows -> R { @@ -82,7 +89,7 @@ extension _UnsafeBitSet { @inlinable @inline(__always) - public static func withTemporaryBitSet( + ${modifier} static func withTemporaryBitSet( wordCount: Int, run body: (inout Self) throws -> R ) rethrows -> R { @@ -94,7 +101,7 @@ extension _UnsafeBitSet { } @inline(never) - public static func _withTemporaryBitSet( + ${modifier} static func _withTemporaryBitSet( wordCount: Int, run body: (inout Self) throws -> Void ) rethrows { @@ -139,11 +146,11 @@ extension _UnsafeBitSet { extension _UnsafeBitSet { @_effects(readnone) @inline(__always) - public static func wordCount(forCapacity capacity: UInt) -> Int { + ${modifier} static func wordCount(forCapacity capacity: UInt) -> Int { _Word.wordCount(forBitCount: capacity) } - public var capacity: UInt { + ${modifier} var capacity: UInt { @inline(__always) get { UInt(wordCount &* _Word.capacity) @@ -156,7 +163,7 @@ extension _UnsafeBitSet { } @inline(__always) - public func contains(_ element: UInt) -> Bool { + ${modifier} func contains(_ element: UInt) -> Bool { let (word, bit) = Index(element).split guard word < wordCount else { return false } return _words[word].contains(bit) @@ -164,7 +171,7 @@ extension _UnsafeBitSet { @_effects(releasenone) @discardableResult - public mutating func insert(_ element: UInt) -> Bool { + ${modifier} mutating func insert(_ element: UInt) -> Bool { ensureMutable() assert(isWithinBounds(element)) let index = Index(element) @@ -173,7 +180,7 @@ extension _UnsafeBitSet { @_effects(releasenone) @discardableResult - public mutating func remove(_ element: UInt) -> Bool { + ${modifier} mutating func remove(_ element: UInt) -> Bool { ensureMutable() let index = Index(element) if index.word >= _words.count { return false } @@ -181,7 +188,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) - public mutating func update(_ member: UInt, to newValue: Bool) -> Bool { + ${modifier} mutating func update(_ member: UInt, to newValue: Bool) -> Bool { ensureMutable() let (w, b) = Index(member).split _mutableWords[w].update(b, to: newValue) @@ -189,7 +196,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) - public mutating func insertAll(upTo max: UInt) { + ${modifier} mutating func insertAll(upTo max: UInt) { assert(max <= capacity) guard max > 0 else { return } let (w, b) = Index(max).split @@ -204,7 +211,7 @@ extension _UnsafeBitSet { @_alwaysEmitIntoClient @inline(__always) @discardableResult - public mutating func insert(_ element: Int) -> Bool { + ${modifier} mutating func insert(_ element: Int) -> Bool { precondition(element >= 0) return insert(UInt(bitPattern: element)) } @@ -212,36 +219,36 @@ extension _UnsafeBitSet { @_alwaysEmitIntoClient @inline(__always) @discardableResult - public mutating func remove(_ element: Int) -> Bool { + ${modifier} mutating func remove(_ element: Int) -> Bool { guard element >= 0 else { return false } return remove(UInt(bitPattern: element)) } @_alwaysEmitIntoClient @inline(__always) - public mutating func insertAll(upTo max: Int) { + ${modifier} mutating func insertAll(upTo max: Int) { precondition(max >= 0) return insertAll(upTo: UInt(bitPattern: max)) } } extension _UnsafeBitSet: Sequence { - public typealias Element = UInt + ${modifier} typealias Element = UInt @inlinable @inline(__always) - public var underestimatedCount: Int { + ${modifier} var underestimatedCount: Int { count // FIXME: really? } @inlinable @inline(__always) - public func makeIterator() -> Iterator { + ${modifier} func makeIterator() -> Iterator { return Iterator(self) } @frozen - public struct Iterator: IteratorProtocol { + ${modifier} struct Iterator: IteratorProtocol { @usableFromInline internal let _bitset: _UnsafeBitSet @@ -259,7 +266,7 @@ extension _UnsafeBitSet: Sequence { } @_effects(releasenone) - public mutating func next() -> UInt? { + ${modifier} mutating func next() -> UInt? { if let bit = _word.next() { return Index(word: _index, bit: bit).value } @@ -278,35 +285,35 @@ extension _UnsafeBitSet: Sequence { extension _UnsafeBitSet: BidirectionalCollection { @inlinable @inline(__always) - public var count: Int { + ${modifier} var count: Int { _words.reduce(0) { $0 + $1.count } } @inlinable @inline(__always) - public var isEmpty: Bool { + ${modifier} var isEmpty: Bool { _words.firstIndex(where: { !$0.isEmpty }) == nil } @inlinable - public var startIndex: Index { + ${modifier} var startIndex: Index { let word = _words.firstIndex { !$0.isEmpty } guard let word = word else { return endIndex } return Index(word: word, bit: _words[word].firstMember!) } @inlinable - public var endIndex: Index { + ${modifier} var endIndex: Index { Index(word: wordCount, bit: 0) } @inlinable - public subscript(position: Index) -> UInt { + ${modifier} subscript(position: Index) -> UInt { position.value } @_effects(releasenone) - public func index(after index: Index) -> Index { + ${modifier} func index(after index: Index) -> Index { precondition(index < endIndex, "Index out of bounds") var word = index.word var w = _words[word] @@ -322,7 +329,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) - public func index(before index: Index) -> Index { + ${modifier} func index(before index: Index) -> Index { precondition(index <= endIndex, "Index out of bounds") var word = index.word var w: _Word @@ -341,7 +348,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) - public func distance(from start: Index, to end: Index) -> Int { + ${modifier} func distance(from start: Index, to end: Index) -> Int { precondition(start <= endIndex && end <= endIndex, "Index out of bounds") let isNegative = end < start let (start, end) = (Swift.min(start, end), Swift.max(start, end)) @@ -372,7 +379,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) - public func index(_ i: Index, offsetBy distance: Int) -> Index { + ${modifier} func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i <= endIndex, "Index out of bounds") precondition(i == endIndex || contains(i.value), "Invalid index") guard distance != 0 else { return i } @@ -412,7 +419,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) - public func index( + ${modifier} func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { precondition(i <= endIndex && limit <= endIndex, "Index out of bounds") @@ -464,3 +471,5 @@ extension _UnsafeBitSet: BidirectionalCollection { return nil } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+Index.swift b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+Index.swift new file mode 100644 index 00000000..56238831 --- /dev/null +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+Index.swift @@ -0,0 +1,182 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension _UnsafeBitSet { + @frozen + internal struct Index: Comparable, Hashable { + @usableFromInline + internal typealias _Word = _UnsafeBitSet._Word + + internal var value: UInt + + @inlinable + internal init(_ value: UInt) { + self.value = value + } + + @inlinable + internal init(_ value: Int) { + self.value = UInt(value) + } + + @inlinable + internal init(word: Int, bit: UInt) { + assert(word >= 0 && word <= Int.max / _Word.capacity) + assert(bit < _Word.capacity) + self.value = UInt(word &* _Word.capacity) &+ bit + } + } +} + +extension _UnsafeBitSet.Index { + @inlinable + internal var word: Int { + // Note: We perform on UInts to get faster unsigned math (shifts). + Int(truncatingIfNeeded: value / UInt(bitPattern: _Word.capacity)) + } + + @inlinable + internal var bit: UInt { + // Note: We perform on UInts to get faster unsigned math (masking). + value % UInt(bitPattern: _Word.capacity) + } + + @inlinable + internal var split: (word: Int, bit: UInt) { + (word, bit) + } + + @inlinable + internal var endSplit: (word: Int, bit: UInt) { + let w = word + let b = bit + if w > 0, b == 0 { return (w &- 1, UInt(_Word.capacity)) } + return (w, b) + } + + @inlinable + internal static func ==(left: Self, right: Self) -> Bool { + left.value == right.value + } + + @inlinable + internal static func <(left: Self, right: Self) -> Bool { + left.value < right.value + } + + @inlinable + internal func hash(into hasher: inout Hasher) { + hasher.combine(value) + } + + @inlinable + internal func _successor() -> Self { + Self(value + 1) + } + + @inlinable + internal func _predecessor() -> Self { + Self(value - 1) + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension _UnsafeBitSet { + @frozen + public struct Index: Comparable, Hashable { + @usableFromInline + internal typealias _Word = _UnsafeBitSet._Word + + public var value: UInt + + @inlinable + public init(_ value: UInt) { + self.value = value + } + + @inlinable + public init(_ value: Int) { + self.value = UInt(value) + } + + @inlinable + public init(word: Int, bit: UInt) { + assert(word >= 0 && word <= Int.max / _Word.capacity) + assert(bit < _Word.capacity) + self.value = UInt(word &* _Word.capacity) &+ bit + } + } +} + +extension _UnsafeBitSet.Index { + @inlinable + public var word: Int { + // Note: We perform on UInts to get faster unsigned math (shifts). + Int(truncatingIfNeeded: value / UInt(bitPattern: _Word.capacity)) + } + + @inlinable + public var bit: UInt { + // Note: We perform on UInts to get faster unsigned math (masking). + value % UInt(bitPattern: _Word.capacity) + } + + @inlinable + public var split: (word: Int, bit: UInt) { + (word, bit) + } + + @inlinable + public var endSplit: (word: Int, bit: UInt) { + let w = word + let b = bit + if w > 0, b == 0 { return (w &- 1, UInt(_Word.capacity)) } + return (w, b) + } + + @inlinable + public static func ==(left: Self, right: Self) -> Bool { + left.value == right.value + } + + @inlinable + public static func <(left: Self, right: Self) -> Bool { + left.value < right.value + } + + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(value) + } + + @inlinable + internal func _successor() -> Self { + Self(value + 1) + } + + @inlinable + internal func _predecessor() -> Self { + Self(value - 1) + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+_Word.swift b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+_Word.swift new file mode 100644 index 00000000..80dfec86 --- /dev/null +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+_Word.swift @@ -0,0 +1,639 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension _UnsafeBitSet { + @frozen + internal struct _Word { + internal var value: UInt + + @inlinable + @inline(__always) + internal init(_ value: UInt) { + self.value = value + } + + @inlinable + @inline(__always) + internal init(upTo bit: UInt) { + assert(bit <= _Word.capacity) + self.init((1 << bit) &- 1) + } + + @inlinable + @inline(__always) + internal init(from start: UInt, to end: UInt) { + assert(start <= end && end <= _Word.capacity) + self = Self(upTo: end).symmetricDifference(Self(upTo: start)) + } + } +} + +extension _UnsafeBitSet._Word: CustomStringConvertible { + internal var description: String { + String(value, radix: 16) + } +} + +extension _UnsafeBitSet._Word { + /// Returns the `n`th member in `self`. + /// + /// - Parameter n: The offset of the element to retrieve. This value is + /// decremented by the number of items found in this `self` towards the + /// value we're looking for. (If the function returns non-nil, then `n` + /// is set to `0` on return.) + /// - Returns: If this word contains enough members to satisfy the request, + /// then this function returns the member found. Otherwise it returns nil. + @inline(never) + internal func nthElement(_ n: inout UInt) -> UInt? { + let c = UInt(bitPattern: count) + guard n < c else { + n &-= c + return nil + } + let m = Int(bitPattern: n) + n = 0 + return value._bit(ranked: m)! + } + + @inline(never) + internal func nthElementFromEnd(_ n: inout UInt) -> UInt? { + let c = UInt(bitPattern: count) + guard n < c else { + n &-= c + return nil + } + let m = Int(bitPattern: c &- 1 &- n) + n = 0 + return value._bit(ranked: m)! + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + internal static func wordCount(forBitCount count: UInt) -> Int { + // Note: We perform on UInts to get faster unsigned math (shifts). + let width = UInt(bitPattern: Self.capacity) + return Int(bitPattern: (count + width - 1) / width) + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + internal static var capacity: Int { + return UInt.bitWidth + } + + @inlinable + @inline(__always) + internal var count: Int { + value.nonzeroBitCount + } + + @inlinable + @inline(__always) + internal var isEmpty: Bool { + value == 0 + } + + @inlinable + @inline(__always) + internal var isFull: Bool { + value == UInt.max + } + + @inlinable + @inline(__always) + internal func contains(_ bit: UInt) -> Bool { + assert(bit >= 0 && bit < UInt.bitWidth) + return value & (1 &<< bit) != 0 + } + + @inlinable + @inline(__always) + internal var firstMember: UInt? { + value._lastSetBit + } + + @inlinable + @inline(__always) + internal var lastMember: UInt? { + value._firstSetBit + } + + @inlinable + @inline(__always) + @discardableResult + internal mutating func insert(_ bit: UInt) -> Bool { + assert(bit < UInt.bitWidth) + let mask: UInt = 1 &<< bit + let inserted = value & mask == 0 + value |= mask + return inserted + } + + @inlinable + @inline(__always) + @discardableResult + internal mutating func remove(_ bit: UInt) -> Bool { + assert(bit < UInt.bitWidth) + let mask: UInt = 1 &<< bit + let removed = (value & mask) != 0 + value &= ~mask + return removed + } + + @inlinable + @inline(__always) + internal mutating func update(_ bit: UInt, to value: Bool) { + assert(bit < UInt.bitWidth) + let mask: UInt = 1 &<< bit + if value { + self.value |= mask + } else { + self.value &= ~mask + } + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + internal mutating func insertAll(upTo bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + let mask: UInt = (1 as UInt &<< bit) &- 1 + value |= mask + } + + @inlinable + @inline(__always) + internal mutating func removeAll(upTo bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + let mask = UInt.max &<< bit + value &= mask + } + + @inlinable + @inline(__always) + internal mutating func removeAll(through bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + var mask = UInt.max &<< bit + mask &= mask &- 1 // Clear lowest nonzero bit. + value &= mask + } + + @inlinable + @inline(__always) + internal mutating func removeAll(from bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + let mask: UInt = (1 as UInt &<< bit) &- 1 + value &= mask + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + internal static var empty: Self { + Self(0) + } + + @inline(__always) + internal static var allBits: Self { + Self(UInt.max) + } +} + +// _Word implements Sequence by using a copy of itself as its Iterator. +// Iteration with `next()` destroys the word's value; however, this won't cause +// problems in normal use, because `next()` is usually called on a separate +// iterator, not the original word. +extension _UnsafeBitSet._Word: Sequence, IteratorProtocol { + @inlinable @inline(__always) + internal var underestimatedCount: Int { + count + } + + /// Return the index of the lowest set bit in this word, + /// and also destructively clear it. + @inlinable + internal mutating func next() -> UInt? { + guard value != 0 else { return nil } + let bit = UInt(truncatingIfNeeded: value.trailingZeroBitCount) + value &= value &- 1 // Clear lowest nonzero bit. + return bit + } +} + +extension _UnsafeBitSet._Word: Equatable { + @inlinable + internal static func ==(left: Self, right: Self) -> Bool { + left.value == right.value + } +} + +extension _UnsafeBitSet._Word: Hashable { + @inlinable + internal func hash(into hasher: inout Hasher) { + hasher.combine(value) + } +} + +extension _UnsafeBitSet._Word { + @inline(__always) + internal func complement() -> Self { + Self(~self.value) + } + + @inline(__always) + internal mutating func formComplement() { + self.value = ~self.value + } + + @inline(__always) + internal func union(_ other: Self) -> Self { + Self(self.value | other.value) + } + + @inline(__always) + internal mutating func formUnion(_ other: Self) { + self.value |= other.value + } + + @inline(__always) + internal func intersection(_ other: Self) -> Self { + Self(self.value & other.value) + } + + @inline(__always) + internal mutating func formIntersection(_ other: Self) { + self.value &= other.value + } + + @inline(__always) + internal func symmetricDifference(_ other: Self) -> Self { + Self(self.value ^ other.value) + } + + @inline(__always) + internal mutating func formSymmetricDifference(_ other: Self) { + self.value ^= other.value + } + + @inline(__always) + internal func subtracting(_ other: Self) -> Self { + Self(self.value & ~other.value) + } + + @inline(__always) + internal mutating func subtract(_ other: Self) { + self.value &= ~other.value + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + internal func shiftedDown(by shift: UInt) -> Self { + assert(shift >= 0 && shift < Self.capacity) + return Self(self.value &>> shift) + } + + @inlinable + @inline(__always) + internal func shiftedUp(by shift: UInt) -> Self { + assert(shift >= 0 && shift < Self.capacity) + return Self(self.value &<< shift) + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension _UnsafeBitSet { + @frozen + public struct _Word { + public var value: UInt + + @inlinable + @inline(__always) + public init(_ value: UInt) { + self.value = value + } + + @inlinable + @inline(__always) + public init(upTo bit: UInt) { + assert(bit <= _Word.capacity) + self.init((1 << bit) &- 1) + } + + @inlinable + @inline(__always) + public init(from start: UInt, to end: UInt) { + assert(start <= end && end <= _Word.capacity) + self = Self(upTo: end).symmetricDifference(Self(upTo: start)) + } + } +} + +extension _UnsafeBitSet._Word: CustomStringConvertible { + public var description: String { + String(value, radix: 16) + } +} + +extension _UnsafeBitSet._Word { + /// Returns the `n`th member in `self`. + /// + /// - Parameter n: The offset of the element to retrieve. This value is + /// decremented by the number of items found in this `self` towards the + /// value we're looking for. (If the function returns non-nil, then `n` + /// is set to `0` on return.) + /// - Returns: If this word contains enough members to satisfy the request, + /// then this function returns the member found. Otherwise it returns nil. + @inline(never) + internal func nthElement(_ n: inout UInt) -> UInt? { + let c = UInt(bitPattern: count) + guard n < c else { + n &-= c + return nil + } + let m = Int(bitPattern: n) + n = 0 + return value._bit(ranked: m)! + } + + @inline(never) + internal func nthElementFromEnd(_ n: inout UInt) -> UInt? { + let c = UInt(bitPattern: count) + guard n < c else { + n &-= c + return nil + } + let m = Int(bitPattern: c &- 1 &- n) + n = 0 + return value._bit(ranked: m)! + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + public static func wordCount(forBitCount count: UInt) -> Int { + // Note: We perform on UInts to get faster unsigned math (shifts). + let width = UInt(bitPattern: Self.capacity) + return Int(bitPattern: (count + width - 1) / width) + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + public static var capacity: Int { + return UInt.bitWidth + } + + @inlinable + @inline(__always) + public var count: Int { + value.nonzeroBitCount + } + + @inlinable + @inline(__always) + public var isEmpty: Bool { + value == 0 + } + + @inlinable + @inline(__always) + public var isFull: Bool { + value == UInt.max + } + + @inlinable + @inline(__always) + public func contains(_ bit: UInt) -> Bool { + assert(bit >= 0 && bit < UInt.bitWidth) + return value & (1 &<< bit) != 0 + } + + @inlinable + @inline(__always) + public var firstMember: UInt? { + value._lastSetBit + } + + @inlinable + @inline(__always) + public var lastMember: UInt? { + value._firstSetBit + } + + @inlinable + @inline(__always) + @discardableResult + public mutating func insert(_ bit: UInt) -> Bool { + assert(bit < UInt.bitWidth) + let mask: UInt = 1 &<< bit + let inserted = value & mask == 0 + value |= mask + return inserted + } + + @inlinable + @inline(__always) + @discardableResult + public mutating func remove(_ bit: UInt) -> Bool { + assert(bit < UInt.bitWidth) + let mask: UInt = 1 &<< bit + let removed = (value & mask) != 0 + value &= ~mask + return removed + } + + @inlinable + @inline(__always) + public mutating func update(_ bit: UInt, to value: Bool) { + assert(bit < UInt.bitWidth) + let mask: UInt = 1 &<< bit + if value { + self.value |= mask + } else { + self.value &= ~mask + } + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + internal mutating func insertAll(upTo bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + let mask: UInt = (1 as UInt &<< bit) &- 1 + value |= mask + } + + @inlinable + @inline(__always) + internal mutating func removeAll(upTo bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + let mask = UInt.max &<< bit + value &= mask + } + + @inlinable + @inline(__always) + internal mutating func removeAll(through bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + var mask = UInt.max &<< bit + mask &= mask &- 1 // Clear lowest nonzero bit. + value &= mask + } + + @inlinable + @inline(__always) + internal mutating func removeAll(from bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + let mask: UInt = (1 as UInt &<< bit) &- 1 + value &= mask + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + public static var empty: Self { + Self(0) + } + + @inline(__always) + public static var allBits: Self { + Self(UInt.max) + } +} + +// _Word implements Sequence by using a copy of itself as its Iterator. +// Iteration with `next()` destroys the word's value; however, this won't cause +// problems in normal use, because `next()` is usually called on a separate +// iterator, not the original word. +extension _UnsafeBitSet._Word: Sequence, IteratorProtocol { + @inlinable @inline(__always) + public var underestimatedCount: Int { + count + } + + /// Return the index of the lowest set bit in this word, + /// and also destructively clear it. + @inlinable + public mutating func next() -> UInt? { + guard value != 0 else { return nil } + let bit = UInt(truncatingIfNeeded: value.trailingZeroBitCount) + value &= value &- 1 // Clear lowest nonzero bit. + return bit + } +} + +extension _UnsafeBitSet._Word: Equatable { + @inlinable + public static func ==(left: Self, right: Self) -> Bool { + left.value == right.value + } +} + +extension _UnsafeBitSet._Word: Hashable { + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(value) + } +} + +extension _UnsafeBitSet._Word { + @inline(__always) + public func complement() -> Self { + Self(~self.value) + } + + @inline(__always) + public mutating func formComplement() { + self.value = ~self.value + } + + @inline(__always) + public func union(_ other: Self) -> Self { + Self(self.value | other.value) + } + + @inline(__always) + public mutating func formUnion(_ other: Self) { + self.value |= other.value + } + + @inline(__always) + public func intersection(_ other: Self) -> Self { + Self(self.value & other.value) + } + + @inline(__always) + public mutating func formIntersection(_ other: Self) { + self.value &= other.value + } + + @inline(__always) + public func symmetricDifference(_ other: Self) -> Self { + Self(self.value ^ other.value) + } + + @inline(__always) + public mutating func formSymmetricDifference(_ other: Self) { + self.value ^= other.value + } + + @inline(__always) + public func subtracting(_ other: Self) -> Self { + Self(self.value & ~other.value) + } + + @inline(__always) + public mutating func subtract(_ other: Self) { + self.value &= ~other.value + } +} + +extension _UnsafeBitSet._Word { + @inlinable + @inline(__always) + public func shiftedDown(by shift: UInt) -> Self { + assert(shift >= 0 && shift < Self.capacity) + return Self(self.value &>> shift) + } + + @inlinable + @inline(__always) + public func shiftedUp(by shift: UInt) -> Self { + assert(shift >= 0 && shift < Self.capacity) + return Self(self.value &<< shift) + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet.swift b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet.swift new file mode 100644 index 00000000..e3c11a6b --- /dev/null +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet.swift @@ -0,0 +1,936 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +/// An unsafe-unowned bitset view over `UInt` storage, providing bit set +/// primitives. +@frozen +internal struct _UnsafeBitSet { + /// An unsafe-unowned storage view. + internal let _words: UnsafeBufferPointer<_Word> + +#if DEBUG + /// True when this handle does not support table mutations. + /// (This is only checked in debug builds.) + @usableFromInline + internal let _mutable: Bool +#endif + + @inlinable + @inline(__always) + internal func ensureMutable() { +#if DEBUG + assert(_mutable) +#endif + } + + @inlinable + @inline(__always) + internal var _mutableWords: UnsafeMutableBufferPointer<_Word> { + ensureMutable() + return UnsafeMutableBufferPointer(mutating: _words) + } + + @inlinable + @inline(__always) + internal init( + words: UnsafeBufferPointer<_Word>, + mutable: Bool + ) { + assert(words.baseAddress != nil) + self._words = words +#if DEBUG + self._mutable = mutable +#endif + } + + @inlinable + @inline(__always) + internal init( + words: UnsafeMutableBufferPointer<_Word>, + mutable: Bool + ) { + self.init(words: UnsafeBufferPointer(words), mutable: mutable) + } +} + +extension _UnsafeBitSet { + @inlinable + @inline(__always) + internal var wordCount: Int { + _words.count + } +} + +extension _UnsafeBitSet { + @inlinable + @inline(__always) + internal static func withTemporaryBitSet( + capacity: Int, + run body: (inout _UnsafeBitSet) throws -> R + ) rethrows -> R { + let wordCount = _UnsafeBitSet.wordCount(forCapacity: UInt(capacity)) + return try withTemporaryBitSet(wordCount: wordCount, run: body) + } + + @inlinable + @inline(__always) + internal static func withTemporaryBitSet( + wordCount: Int, + run body: (inout Self) throws -> R + ) rethrows -> R { + var result: R? + try _withTemporaryBitSet(wordCount: wordCount) { bitset in + result = try body(&bitset) + } + return result! + } + + @inline(never) + internal static func _withTemporaryBitSet( + wordCount: Int, + run body: (inout Self) throws -> Void + ) rethrows { + try _withTemporaryUninitializedBitSet(wordCount: wordCount) { handle in + handle._mutableWords.initialize(repeating: .empty) + try body(&handle) + } + } + + internal static func _withTemporaryUninitializedBitSet( + wordCount: Int, + run body: (inout Self) throws -> Void + ) rethrows { + assert(wordCount >= 0) +#if compiler(>=5.6) + return try withUnsafeTemporaryAllocation( + of: _Word.self, capacity: wordCount + ) { words in + var bitset = Self(words: words, mutable: true) + return try body(&bitset) + } +#else + if wordCount <= 2 { + var buffer: (_Word, _Word) = (.empty, .empty) + return try withUnsafeMutablePointer(to: &buffer) { p in + // Homogeneous tuples are layout-compatible with their component type. + let start = UnsafeMutableRawPointer(p) + .assumingMemoryBound(to: _Word.self) + let words = UnsafeMutableBufferPointer(start: start, count: wordCount) + var bitset = Self(words: words, mutable: true) + return try body(&bitset) + } + } + let words = UnsafeMutableBufferPointer<_Word>.allocate(capacity: wordCount) + defer { words.deallocate() } + var bitset = Self(words: words, mutable: true) + return try body(&bitset) +#endif + } +} + +extension _UnsafeBitSet { + @_effects(readnone) + @inline(__always) + internal static func wordCount(forCapacity capacity: UInt) -> Int { + _Word.wordCount(forBitCount: capacity) + } + + internal var capacity: UInt { + @inline(__always) + get { + UInt(wordCount &* _Word.capacity) + } + } + + @inline(__always) + internal func isWithinBounds(_ element: UInt) -> Bool { + element < capacity + } + + @inline(__always) + internal func contains(_ element: UInt) -> Bool { + let (word, bit) = Index(element).split + guard word < wordCount else { return false } + return _words[word].contains(bit) + } + + @_effects(releasenone) + @discardableResult + internal mutating func insert(_ element: UInt) -> Bool { + ensureMutable() + assert(isWithinBounds(element)) + let index = Index(element) + return _mutableWords[index.word].insert(index.bit) + } + + @_effects(releasenone) + @discardableResult + internal mutating func remove(_ element: UInt) -> Bool { + ensureMutable() + let index = Index(element) + if index.word >= _words.count { return false } + return _mutableWords[index.word].remove(index.bit) + } + + @_effects(releasenone) + internal mutating func update(_ member: UInt, to newValue: Bool) -> Bool { + ensureMutable() + let (w, b) = Index(member).split + _mutableWords[w].update(b, to: newValue) + return w == _words.count &- 1 + } + + @_effects(releasenone) + internal mutating func insertAll(upTo max: UInt) { + assert(max <= capacity) + guard max > 0 else { return } + let (w, b) = Index(max).split + for i in 0 ..< w { + _mutableWords[i] = .allBits + } + if b > 0 { + _mutableWords[w].insertAll(upTo: b) + } + } + + @_alwaysEmitIntoClient + @inline(__always) + @discardableResult + internal mutating func insert(_ element: Int) -> Bool { + precondition(element >= 0) + return insert(UInt(bitPattern: element)) + } + + @_alwaysEmitIntoClient + @inline(__always) + @discardableResult + internal mutating func remove(_ element: Int) -> Bool { + guard element >= 0 else { return false } + return remove(UInt(bitPattern: element)) + } + + @_alwaysEmitIntoClient + @inline(__always) + internal mutating func insertAll(upTo max: Int) { + precondition(max >= 0) + return insertAll(upTo: UInt(bitPattern: max)) + } +} + +extension _UnsafeBitSet: Sequence { + internal typealias Element = UInt + + @inlinable + @inline(__always) + internal var underestimatedCount: Int { + count // FIXME: really? + } + + @inlinable + @inline(__always) + internal func makeIterator() -> Iterator { + return Iterator(self) + } + + @frozen + internal struct Iterator: IteratorProtocol { + @usableFromInline + internal let _bitset: _UnsafeBitSet + + @usableFromInline + internal var _index: Int + + @usableFromInline + internal var _word: _Word + + @inlinable + internal init(_ bitset: _UnsafeBitSet) { + self._bitset = bitset + self._index = 0 + self._word = bitset.wordCount > 0 ? bitset._words[0] : .empty + } + + @_effects(releasenone) + internal mutating func next() -> UInt? { + if let bit = _word.next() { + return Index(word: _index, bit: bit).value + } + while (_index + 1) < _bitset.wordCount { + _index += 1 + _word = _bitset._words[_index] + if let bit = _word.next() { + return Index(word: _index, bit: bit).value + } + } + return nil + } + } +} + +extension _UnsafeBitSet: BidirectionalCollection { + @inlinable + @inline(__always) + internal var count: Int { + _words.reduce(0) { $0 + $1.count } + } + + @inlinable + @inline(__always) + internal var isEmpty: Bool { + _words.firstIndex(where: { !$0.isEmpty }) == nil + } + + @inlinable + internal var startIndex: Index { + let word = _words.firstIndex { !$0.isEmpty } + guard let word = word else { return endIndex } + return Index(word: word, bit: _words[word].firstMember!) + } + + @inlinable + internal var endIndex: Index { + Index(word: wordCount, bit: 0) + } + + @inlinable + internal subscript(position: Index) -> UInt { + position.value + } + + @_effects(releasenone) + internal func index(after index: Index) -> Index { + precondition(index < endIndex, "Index out of bounds") + var word = index.word + var w = _words[word] + w.removeAll(through: index.bit) + while w.isEmpty { + word += 1 + guard word < wordCount else { + return Index(word: wordCount, bit: 0) + } + w = _words[word] + } + return Index(word: word, bit: w.firstMember!) + } + + @_effects(releasenone) + internal func index(before index: Index) -> Index { + precondition(index <= endIndex, "Index out of bounds") + var word = index.word + var w: _Word + if index.bit > 0 { + w = _words[word] + w.removeAll(from: index.bit) + } else { + w = .empty + } + while w.isEmpty { + word -= 1 + precondition(word >= 0, "Can't advance below startIndex") + w = _words[word] + } + return Index(word: word, bit: w.lastMember!) + } + + @_effects(releasenone) + internal func distance(from start: Index, to end: Index) -> Int { + precondition(start <= endIndex && end <= endIndex, "Index out of bounds") + let isNegative = end < start + let (start, end) = (Swift.min(start, end), Swift.max(start, end)) + + let (w1, b1) = start.split + let (w2, b2) = end.split + + if w1 == w2 { + guard w1 < wordCount else { return 0 } + let mask = _Word(from: b1, to: b2) + let c = _words[w1].intersection(mask).count + return isNegative ? -c : c + } + + var c = 0 + var w = w1 + guard w < wordCount else { return 0 } + + c &+= _words[w].subtracting(_Word(upTo: b1)).count + w &+= 1 + while w < w2 { + c &+= _words[w].count + w &+= 1 + } + guard w < wordCount else { return isNegative ? -c : c } + c &+= _words[w].intersection(_Word(upTo: b2)).count + return isNegative ? -c : c + } + + @_effects(releasenone) + internal func index(_ i: Index, offsetBy distance: Int) -> Index { + precondition(i <= endIndex, "Index out of bounds") + precondition(i == endIndex || contains(i.value), "Invalid index") + guard distance != 0 else { return i } + var remaining = distance.magnitude + if distance > 0 { + var (w, b) = i.split + precondition(w < wordCount, "Index out of bounds") + if let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) { + return Index(word: w, bit: v) + } + while true { + w &+= 1 + guard w < wordCount else { break } + if let v = _words[w].nthElement(&remaining) { + return Index(word: w, bit: v) + } + } + precondition(remaining == 0, "Index out of bounds") + return endIndex + } + + // distance < 0 + remaining -= 1 + var (w, b) = i.endSplit + if w < wordCount { + if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) { + return Index(word: w, bit: v) + } + } + while true { + precondition(w > 0, "Index out of bounds") + w &-= 1 + if let v = _words[w].nthElementFromEnd(&remaining) { + return Index(word: w, bit: v) + } + } + } + + @_effects(releasenone) + internal func index( + _ i: Index, offsetBy distance: Int, limitedBy limit: Index + ) -> Index? { + precondition(i <= endIndex && limit <= endIndex, "Index out of bounds") + precondition(i == endIndex || contains(i.value), "Invalid index") + guard distance != 0 else { return i } + var remaining = distance.magnitude + if distance > 0 { + guard i <= limit else { + return self.index(i, offsetBy: distance) + } + var (w, b) = i.split + if w < wordCount, + let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) + { + let r = Index(word: w, bit: v) + return r <= limit ? r : nil + } + let maxWord = Swift.min(wordCount - 1, limit.word) + while w < maxWord { + w &+= 1 + if let v = _words[w].nthElement(&remaining) { + let r = Index(word: w, bit: v) + return r <= limit ? r : nil + } + } + return remaining == 0 && limit == endIndex ? endIndex : nil + } + + // distance < 0 + guard i >= limit else { + return self.index(i, offsetBy: distance) + } + remaining &-= 1 + var (w, b) = i.endSplit + if w < wordCount { + if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) { + let r = Index(word: w, bit: v) + return r >= limit ? r : nil + } + } + let minWord = limit.word + while w > minWord { + w &-= 1 + if let v = _words[w].nthElementFromEnd(&remaining) { + let r = Index(word: w, bit: v) + return r >= limit ? r : nil + } + } + return nil + } +} +#else // !COLLECTIONS_SINGLE_MODULE +/// An unsafe-unowned bitset view over `UInt` storage, providing bit set +/// primitives. +@frozen +public struct _UnsafeBitSet { + /// An unsafe-unowned storage view. + public let _words: UnsafeBufferPointer<_Word> + +#if DEBUG + /// True when this handle does not support table mutations. + /// (This is only checked in debug builds.) + @usableFromInline + internal let _mutable: Bool +#endif + + @inlinable + @inline(__always) + public func ensureMutable() { +#if DEBUG + assert(_mutable) +#endif + } + + @inlinable + @inline(__always) + public var _mutableWords: UnsafeMutableBufferPointer<_Word> { + ensureMutable() + return UnsafeMutableBufferPointer(mutating: _words) + } + + @inlinable + @inline(__always) + public init( + words: UnsafeBufferPointer<_Word>, + mutable: Bool + ) { + assert(words.baseAddress != nil) + self._words = words +#if DEBUG + self._mutable = mutable +#endif + } + + @inlinable + @inline(__always) + public init( + words: UnsafeMutableBufferPointer<_Word>, + mutable: Bool + ) { + self.init(words: UnsafeBufferPointer(words), mutable: mutable) + } +} + +extension _UnsafeBitSet { + @inlinable + @inline(__always) + public var wordCount: Int { + _words.count + } +} + +extension _UnsafeBitSet { + @inlinable + @inline(__always) + public static func withTemporaryBitSet( + capacity: Int, + run body: (inout _UnsafeBitSet) throws -> R + ) rethrows -> R { + let wordCount = _UnsafeBitSet.wordCount(forCapacity: UInt(capacity)) + return try withTemporaryBitSet(wordCount: wordCount, run: body) + } + + @inlinable + @inline(__always) + public static func withTemporaryBitSet( + wordCount: Int, + run body: (inout Self) throws -> R + ) rethrows -> R { + var result: R? + try _withTemporaryBitSet(wordCount: wordCount) { bitset in + result = try body(&bitset) + } + return result! + } + + @inline(never) + public static func _withTemporaryBitSet( + wordCount: Int, + run body: (inout Self) throws -> Void + ) rethrows { + try _withTemporaryUninitializedBitSet(wordCount: wordCount) { handle in + handle._mutableWords.initialize(repeating: .empty) + try body(&handle) + } + } + + internal static func _withTemporaryUninitializedBitSet( + wordCount: Int, + run body: (inout Self) throws -> Void + ) rethrows { + assert(wordCount >= 0) +#if compiler(>=5.6) + return try withUnsafeTemporaryAllocation( + of: _Word.self, capacity: wordCount + ) { words in + var bitset = Self(words: words, mutable: true) + return try body(&bitset) + } +#else + if wordCount <= 2 { + var buffer: (_Word, _Word) = (.empty, .empty) + return try withUnsafeMutablePointer(to: &buffer) { p in + // Homogeneous tuples are layout-compatible with their component type. + let start = UnsafeMutableRawPointer(p) + .assumingMemoryBound(to: _Word.self) + let words = UnsafeMutableBufferPointer(start: start, count: wordCount) + var bitset = Self(words: words, mutable: true) + return try body(&bitset) + } + } + let words = UnsafeMutableBufferPointer<_Word>.allocate(capacity: wordCount) + defer { words.deallocate() } + var bitset = Self(words: words, mutable: true) + return try body(&bitset) +#endif + } +} + +extension _UnsafeBitSet { + @_effects(readnone) + @inline(__always) + public static func wordCount(forCapacity capacity: UInt) -> Int { + _Word.wordCount(forBitCount: capacity) + } + + public var capacity: UInt { + @inline(__always) + get { + UInt(wordCount &* _Word.capacity) + } + } + + @inline(__always) + internal func isWithinBounds(_ element: UInt) -> Bool { + element < capacity + } + + @inline(__always) + public func contains(_ element: UInt) -> Bool { + let (word, bit) = Index(element).split + guard word < wordCount else { return false } + return _words[word].contains(bit) + } + + @_effects(releasenone) + @discardableResult + public mutating func insert(_ element: UInt) -> Bool { + ensureMutable() + assert(isWithinBounds(element)) + let index = Index(element) + return _mutableWords[index.word].insert(index.bit) + } + + @_effects(releasenone) + @discardableResult + public mutating func remove(_ element: UInt) -> Bool { + ensureMutable() + let index = Index(element) + if index.word >= _words.count { return false } + return _mutableWords[index.word].remove(index.bit) + } + + @_effects(releasenone) + public mutating func update(_ member: UInt, to newValue: Bool) -> Bool { + ensureMutable() + let (w, b) = Index(member).split + _mutableWords[w].update(b, to: newValue) + return w == _words.count &- 1 + } + + @_effects(releasenone) + public mutating func insertAll(upTo max: UInt) { + assert(max <= capacity) + guard max > 0 else { return } + let (w, b) = Index(max).split + for i in 0 ..< w { + _mutableWords[i] = .allBits + } + if b > 0 { + _mutableWords[w].insertAll(upTo: b) + } + } + + @_alwaysEmitIntoClient + @inline(__always) + @discardableResult + public mutating func insert(_ element: Int) -> Bool { + precondition(element >= 0) + return insert(UInt(bitPattern: element)) + } + + @_alwaysEmitIntoClient + @inline(__always) + @discardableResult + public mutating func remove(_ element: Int) -> Bool { + guard element >= 0 else { return false } + return remove(UInt(bitPattern: element)) + } + + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insertAll(upTo max: Int) { + precondition(max >= 0) + return insertAll(upTo: UInt(bitPattern: max)) + } +} + +extension _UnsafeBitSet: Sequence { + public typealias Element = UInt + + @inlinable + @inline(__always) + public var underestimatedCount: Int { + count // FIXME: really? + } + + @inlinable + @inline(__always) + public func makeIterator() -> Iterator { + return Iterator(self) + } + + @frozen + public struct Iterator: IteratorProtocol { + @usableFromInline + internal let _bitset: _UnsafeBitSet + + @usableFromInline + internal var _index: Int + + @usableFromInline + internal var _word: _Word + + @inlinable + internal init(_ bitset: _UnsafeBitSet) { + self._bitset = bitset + self._index = 0 + self._word = bitset.wordCount > 0 ? bitset._words[0] : .empty + } + + @_effects(releasenone) + public mutating func next() -> UInt? { + if let bit = _word.next() { + return Index(word: _index, bit: bit).value + } + while (_index + 1) < _bitset.wordCount { + _index += 1 + _word = _bitset._words[_index] + if let bit = _word.next() { + return Index(word: _index, bit: bit).value + } + } + return nil + } + } +} + +extension _UnsafeBitSet: BidirectionalCollection { + @inlinable + @inline(__always) + public var count: Int { + _words.reduce(0) { $0 + $1.count } + } + + @inlinable + @inline(__always) + public var isEmpty: Bool { + _words.firstIndex(where: { !$0.isEmpty }) == nil + } + + @inlinable + public var startIndex: Index { + let word = _words.firstIndex { !$0.isEmpty } + guard let word = word else { return endIndex } + return Index(word: word, bit: _words[word].firstMember!) + } + + @inlinable + public var endIndex: Index { + Index(word: wordCount, bit: 0) + } + + @inlinable + public subscript(position: Index) -> UInt { + position.value + } + + @_effects(releasenone) + public func index(after index: Index) -> Index { + precondition(index < endIndex, "Index out of bounds") + var word = index.word + var w = _words[word] + w.removeAll(through: index.bit) + while w.isEmpty { + word += 1 + guard word < wordCount else { + return Index(word: wordCount, bit: 0) + } + w = _words[word] + } + return Index(word: word, bit: w.firstMember!) + } + + @_effects(releasenone) + public func index(before index: Index) -> Index { + precondition(index <= endIndex, "Index out of bounds") + var word = index.word + var w: _Word + if index.bit > 0 { + w = _words[word] + w.removeAll(from: index.bit) + } else { + w = .empty + } + while w.isEmpty { + word -= 1 + precondition(word >= 0, "Can't advance below startIndex") + w = _words[word] + } + return Index(word: word, bit: w.lastMember!) + } + + @_effects(releasenone) + public func distance(from start: Index, to end: Index) -> Int { + precondition(start <= endIndex && end <= endIndex, "Index out of bounds") + let isNegative = end < start + let (start, end) = (Swift.min(start, end), Swift.max(start, end)) + + let (w1, b1) = start.split + let (w2, b2) = end.split + + if w1 == w2 { + guard w1 < wordCount else { return 0 } + let mask = _Word(from: b1, to: b2) + let c = _words[w1].intersection(mask).count + return isNegative ? -c : c + } + + var c = 0 + var w = w1 + guard w < wordCount else { return 0 } + + c &+= _words[w].subtracting(_Word(upTo: b1)).count + w &+= 1 + while w < w2 { + c &+= _words[w].count + w &+= 1 + } + guard w < wordCount else { return isNegative ? -c : c } + c &+= _words[w].intersection(_Word(upTo: b2)).count + return isNegative ? -c : c + } + + @_effects(releasenone) + public func index(_ i: Index, offsetBy distance: Int) -> Index { + precondition(i <= endIndex, "Index out of bounds") + precondition(i == endIndex || contains(i.value), "Invalid index") + guard distance != 0 else { return i } + var remaining = distance.magnitude + if distance > 0 { + var (w, b) = i.split + precondition(w < wordCount, "Index out of bounds") + if let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) { + return Index(word: w, bit: v) + } + while true { + w &+= 1 + guard w < wordCount else { break } + if let v = _words[w].nthElement(&remaining) { + return Index(word: w, bit: v) + } + } + precondition(remaining == 0, "Index out of bounds") + return endIndex + } + + // distance < 0 + remaining -= 1 + var (w, b) = i.endSplit + if w < wordCount { + if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) { + return Index(word: w, bit: v) + } + } + while true { + precondition(w > 0, "Index out of bounds") + w &-= 1 + if let v = _words[w].nthElementFromEnd(&remaining) { + return Index(word: w, bit: v) + } + } + } + + @_effects(releasenone) + public func index( + _ i: Index, offsetBy distance: Int, limitedBy limit: Index + ) -> Index? { + precondition(i <= endIndex && limit <= endIndex, "Index out of bounds") + precondition(i == endIndex || contains(i.value), "Invalid index") + guard distance != 0 else { return i } + var remaining = distance.magnitude + if distance > 0 { + guard i <= limit else { + return self.index(i, offsetBy: distance) + } + var (w, b) = i.split + if w < wordCount, + let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) + { + let r = Index(word: w, bit: v) + return r <= limit ? r : nil + } + let maxWord = Swift.min(wordCount - 1, limit.word) + while w < maxWord { + w &+= 1 + if let v = _words[w].nthElement(&remaining) { + let r = Index(word: w, bit: v) + return r <= limit ? r : nil + } + } + return remaining == 0 && limit == endIndex ? endIndex : nil + } + + // distance < 0 + guard i >= limit else { + return self.index(i, offsetBy: distance) + } + remaining &-= 1 + var (w, b) = i.endSplit + if w < wordCount { + if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) { + let r = Index(word: w, bit: v) + return r >= limit ? r : nil + } + } + let minWord = limit.word + while w > minWord { + w &-= 1 + if let v = _words[w].nthElementFromEnd(&remaining) { + let r = Index(word: w, bit: v) + return r >= limit ? r : nil + } + } + return nil + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/UnsafeBufferPointer+Extras.swift b/Sources/_CollectionsUtilities/UnsafeBufferPointer+Extras.swift.gyb similarity index 63% rename from Sources/_CollectionsUtilities/UnsafeBufferPointer+Extras.swift rename to Sources/_CollectionsUtilities/UnsafeBufferPointer+Extras.swift.gyb index f65d2aba..9c1b6f18 100644 --- a/Sources/_CollectionsUtilities/UnsafeBufferPointer+Extras.swift +++ b/Sources/_CollectionsUtilities/UnsafeBufferPointer+Extras.swift.gyb @@ -2,18 +2,27 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension UnsafeBufferPointer { @inlinable @inline(__always) - public func _ptr(at index: Int) -> UnsafePointer { + ${modifier} func _ptr(at index: Int) -> UnsafePointer { assert(index >= 0 && index < count) return baseAddress.unsafelyUnwrapped + index } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb similarity index 94% rename from Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift rename to Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb index 8a85e59b..0f85ac4c 100644 --- a/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb @@ -2,13 +2,20 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 // //===----------------------------------------------------------------------===// +%{ + from gyb_utils import * +}% +${autogenerated_warning()} + +% for modifier in visibility_levels: +${visibility_boilerplate(modifier)} extension UnsafeMutableBufferPointer { @inlinable public func initialize(fromContentsOf source: Self) -> Index { @@ -135,3 +142,5 @@ extension Slice { target.moveInitializeAll(fromContentsOf: source) } } +% end +${visibility_boilerplate("end")} diff --git a/Sources/_CollectionsUtilities/autogenerated/Debugging.swift b/Sources/_CollectionsUtilities/autogenerated/Debugging.swift new file mode 100644 index 00000000..8ed18c5b --- /dev/null +++ b/Sources/_CollectionsUtilities/autogenerated/Debugging.swift @@ -0,0 +1,54 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +/// True if consistency checking is enabled in the implementation of the +/// Swift Collections package, false otherwise. +/// +/// Documented performance promises are null and void when this property +/// returns true -- for example, operations that are documented to take +/// O(1) time might take O(*n*) time, or worse. +@inlinable @inline(__always) +internal var _isCollectionsInternalCheckingEnabled: Bool { +#if COLLECTIONS_INTERNAL_CHECKS + return true +#else + return false +#endif +} +#else // !COLLECTIONS_SINGLE_MODULE +/// True if consistency checking is enabled in the implementation of the +/// Swift Collections package, false otherwise. +/// +/// Documented performance promises are null and void when this property +/// returns true -- for example, operations that are documented to take +/// O(1) time might take O(*n*) time, or worse. +@inlinable @inline(__always) +public var _isCollectionsInternalCheckingEnabled: Bool { +#if COLLECTIONS_INTERNAL_CHECKS + return true +#else + return false +#endif +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift b/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift new file mode 100644 index 00000000..aa800f67 --- /dev/null +++ b/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift @@ -0,0 +1,190 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE + +internal func _addressString(for pointer: UnsafeRawPointer) -> String { + let address = UInt(bitPattern: pointer) + return "0x\(String(address, radix: 16))" +} + +internal func _addressString(for object: AnyObject) -> String { + _addressString(for: Unmanaged.passUnretained(object).toOpaque()) +} + +@inlinable +internal func _addressString(for object: Unmanaged) -> String { + _addressString(for: object.toOpaque()) +} + +@inlinable +internal func _arrayDescription( + for elements: C, + debug: Bool = false, + typeName: String? = nil +) -> String { + var result = "" + if let typeName = typeName { + result += "\(typeName)(" + } + result += "[" + var first = true + for item in elements { + if first { + first = false + } else { + result += ", " + } + if debug { + debugPrint(item, terminator: "", to: &result) + } else { + print(item, terminator: "", to: &result) + } + } + result += "]" + if typeName != nil { result += ")" } + return result +} + +@inlinable +internal func _dictionaryDescription( + for elements: C, + debug: Bool = false, + typeName: String? = nil +) -> String where C.Element == (key: Key, value: Value) { + var result = "" + if let typeName = typeName { + result += "\(typeName)(" + } + + if elements.isEmpty { + result += "[:]" + } else { + result += "[" + var first = true + for (key, value) in elements { + if first { + first = false + } else { + result += ", " + } + if debug { + debugPrint(key, terminator: "", to: &result) + result += ": " + debugPrint(value, terminator: "", to: &result) + } else { + result += "\(key): \(value)" + } + } + result += "]" + } + + if typeName != nil { + result += ")" + } + return result +} +#else // !COLLECTIONS_SINGLE_MODULE + +public func _addressString(for pointer: UnsafeRawPointer) -> String { + let address = UInt(bitPattern: pointer) + return "0x\(String(address, radix: 16))" +} + +public func _addressString(for object: AnyObject) -> String { + _addressString(for: Unmanaged.passUnretained(object).toOpaque()) +} + +@inlinable +public func _addressString(for object: Unmanaged) -> String { + _addressString(for: object.toOpaque()) +} + +@inlinable +public func _arrayDescription( + for elements: C, + debug: Bool = false, + typeName: String? = nil +) -> String { + var result = "" + if let typeName = typeName { + result += "\(typeName)(" + } + result += "[" + var first = true + for item in elements { + if first { + first = false + } else { + result += ", " + } + if debug { + debugPrint(item, terminator: "", to: &result) + } else { + print(item, terminator: "", to: &result) + } + } + result += "]" + if typeName != nil { result += ")" } + return result +} + +@inlinable +public func _dictionaryDescription( + for elements: C, + debug: Bool = false, + typeName: String? = nil +) -> String where C.Element == (key: Key, value: Value) { + var result = "" + if let typeName = typeName { + result += "\(typeName)(" + } + + if elements.isEmpty { + result += "[:]" + } else { + result += "[" + var first = true + for (key, value) in elements { + if first { + first = false + } else { + result += ", " + } + if debug { + debugPrint(key, terminator: "", to: &result) + result += ": " + debugPrint(value, terminator: "", to: &result) + } else { + result += "\(key): \(value)" + } + } + result += "]" + } + + if typeName != nil { + result += ")" + } + return result +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/autogenerated/RandomAccessCollection+Offsets.swift b/Sources/_CollectionsUtilities/autogenerated/RandomAccessCollection+Offsets.swift new file mode 100644 index 00000000..248a43cf --- /dev/null +++ b/Sources/_CollectionsUtilities/autogenerated/RandomAccessCollection+Offsets.swift @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension RandomAccessCollection { + @_alwaysEmitIntoClient @inline(__always) + internal func _index(at offset: Int) -> Index { + index(startIndex, offsetBy: offset) + } + + @_alwaysEmitIntoClient @inline(__always) + internal func _offset(of index: Index) -> Int { + distance(from: startIndex, to: index) + } + + @_alwaysEmitIntoClient @inline(__always) + internal subscript(_offset offset: Int) -> Element { + self[_index(at: offset)] + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension RandomAccessCollection { + @_alwaysEmitIntoClient @inline(__always) + public func _index(at offset: Int) -> Index { + index(startIndex, offsetBy: offset) + } + + @_alwaysEmitIntoClient @inline(__always) + public func _offset(of index: Index) -> Int { + distance(from: startIndex, to: index) + } + + @_alwaysEmitIntoClient @inline(__always) + public subscript(_offset offset: Int) -> Element { + self[_index(at: offset)] + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/autogenerated/UnsafeBufferPointer+Extras.swift b/Sources/_CollectionsUtilities/autogenerated/UnsafeBufferPointer+Extras.swift new file mode 100644 index 00000000..075f1e80 --- /dev/null +++ b/Sources/_CollectionsUtilities/autogenerated/UnsafeBufferPointer+Extras.swift @@ -0,0 +1,42 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension UnsafeBufferPointer { + @inlinable + @inline(__always) + internal func _ptr(at index: Int) -> UnsafePointer { + assert(index >= 0 && index < count) + return baseAddress.unsafelyUnwrapped + index + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension UnsafeBufferPointer { + @inlinable + @inline(__always) + public func _ptr(at index: Int) -> UnsafePointer { + assert(index >= 0 && index < count) + return baseAddress.unsafelyUnwrapped + index + } +} +#endif // COLLECTIONS_SINGLE_MODULE diff --git a/Sources/_CollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift b/Sources/_CollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift new file mode 100644 index 00000000..fa6ec961 --- /dev/null +++ b/Sources/_CollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift @@ -0,0 +1,278 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 - 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 +// +//===----------------------------------------------------------------------===// + + +// ############################################################################# +// # # +// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. # +// # # +// ############################################################################# + + + +// In single module mode, we need these declarations to be internal, +// but in regular builds we want them to be public. Unfortunately +// the current best way to do this is to duplicate all definitions. +#if COLLECTIONS_SINGLE_MODULE +extension UnsafeMutableBufferPointer { + @inlinable + public func initialize(fromContentsOf source: Self) -> Index { + guard source.count > 0 else { return 0 } + precondition( + source.count <= self.count, + "buffer cannot contain every element from source.") + baseAddress.unsafelyUnwrapped.initialize( + from: source.baseAddress.unsafelyUnwrapped, + count: source.count) + return source.count + } + + @inlinable + public func initialize(fromContentsOf source: Slice) -> Index { + let sourceCount = source.count + guard sourceCount > 0 else { return 0 } + precondition( + sourceCount <= self.count, + "buffer cannot contain every element from source.") + baseAddress.unsafelyUnwrapped.initialize( + from: source.base.baseAddress.unsafelyUnwrapped + source.startIndex, + count: sourceCount) + return sourceCount + } +} + +extension Slice { + @inlinable @inline(__always) + public func initialize( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Index + where Base == UnsafeMutableBufferPointer + { + let target = UnsafeMutableBufferPointer(rebasing: self) + let i = target.initialize(fromContentsOf: source) + return self.startIndex + i + } + + @inlinable @inline(__always) + public func initialize( + fromContentsOf source: Slice> + ) -> Index + where Base == UnsafeMutableBufferPointer + { + let target = UnsafeMutableBufferPointer(rebasing: self) + let i = target.initialize(fromContentsOf: source) + return self.startIndex + i + } +} + +extension UnsafeMutableBufferPointer { + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: C + ) where C.Element == Element { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func initializeAll(fromContentsOf source: Self) { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func initializeAll(fromContentsOf source: Slice) { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func moveInitializeAll(fromContentsOf source: Self) { + let i = self.moveInitialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func moveInitializeAll(fromContentsOf source: Slice) { + let i = self.moveInitialize(fromContentsOf: source) + assert(i == self.endIndex) + } +} + +extension Slice { + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: C + ) where Base == UnsafeMutableBufferPointer { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: UnsafeMutableBufferPointer + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.initializeAll(fromContentsOf: source) + } + + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: Slice> + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.initializeAll(fromContentsOf: source) + } + + @inlinable @inline(__always) + public func moveInitializeAll( + fromContentsOf source: UnsafeMutableBufferPointer + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.moveInitializeAll(fromContentsOf: source) + } + + @inlinable @inline(__always) + public func moveInitializeAll( + fromContentsOf source: Slice> + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.moveInitializeAll(fromContentsOf: source) + } +} +#else // !COLLECTIONS_SINGLE_MODULE +extension UnsafeMutableBufferPointer { + @inlinable + public func initialize(fromContentsOf source: Self) -> Index { + guard source.count > 0 else { return 0 } + precondition( + source.count <= self.count, + "buffer cannot contain every element from source.") + baseAddress.unsafelyUnwrapped.initialize( + from: source.baseAddress.unsafelyUnwrapped, + count: source.count) + return source.count + } + + @inlinable + public func initialize(fromContentsOf source: Slice) -> Index { + let sourceCount = source.count + guard sourceCount > 0 else { return 0 } + precondition( + sourceCount <= self.count, + "buffer cannot contain every element from source.") + baseAddress.unsafelyUnwrapped.initialize( + from: source.base.baseAddress.unsafelyUnwrapped + source.startIndex, + count: sourceCount) + return sourceCount + } +} + +extension Slice { + @inlinable @inline(__always) + public func initialize( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Index + where Base == UnsafeMutableBufferPointer + { + let target = UnsafeMutableBufferPointer(rebasing: self) + let i = target.initialize(fromContentsOf: source) + return self.startIndex + i + } + + @inlinable @inline(__always) + public func initialize( + fromContentsOf source: Slice> + ) -> Index + where Base == UnsafeMutableBufferPointer + { + let target = UnsafeMutableBufferPointer(rebasing: self) + let i = target.initialize(fromContentsOf: source) + return self.startIndex + i + } +} + +extension UnsafeMutableBufferPointer { + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: C + ) where C.Element == Element { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func initializeAll(fromContentsOf source: Self) { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func initializeAll(fromContentsOf source: Slice) { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func moveInitializeAll(fromContentsOf source: Self) { + let i = self.moveInitialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func moveInitializeAll(fromContentsOf source: Slice) { + let i = self.moveInitialize(fromContentsOf: source) + assert(i == self.endIndex) + } +} + +extension Slice { + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: C + ) where Base == UnsafeMutableBufferPointer { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: UnsafeMutableBufferPointer + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.initializeAll(fromContentsOf: source) + } + + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: Slice> + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.initializeAll(fromContentsOf: source) + } + + @inlinable @inline(__always) + public func moveInitializeAll( + fromContentsOf source: UnsafeMutableBufferPointer + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.moveInitializeAll(fromContentsOf: source) + } + + @inlinable @inline(__always) + public func moveInitializeAll( + fromContentsOf source: Slice> + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.moveInitializeAll(fromContentsOf: source) + } +} +#endif // COLLECTIONS_SINGLE_MODULE From 2453c1bc23a44e0ead3bfcb6576091b335c4906d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 22 Mar 2023 20:01:23 -0700 Subject: [PATCH 087/113] Also generate @usableFromInline attributes, as needed --- Package.swift | 20 +++++- .../Descriptions.swift.gyb | 4 +- .../IntegerTricks/Integer rank.swift.gyb | 3 + .../autogenerated/Integer rank.swift | 6 ++ .../_UnsafeBitSet+Index.swift.gyb | 3 +- .../_UnsafeBitSet+_Word.swift.gyb | 24 +++---- .../UnsafeBitSet/_UnsafeBitSet.swift.gyb | 34 +++++++--- .../autogenerated/_UnsafeBitSet+Index.swift | 4 +- .../autogenerated/_UnsafeBitSet+_Word.swift | 46 +++++++------- .../autogenerated/_UnsafeBitSet.swift | 62 ++++++++++++++----- .../autogenerated/Descriptions.swift | 8 ++- 11 files changed, 152 insertions(+), 62 deletions(-) diff --git a/Package.swift b/Package.swift index 93e3430c..18fc62a9 100644 --- a/Package.swift +++ b/Package.swift @@ -97,7 +97,25 @@ registerTargets( .target( name: "_CollectionsUtilities", - exclude: ["CMakeLists.txt"], + exclude: [ + "CMakeLists.txt", + "Compatibility/Array+WithContiguousStorage Compatibility.swift.gyb", + "Compatibility/UnsafeMutableBufferPointer+SE-0370.swift.gyb", + "Compatibility/UnsafeMutablePointer+SE-0370.swift.gyb", + "Compatibility/UnsafeRawPointer extensions.swift.gyb", + "Debugging.swift.gyb", + "Descriptions.swift.gyb", + "IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift.gyb", + "IntegerTricks/Integer rank.swift.gyb", + "IntegerTricks/UInt+first and last set bit.swift.gyb", + "IntegerTricks/UInt+reversed.swift.gyb", + "RandomAccessCollection+Offsets.swift.gyb", + "UnsafeBitSet/_UnsafeBitSet+Index.swift.gyb", + "UnsafeBitSet/_UnsafeBitSet+_Word.swift.gyb", + "UnsafeBitSet/_UnsafeBitSet.swift.gyb", + "UnsafeBufferPointer+Extras.swift.gyb", + "UnsafeMutableBufferPointer+Extras.swift.gyb", + ], swiftSettings: _settings) ) diff --git a/Sources/_CollectionsUtilities/Descriptions.swift.gyb b/Sources/_CollectionsUtilities/Descriptions.swift.gyb index d665d0d5..73e10e11 100644 --- a/Sources/_CollectionsUtilities/Descriptions.swift.gyb +++ b/Sources/_CollectionsUtilities/Descriptions.swift.gyb @@ -17,16 +17,18 @@ ${autogenerated_warning()} % for modifier in visibility_levels: ${visibility_boilerplate(modifier)} +${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func _addressString(for pointer: UnsafeRawPointer) -> String { let address = UInt(bitPattern: pointer) return "0x\(String(address, radix: 16))" } +${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func _addressString(for object: AnyObject) -> String { _addressString(for: Unmanaged.passUnretained(object).toOpaque()) } -@inlinable +${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func _addressString(for object: Unmanaged) -> String { _addressString(for: object.toOpaque()) } diff --git a/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb b/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb index c0a4dc16..de75e1f7 100644 --- a/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb +++ b/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb @@ -32,6 +32,7 @@ extension FixedWidthInteger { extension UInt { @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(UInt.bitWidth == 64 || UInt.bitWidth == 32, @@ -81,6 +82,7 @@ extension UInt32 { // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) @@ -120,6 +122,7 @@ extension UInt16 { // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) diff --git a/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift index 83bc1949..02790d35 100644 --- a/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift +++ b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift @@ -38,6 +38,7 @@ extension FixedWidthInteger { extension UInt { @_effects(releasenone) + @usableFromInline internal func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(UInt.bitWidth == 64 || UInt.bitWidth == 32, @@ -87,6 +88,7 @@ extension UInt32 { // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) + @usableFromInline internal func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) @@ -126,6 +128,7 @@ extension UInt16 { // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) + @usableFromInline internal func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) @@ -172,6 +175,7 @@ extension FixedWidthInteger { extension UInt { @_effects(releasenone) + //@usableFromInline public func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(UInt.bitWidth == 64 || UInt.bitWidth == 32, @@ -221,6 +225,7 @@ extension UInt32 { // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) + //@usableFromInline public func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) @@ -260,6 +265,7 @@ extension UInt16 { // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) + //@usableFromInline public func _bit(ranked n: Int) -> UInt? { // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift.gyb b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift.gyb index 3cc4377b..c4f52e63 100644 --- a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift.gyb +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift.gyb @@ -17,11 +17,12 @@ ${autogenerated_warning()} % for modifier in visibility_levels: ${visibility_boilerplate(modifier)} extension _UnsafeBitSet { - @frozen + ${"@frozen" if modifier == "public" else "@frozen @usableFromInline"} ${modifier} struct Index: Comparable, Hashable { @usableFromInline internal typealias _Word = _UnsafeBitSet._Word + ${"@usableFromInline" if modifier != "public" else ""} ${modifier} var value: UInt @inlinable diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift.gyb b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift.gyb index 3d4d8c7d..8b9b9547 100644 --- a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift.gyb +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift.gyb @@ -18,8 +18,9 @@ ${autogenerated_warning()} % for modifier in visibility_levels: ${visibility_boilerplate(modifier)} extension _UnsafeBitSet { - @frozen + ${"@frozen" if modifier == "public" else "@frozen @usableFromInline"} ${modifier} struct _Word { + ${"@usableFromInline" if modifier != "public" else ""} ${modifier} var value: UInt @inlinable @@ -45,6 +46,7 @@ extension _UnsafeBitSet { } extension _UnsafeBitSet._Word: CustomStringConvertible { + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} var description: String { String(value, radix: 16) } @@ -257,52 +259,52 @@ extension _UnsafeBitSet._Word: Hashable { } extension _UnsafeBitSet._Word { - @inline(__always) + @inlinable @inline(__always) ${modifier} func complement() -> Self { Self(~self.value) } - @inline(__always) + @inlinable @inline(__always) ${modifier} mutating func formComplement() { self.value = ~self.value } - @inline(__always) + @inlinable @inline(__always) ${modifier} func union(_ other: Self) -> Self { Self(self.value | other.value) } - @inline(__always) + @inlinable @inline(__always) ${modifier} mutating func formUnion(_ other: Self) { self.value |= other.value } - @inline(__always) + @inlinable @inline(__always) ${modifier} func intersection(_ other: Self) -> Self { Self(self.value & other.value) } - @inline(__always) + @inlinable @inline(__always) ${modifier} mutating func formIntersection(_ other: Self) { self.value &= other.value } - @inline(__always) + @inlinable @inline(__always) ${modifier} func symmetricDifference(_ other: Self) -> Self { Self(self.value ^ other.value) } - @inline(__always) + @inlinable @inline(__always) ${modifier} mutating func formSymmetricDifference(_ other: Self) { self.value ^= other.value } - @inline(__always) + @inlinable @inline(__always) ${modifier} func subtracting(_ other: Self) -> Self { Self(self.value & ~other.value) } - @inline(__always) + @inlinable @inline(__always) ${modifier} mutating func subtract(_ other: Self) { self.value &= ~other.value } diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift.gyb b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift.gyb index 79dc9dc2..1c9d12f7 100644 --- a/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift.gyb +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift.gyb @@ -18,9 +18,10 @@ ${autogenerated_warning()} ${visibility_boilerplate(modifier)} /// An unsafe-unowned bitset view over `UInt` storage, providing bit set /// primitives. -@frozen +${"@frozen" if modifier == "public" else "@frozen @usableFromInline"} ${modifier} struct _UnsafeBitSet { /// An unsafe-unowned storage view. + ${"@usableFromInline" if modifier != "public" else ""} ${modifier} let _words: UnsafeBufferPointer<_Word> #if DEBUG @@ -101,7 +102,8 @@ extension _UnsafeBitSet { } @inline(never) - ${modifier} static func _withTemporaryBitSet( + @usableFromInline + internal static func _withTemporaryBitSet( wordCount: Int, run body: (inout Self) throws -> Void ) rethrows { @@ -145,24 +147,24 @@ extension _UnsafeBitSet { extension _UnsafeBitSet { @_effects(readnone) - @inline(__always) + @inlinable @inline(__always) ${modifier} static func wordCount(forCapacity capacity: UInt) -> Int { _Word.wordCount(forBitCount: capacity) } + @inlinable @inline(__always) ${modifier} var capacity: UInt { - @inline(__always) - get { - UInt(wordCount &* _Word.capacity) - } + UInt(wordCount &* _Word.capacity) } - @inline(__always) + @inlinable @inline(__always) internal func isWithinBounds(_ element: UInt) -> Bool { element < capacity } + @_effects(releasenone) @inline(__always) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func contains(_ element: UInt) -> Bool { let (word, bit) = Index(element).split guard word < wordCount else { return false } @@ -170,6 +172,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } @discardableResult ${modifier} mutating func insert(_ element: UInt) -> Bool { ensureMutable() @@ -179,6 +182,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } @discardableResult ${modifier} mutating func remove(_ element: UInt) -> Bool { ensureMutable() @@ -188,6 +192,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} mutating func update(_ member: UInt, to newValue: Bool) -> Bool { ensureMutable() let (w, b) = Index(member).split @@ -196,6 +201,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} mutating func insertAll(upTo max: UInt) { assert(max <= capacity) guard max > 0 else { return } @@ -209,6 +215,7 @@ extension _UnsafeBitSet { } @_alwaysEmitIntoClient + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } @inline(__always) @discardableResult ${modifier} mutating func insert(_ element: Int) -> Bool { @@ -217,6 +224,7 @@ extension _UnsafeBitSet { } @_alwaysEmitIntoClient + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } @inline(__always) @discardableResult ${modifier} mutating func remove(_ element: Int) -> Bool { @@ -225,6 +233,7 @@ extension _UnsafeBitSet { } @_alwaysEmitIntoClient + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } @inline(__always) ${modifier} mutating func insertAll(upTo max: Int) { precondition(max >= 0) @@ -233,6 +242,7 @@ extension _UnsafeBitSet { } extension _UnsafeBitSet: Sequence { + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} typealias Element = UInt @inlinable @@ -247,7 +257,7 @@ extension _UnsafeBitSet: Sequence { return Iterator(self) } - @frozen + ${"@frozen" if modifier == "public" else "@usableFromInline @frozen"} ${modifier} struct Iterator: IteratorProtocol { @usableFromInline internal let _bitset: _UnsafeBitSet @@ -266,6 +276,7 @@ extension _UnsafeBitSet: Sequence { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} mutating func next() -> UInt? { if let bit = _word.next() { return Index(word: _index, bit: bit).value @@ -313,6 +324,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func index(after index: Index) -> Index { precondition(index < endIndex, "Index out of bounds") var word = index.word @@ -329,6 +341,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func index(before index: Index) -> Index { precondition(index <= endIndex, "Index out of bounds") var word = index.word @@ -348,6 +361,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func distance(from start: Index, to end: Index) -> Int { precondition(start <= endIndex && end <= endIndex, "Index out of bounds") let isNegative = end < start @@ -379,6 +393,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i <= endIndex, "Index out of bounds") precondition(i == endIndex || contains(i.value), "Invalid index") @@ -419,6 +434,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + ${"@usableFromInline" if modifier != "public" else "//@usableFromInline" } ${modifier} func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+Index.swift b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+Index.swift index 56238831..529fe7e5 100644 --- a/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+Index.swift +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+Index.swift @@ -23,11 +23,12 @@ // the current best way to do this is to duplicate all definitions. #if COLLECTIONS_SINGLE_MODULE extension _UnsafeBitSet { - @frozen + @frozen @usableFromInline internal struct Index: Comparable, Hashable { @usableFromInline internal typealias _Word = _UnsafeBitSet._Word + @usableFromInline internal var value: UInt @inlinable @@ -107,6 +108,7 @@ extension _UnsafeBitSet { @usableFromInline internal typealias _Word = _UnsafeBitSet._Word + public var value: UInt @inlinable diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+_Word.swift b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+_Word.swift index 80dfec86..bba3891d 100644 --- a/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+_Word.swift +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet+_Word.swift @@ -24,8 +24,9 @@ // the current best way to do this is to duplicate all definitions. #if COLLECTIONS_SINGLE_MODULE extension _UnsafeBitSet { - @frozen + @frozen @usableFromInline internal struct _Word { + @usableFromInline internal var value: UInt @inlinable @@ -51,6 +52,7 @@ extension _UnsafeBitSet { } extension _UnsafeBitSet._Word: CustomStringConvertible { + @usableFromInline internal var description: String { String(value, radix: 16) } @@ -263,52 +265,52 @@ extension _UnsafeBitSet._Word: Hashable { } extension _UnsafeBitSet._Word { - @inline(__always) + @inlinable @inline(__always) internal func complement() -> Self { Self(~self.value) } - @inline(__always) + @inlinable @inline(__always) internal mutating func formComplement() { self.value = ~self.value } - @inline(__always) + @inlinable @inline(__always) internal func union(_ other: Self) -> Self { Self(self.value | other.value) } - @inline(__always) + @inlinable @inline(__always) internal mutating func formUnion(_ other: Self) { self.value |= other.value } - @inline(__always) + @inlinable @inline(__always) internal func intersection(_ other: Self) -> Self { Self(self.value & other.value) } - @inline(__always) + @inlinable @inline(__always) internal mutating func formIntersection(_ other: Self) { self.value &= other.value } - @inline(__always) + @inlinable @inline(__always) internal func symmetricDifference(_ other: Self) -> Self { Self(self.value ^ other.value) } - @inline(__always) + @inlinable @inline(__always) internal mutating func formSymmetricDifference(_ other: Self) { self.value ^= other.value } - @inline(__always) + @inlinable @inline(__always) internal func subtracting(_ other: Self) -> Self { Self(self.value & ~other.value) } - @inline(__always) + @inlinable @inline(__always) internal mutating func subtract(_ other: Self) { self.value &= ~other.value } @@ -333,6 +335,7 @@ extension _UnsafeBitSet._Word { extension _UnsafeBitSet { @frozen public struct _Word { + public var value: UInt @inlinable @@ -358,6 +361,7 @@ extension _UnsafeBitSet { } extension _UnsafeBitSet._Word: CustomStringConvertible { + //@usableFromInline public var description: String { String(value, radix: 16) } @@ -570,52 +574,52 @@ extension _UnsafeBitSet._Word: Hashable { } extension _UnsafeBitSet._Word { - @inline(__always) + @inlinable @inline(__always) public func complement() -> Self { Self(~self.value) } - @inline(__always) + @inlinable @inline(__always) public mutating func formComplement() { self.value = ~self.value } - @inline(__always) + @inlinable @inline(__always) public func union(_ other: Self) -> Self { Self(self.value | other.value) } - @inline(__always) + @inlinable @inline(__always) public mutating func formUnion(_ other: Self) { self.value |= other.value } - @inline(__always) + @inlinable @inline(__always) public func intersection(_ other: Self) -> Self { Self(self.value & other.value) } - @inline(__always) + @inlinable @inline(__always) public mutating func formIntersection(_ other: Self) { self.value &= other.value } - @inline(__always) + @inlinable @inline(__always) public func symmetricDifference(_ other: Self) -> Self { Self(self.value ^ other.value) } - @inline(__always) + @inlinable @inline(__always) public mutating func formSymmetricDifference(_ other: Self) { self.value ^= other.value } - @inline(__always) + @inlinable @inline(__always) public func subtracting(_ other: Self) -> Self { Self(self.value & ~other.value) } - @inline(__always) + @inlinable @inline(__always) public mutating func subtract(_ other: Self) { self.value &= ~other.value } diff --git a/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet.swift b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet.swift index e3c11a6b..eaf6dee2 100644 --- a/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet.swift +++ b/Sources/_CollectionsUtilities/UnsafeBitSet/autogenerated/_UnsafeBitSet.swift @@ -24,9 +24,10 @@ #if COLLECTIONS_SINGLE_MODULE /// An unsafe-unowned bitset view over `UInt` storage, providing bit set /// primitives. -@frozen +@frozen @usableFromInline internal struct _UnsafeBitSet { /// An unsafe-unowned storage view. + @usableFromInline internal let _words: UnsafeBufferPointer<_Word> #if DEBUG @@ -107,6 +108,7 @@ extension _UnsafeBitSet { } @inline(never) + @usableFromInline internal static func _withTemporaryBitSet( wordCount: Int, run body: (inout Self) throws -> Void @@ -151,24 +153,24 @@ extension _UnsafeBitSet { extension _UnsafeBitSet { @_effects(readnone) - @inline(__always) + @inlinable @inline(__always) internal static func wordCount(forCapacity capacity: UInt) -> Int { _Word.wordCount(forBitCount: capacity) } + @inlinable @inline(__always) internal var capacity: UInt { - @inline(__always) - get { - UInt(wordCount &* _Word.capacity) - } + UInt(wordCount &* _Word.capacity) } - @inline(__always) + @inlinable @inline(__always) internal func isWithinBounds(_ element: UInt) -> Bool { element < capacity } + @_effects(releasenone) @inline(__always) + @usableFromInline internal func contains(_ element: UInt) -> Bool { let (word, bit) = Index(element).split guard word < wordCount else { return false } @@ -176,6 +178,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + @usableFromInline @discardableResult internal mutating func insert(_ element: UInt) -> Bool { ensureMutable() @@ -185,6 +188,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + @usableFromInline @discardableResult internal mutating func remove(_ element: UInt) -> Bool { ensureMutable() @@ -194,6 +198,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + @usableFromInline internal mutating func update(_ member: UInt, to newValue: Bool) -> Bool { ensureMutable() let (w, b) = Index(member).split @@ -202,6 +207,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + @usableFromInline internal mutating func insertAll(upTo max: UInt) { assert(max <= capacity) guard max > 0 else { return } @@ -215,6 +221,7 @@ extension _UnsafeBitSet { } @_alwaysEmitIntoClient + @usableFromInline @inline(__always) @discardableResult internal mutating func insert(_ element: Int) -> Bool { @@ -223,6 +230,7 @@ extension _UnsafeBitSet { } @_alwaysEmitIntoClient + @usableFromInline @inline(__always) @discardableResult internal mutating func remove(_ element: Int) -> Bool { @@ -231,6 +239,7 @@ extension _UnsafeBitSet { } @_alwaysEmitIntoClient + @usableFromInline @inline(__always) internal mutating func insertAll(upTo max: Int) { precondition(max >= 0) @@ -239,6 +248,7 @@ extension _UnsafeBitSet { } extension _UnsafeBitSet: Sequence { + @usableFromInline internal typealias Element = UInt @inlinable @@ -253,7 +263,7 @@ extension _UnsafeBitSet: Sequence { return Iterator(self) } - @frozen + @usableFromInline @frozen internal struct Iterator: IteratorProtocol { @usableFromInline internal let _bitset: _UnsafeBitSet @@ -272,6 +282,7 @@ extension _UnsafeBitSet: Sequence { } @_effects(releasenone) + @usableFromInline internal mutating func next() -> UInt? { if let bit = _word.next() { return Index(word: _index, bit: bit).value @@ -319,6 +330,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + @usableFromInline internal func index(after index: Index) -> Index { precondition(index < endIndex, "Index out of bounds") var word = index.word @@ -335,6 +347,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + @usableFromInline internal func index(before index: Index) -> Index { precondition(index <= endIndex, "Index out of bounds") var word = index.word @@ -354,6 +367,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + @usableFromInline internal func distance(from start: Index, to end: Index) -> Int { precondition(start <= endIndex && end <= endIndex, "Index out of bounds") let isNegative = end < start @@ -385,6 +399,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + @usableFromInline internal func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i <= endIndex, "Index out of bounds") precondition(i == endIndex || contains(i.value), "Invalid index") @@ -425,6 +440,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + @usableFromInline internal func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { @@ -483,6 +499,7 @@ extension _UnsafeBitSet: BidirectionalCollection { @frozen public struct _UnsafeBitSet { /// An unsafe-unowned storage view. + public let _words: UnsafeBufferPointer<_Word> #if DEBUG @@ -563,7 +580,8 @@ extension _UnsafeBitSet { } @inline(never) - public static func _withTemporaryBitSet( + @usableFromInline + internal static func _withTemporaryBitSet( wordCount: Int, run body: (inout Self) throws -> Void ) rethrows { @@ -607,24 +625,24 @@ extension _UnsafeBitSet { extension _UnsafeBitSet { @_effects(readnone) - @inline(__always) + @inlinable @inline(__always) public static func wordCount(forCapacity capacity: UInt) -> Int { _Word.wordCount(forBitCount: capacity) } + @inlinable @inline(__always) public var capacity: UInt { - @inline(__always) - get { - UInt(wordCount &* _Word.capacity) - } + UInt(wordCount &* _Word.capacity) } - @inline(__always) + @inlinable @inline(__always) internal func isWithinBounds(_ element: UInt) -> Bool { element < capacity } + @_effects(releasenone) @inline(__always) + //@usableFromInline public func contains(_ element: UInt) -> Bool { let (word, bit) = Index(element).split guard word < wordCount else { return false } @@ -632,6 +650,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + //@usableFromInline @discardableResult public mutating func insert(_ element: UInt) -> Bool { ensureMutable() @@ -641,6 +660,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + //@usableFromInline @discardableResult public mutating func remove(_ element: UInt) -> Bool { ensureMutable() @@ -650,6 +670,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + //@usableFromInline public mutating func update(_ member: UInt, to newValue: Bool) -> Bool { ensureMutable() let (w, b) = Index(member).split @@ -658,6 +679,7 @@ extension _UnsafeBitSet { } @_effects(releasenone) + //@usableFromInline public mutating func insertAll(upTo max: UInt) { assert(max <= capacity) guard max > 0 else { return } @@ -671,6 +693,7 @@ extension _UnsafeBitSet { } @_alwaysEmitIntoClient + //@usableFromInline @inline(__always) @discardableResult public mutating func insert(_ element: Int) -> Bool { @@ -679,6 +702,7 @@ extension _UnsafeBitSet { } @_alwaysEmitIntoClient + //@usableFromInline @inline(__always) @discardableResult public mutating func remove(_ element: Int) -> Bool { @@ -687,6 +711,7 @@ extension _UnsafeBitSet { } @_alwaysEmitIntoClient + //@usableFromInline @inline(__always) public mutating func insertAll(upTo max: Int) { precondition(max >= 0) @@ -695,6 +720,7 @@ extension _UnsafeBitSet { } extension _UnsafeBitSet: Sequence { + //@usableFromInline public typealias Element = UInt @inlinable @@ -728,6 +754,7 @@ extension _UnsafeBitSet: Sequence { } @_effects(releasenone) + //@usableFromInline public mutating func next() -> UInt? { if let bit = _word.next() { return Index(word: _index, bit: bit).value @@ -775,6 +802,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + //@usableFromInline public func index(after index: Index) -> Index { precondition(index < endIndex, "Index out of bounds") var word = index.word @@ -791,6 +819,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + //@usableFromInline public func index(before index: Index) -> Index { precondition(index <= endIndex, "Index out of bounds") var word = index.word @@ -810,6 +839,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + //@usableFromInline public func distance(from start: Index, to end: Index) -> Int { precondition(start <= endIndex && end <= endIndex, "Index out of bounds") let isNegative = end < start @@ -841,6 +871,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + //@usableFromInline public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i <= endIndex, "Index out of bounds") precondition(i == endIndex || contains(i.value), "Invalid index") @@ -881,6 +912,7 @@ extension _UnsafeBitSet: BidirectionalCollection { } @_effects(releasenone) + //@usableFromInline public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { diff --git a/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift b/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift index aa800f67..93bdbe93 100644 --- a/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift +++ b/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift @@ -23,16 +23,18 @@ // the current best way to do this is to duplicate all definitions. #if COLLECTIONS_SINGLE_MODULE +@usableFromInline internal func _addressString(for pointer: UnsafeRawPointer) -> String { let address = UInt(bitPattern: pointer) return "0x\(String(address, radix: 16))" } +@usableFromInline internal func _addressString(for object: AnyObject) -> String { _addressString(for: Unmanaged.passUnretained(object).toOpaque()) } -@inlinable +@usableFromInline internal func _addressString(for object: Unmanaged) -> String { _addressString(for: object.toOpaque()) } @@ -106,16 +108,18 @@ internal func _dictionaryDescription( } #else // !COLLECTIONS_SINGLE_MODULE +//@usableFromInline public func _addressString(for pointer: UnsafeRawPointer) -> String { let address = UInt(bitPattern: pointer) return "0x\(String(address, radix: 16))" } +//@usableFromInline public func _addressString(for object: AnyObject) -> String { _addressString(for: Unmanaged.passUnretained(object).toOpaque()) } -@inlinable +//@usableFromInline public func _addressString(for object: Unmanaged) -> String { _addressString(for: object.toOpaque()) } From f17cf642c1eb200f46c0535b9300a53503c1a7e5 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 22 Mar 2023 21:44:23 -0700 Subject: [PATCH 088/113] Add support building with COLLECTIONS_SINGLE_MODULE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Sources/_CollectionsTestSupport → Tests/_CollectionsTestSupport - Refactor Package.swift to allow switching between the default polymodule and the new monomodule product configurations (by editing the manifest file). - Fix build errors in the monomodule variant. --- Package.swift | 301 ++++++++++++------ Sources/Collections/Collections.swift | 3 +- .../UtilitiesTests.swift | 8 +- Tests/HeapTests/HeapNodeTests.swift | 2 +- .../HashTable/HashTableTests.swift | 8 +- .../RandomAccessCollection+Extras.swift | 15 + .../AssertionContexts/Assertions.swift | 0 .../CollectionTestCase.swift | 0 .../AssertionContexts/Combinatorics.swift | 0 .../AssertionContexts/TestContext.swift | 0 .../CheckBidirectionalCollection.swift | 0 .../ConformanceCheckers/CheckCollection.swift | 0 .../ConformanceCheckers/CheckComparable.swift | 0 .../ConformanceCheckers/CheckEquatable.swift | 0 .../ConformanceCheckers/CheckHashable.swift | 0 .../ConformanceCheckers/CheckSequence.swift | 0 .../MinimalBidirectionalCollection.swift | 0 .../MinimalTypes/MinimalCollection.swift | 0 .../MinimalTypes/MinimalDecoder.swift | 0 .../MinimalTypes/MinimalEncoder.swift | 0 .../MinimalTypes/MinimalIndex.swift | 0 .../MinimalTypes/MinimalIterator.swift | 0 ...MinimalMutableRandomAccessCollection.swift | 0 ...ngeReplaceableRandomAccessCollection.swift | 0 .../MinimalRandomAccessCollection.swift | 0 ...ngeReplaceableRandomAccessCollection.swift | 0 .../MinimalTypes/MinimalSequence.swift | 0 .../MinimalTypes/ResettableValue.swift | 0 .../MinimalTypes/_CollectionState.swift | 0 .../MinimalTypes/_MinimalCollectionCore.swift | 0 .../AllOnesRandomNumberGenerator.swift | 0 .../Utilities/Box.swift | 0 .../Utilities/DictionaryAPIChecker.swift | 0 .../Utilities/HashableBox.swift | 0 .../Utilities/IndexRangeCollection.swift | 0 .../Utilities/Integer Square Root.swift | 0 .../Utilities/LifetimeTracked.swift | 0 .../Utilities/LifetimeTracker.swift | 0 .../Utilities/RandomStableSample.swift | 0 .../RepeatableRandomNumberGenerator.swift | 0 .../Utilities/SetAPIChecker.swift | 0 .../SortedCollectionAPIChecker.swift | 4 +- .../Utilities/StringConvertibleValue.swift | 0 43 files changed, 231 insertions(+), 110 deletions(-) rename {Sources => Tests}/_CollectionsTestSupport/AssertionContexts/Assertions.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/AssertionContexts/TestContext.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalIndex.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalIterator.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/ResettableValue.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/_CollectionState.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/AllOnesRandomNumberGenerator.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/Box.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/HashableBox.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/Integer Square Root.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/LifetimeTracked.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/LifetimeTracker.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/RandomStableSample.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/RepeatableRandomNumberGenerator.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/SetAPIChecker.swift (100%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift (95%) rename {Sources => Tests}/_CollectionsTestSupport/Utilities/StringConvertibleValue.swift (100%) diff --git a/Package.swift b/Package.swift index 18fc62a9..3aefbde9 100644 --- a/Package.swift +++ b/Package.swift @@ -48,54 +48,144 @@ var defines: [String] = [ // Enable modules that aren't source stable yet, and aren't ready for general use. // "COLLECTIONS_ENABLE_UNSTABLE_MODULES", - // Enable this to allow building the sources as a single, large module. - // Note: this setting isn't a supported package configuration, but it's listed - // here for completeness. -// "COLLECTIONS_SINGLE_MODULE", + // Enable this to build the sources as a single, large module. + // This removes the distinct modules for each data structure, instead + // putting them all directly into the `Collections` module. + // Note: This is a source-incompatible variation of the default configuration. + "COLLECTIONS_SINGLE_MODULE", ] -var _modules: [String] = [] -var _products: [Product] = [] -var _targets: [Target] = [] var _settings: [SwiftSetting] = defines.map { .define($0) } -func registerTargets(_ targets: [Target]) { - _targets.append(contentsOf: targets) -} -func registerTargets(_ targets: Target...) { registerTargets(targets) } +struct CustomTarget { + enum Kind { + case exported + case hidden + case test + case testSupport + } -func registerLibrary(_ module: String, _ targets: [Target]) { - _modules.append(module) - _products.append(.library(name: module, targets: [module])) - registerTargets(targets) -} -func registerLibrary(_ module: String, _ targets: Target...) { - registerLibrary(module, targets) + var kind: Kind + var name: String + var dependencies: [Target.Dependency] + var directory: String + var exclude: [String] } -func registerUnstableLibrary(_ module: String, _ targets: Target...) { - if defines.contains("COLLECTIONS_ENABLE_UNSTABLE_MODULES") { - registerLibrary(module, targets) +extension CustomTarget.Kind { + func path(for name: String) -> String { + switch self { + case .exported, .hidden: return "Sources/\(name)" + case .test, .testSupport: return "Tests/\(name)" + } + } + + var isTest: Bool { + switch self { + case .exported, .hidden: return false + case .test, .testSupport: return true + } } } -registerTargets( - .target( - name: "_CollectionsTestSupport", - dependencies: ["_CollectionsUtilities"], - swiftSettings: _settings, - linkerSettings: [ - .linkedFramework( - "XCTest", - .when(platforms: [.macOS, .iOS, .watchOS, .tvOS])), - ] - ), - .testTarget( - name: "CollectionsTestSupportTests", - dependencies: ["_CollectionsTestSupport"], - swiftSettings: _settings), +extension CustomTarget { + static func target( + kind: Kind, + name: String, + dependencies: [Target.Dependency] = [], + directory: String? = nil, + exclude: [String] = [] + ) -> CustomTarget { + CustomTarget( + kind: kind, + name: name, + dependencies: dependencies, + directory: directory ?? name, + exclude: exclude) + } + func toTarget() -> Target { + var linkerSettings: [LinkerSetting] = [] + if kind == .testSupport { + linkerSettings.append( + .linkedFramework("XCTest", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS]))) + } + switch kind { + case .exported, .hidden, .testSupport: + return Target.target( + name: name, + dependencies: dependencies, + path: kind.path(for: directory), + exclude: exclude, + swiftSettings: _settings, + linkerSettings: linkerSettings) + case .test: + return Target.testTarget( + name: name, + dependencies: dependencies, + path: kind.path(for: directory), + exclude: exclude, + swiftSettings: _settings, + linkerSettings: linkerSettings) + } + } +} + +extension Array where Element == CustomTarget { + func toMonolithicTarget( + name: String, + linkerSettings: [LinkerSetting] = [] + ) -> Target { + let targets = self.filter { !$0.kind.isTest } + return Target.target( + name: name, + path: "Sources", + exclude: [ + "CMakeLists.txt", + "BitCollections/BitCollections.docc", + "Collections/Collections.docc", + "DequeModule/DequeModule.docc", + "HashTreeCollections/HashTreeCollections.docc", + "HeapModule/HeapModule.docc", + "OrderedCollections/OrderedCollections.docc", + ] + targets.flatMap { t in + t.exclude.map { "\(t.name)/\($0)" } + }, + sources: targets.map { "\($0.directory)" }, + swiftSettings: _settings, + linkerSettings: linkerSettings) + } + + func toMonolithicTestTarget( + name: String, + dependencies: [Target.Dependency] = [], + linkerSettings: [LinkerSetting] = [] + ) -> Target { + let targets = self.filter { $0.kind.isTest } + return Target.testTarget( + name: name, + dependencies: dependencies, + path: "Tests", + exclude: targets.flatMap { t in + t.exclude.map { "\(t.name)/\($0)" } + }, + sources: targets.map { "\($0.name)" }, + swiftSettings: _settings, + linkerSettings: linkerSettings) + } +} + +let targets: [CustomTarget] = [ .target( + kind: .testSupport, + name: "_CollectionsTestSupport", + dependencies: ["_CollectionsUtilities"]), + .target( + kind: .test, + name: "CollectionsTestSupportTests", + dependencies: ["_CollectionsTestSupport"]), + .target( + kind: .hidden, name: "_CollectionsUtilities", exclude: [ "CMakeLists.txt", @@ -115,98 +205,103 @@ registerTargets( "UnsafeBitSet/_UnsafeBitSet.swift.gyb", "UnsafeBufferPointer+Extras.swift.gyb", "UnsafeMutableBufferPointer+Extras.swift.gyb", - ], - swiftSettings: _settings) -) + ]), -registerLibrary( - "BitCollections", .target( + kind: .exported, name: "BitCollections", dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: _settings), - .testTarget( + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, name: "BitCollectionsTests", dependencies: [ "BitCollections", "_CollectionsTestSupport", "OrderedCollections" - ], - swiftSettings: _settings) -) + ]), -registerLibrary( - "DequeModule", .target( + kind: .exported, name: "DequeModule", dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: _settings), - .testTarget( - name: "DequeTests", - dependencies: ["DequeModule", "_CollectionsTestSupport"], - swiftSettings: _settings) -) - -registerLibrary( - "HashTreeCollections", + exclude: ["CMakeLists.txt"]), .target( + kind: .test, + name: "DequeTests", + dependencies: ["DequeModule", "_CollectionsTestSupport"]), + + .target( + kind: .exported, name: "HashTreeCollections", dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: _settings), - .testTarget( - name: "HashTreeCollectionsTests", - dependencies: ["HashTreeCollections", "_CollectionsTestSupport"], - swiftSettings: _settings) -) - -registerLibrary( - "HeapModule", + exclude: ["CMakeLists.txt"]), .target( + kind: .test, + name: "HashTreeCollectionsTests", + dependencies: ["HashTreeCollections", "_CollectionsTestSupport"]), + + .target( + kind: .exported, name: "HeapModule", dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: _settings), - .testTarget( - name: "HeapTests", - dependencies: ["HeapModule", "_CollectionsTestSupport"], - swiftSettings: _settings) -) - -registerLibrary( - "OrderedCollections", + exclude: ["CMakeLists.txt"]), .target( + kind: .test, + name: "HeapTests", + dependencies: ["HeapModule", "_CollectionsTestSupport"]), + + .target( + kind: .exported, name: "OrderedCollections", dependencies: ["_CollectionsUtilities"], - exclude: ["CMakeLists.txt"], - swiftSettings: _settings), - .testTarget( - name: "OrderedCollectionsTests", - dependencies: ["OrderedCollections", "_CollectionsTestSupport"], - swiftSettings: _settings) -) - -registerLibrary( - "_RopeModule", + exclude: ["CMakeLists.txt"]), .target( + kind: .test, + name: "OrderedCollectionsTests", + dependencies: ["OrderedCollections", "_CollectionsTestSupport"]), + + .target( + kind: .exported, name: "_RopeModule", dependencies: ["_CollectionsUtilities"], - path: "Sources/RopeModule", - swiftSettings: _settings), - .testTarget( - name: "RopeModuleTests", - dependencies: ["_RopeModule", "_CollectionsTestSupport"], - swiftSettings: _settings) -) - -registerLibrary( - "Collections", + directory: "RopeModule"), .target( + kind: .test, + name: "RopeModuleTests", + dependencies: ["_RopeModule", "_CollectionsTestSupport"]), + + .target( + kind: .exported, name: "Collections", - dependencies: _modules.map { .target(name: $0) }, - exclude: ["CMakeLists.txt"], - swiftSettings: _settings) -) + dependencies: [ + "BitCollections", + "DequeModule", + "HashTreeCollections", + "HeapModule", + "OrderedCollections", + "_RopeModule", + ], + exclude: ["CMakeLists.txt"]) +] + +var _products: [Product] = [] +var _targets: [Target] = [] +if defines.contains("COLLECTIONS_SINGLE_MODULE") { + _products = [ + .library(name: "Collections", targets: ["Collections"]), + ] + _targets = [ + targets.toMonolithicTarget(name: "Collections"), + targets.toMonolithicTestTarget( + name: "CollectionsTests", + dependencies: ["Collections"]), + ] +} else { + _products = targets.compactMap { t in + guard t.kind == .exported else { return nil } + return .library(name: t.name, targets: [t.name]) + } + _targets = targets.map { $0.toTarget() } +} let package = Package( name: "swift-collections", diff --git a/Sources/Collections/Collections.swift b/Sources/Collections/Collections.swift index b500a766..8e6a9c29 100644 --- a/Sources/Collections/Collections.swift +++ b/Sources/Collections/Collections.swift @@ -9,10 +9,11 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE @_exported import BitCollections @_exported import DequeModule @_exported import HashTreeCollections @_exported import HeapModule @_exported import OrderedCollections - //@_exported import _RopeModule +#endif diff --git a/Tests/CollectionsTestSupportTests/UtilitiesTests.swift b/Tests/CollectionsTestSupportTests/UtilitiesTests.swift index 86ae1e9b..b0038980 100644 --- a/Tests/CollectionsTestSupportTests/UtilitiesTests.swift +++ b/Tests/CollectionsTestSupportTests/UtilitiesTests.swift @@ -9,10 +9,13 @@ // //===----------------------------------------------------------------------===// -#if DEBUG import XCTest -@testable import _CollectionsTestSupport +#if !COLLECTIONS_SINGLE_MODULE && DEBUG +@testable import _CollectionsTestSupport +#endif + +#if COLLECTIONS_SINGLE_MODULE || DEBUG final class UtilitiesTests: CollectionTestCase { func testIntegerSquareRoot() { withSome("i", in: 0 ..< Int.max, maxSamples: 100_000) { i in @@ -22,5 +25,4 @@ final class UtilitiesTests: CollectionTestCase { } } } - #endif diff --git a/Tests/HeapTests/HeapNodeTests.swift b/Tests/HeapTests/HeapNodeTests.swift index 9380ae38..29bf0a1b 100644 --- a/Tests/HeapTests/HeapNodeTests.swift +++ b/Tests/HeapTests/HeapNodeTests.swift @@ -12,7 +12,7 @@ #if DEBUG // These unit tests need access to HeapModule internals import XCTest #if COLLECTIONS_SINGLE_MODULE -import Collections +@testable import Collections #else @testable import HeapModule #endif diff --git a/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift b/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift index e3289a5b..0e51b013 100644 --- a/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift +++ b/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift @@ -9,10 +9,16 @@ // //===----------------------------------------------------------------------===// -#if DEBUG // These unit tests need access to OrderedSet internals import XCTest + +#if DEBUG // These unit tests use internal decls + +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) @testable import Collections +#else import _CollectionsTestSupport @_spi(Testing) @testable import OrderedCollections +#endif class HashTableTests: CollectionTestCase { typealias Bucket = _HashTable.Bucket diff --git a/Tests/OrderedCollectionsTests/OrderedSet/RandomAccessCollection+Extras.swift b/Tests/OrderedCollectionsTests/OrderedSet/RandomAccessCollection+Extras.swift index d6c51e9a..fd6bcb2b 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/RandomAccessCollection+Extras.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/RandomAccessCollection+Extras.swift @@ -14,6 +14,21 @@ import _CollectionsUtilities #endif extension RandomAccessCollection { + @inline(__always) + internal func _index(at offset: Int) -> Index { + index(startIndex, offsetBy: offset) + } + + @inline(__always) + internal func _offset(of index: Index) -> Int { + distance(from: startIndex, to: index) + } + + @inline(__always) + internal subscript(_offset offset: Int) -> Element { + self[_index(at: offset)] + } + @inline(__always) internal func _indexRange(at offsets: Range) -> Range { _index(at: offsets.lowerBound) ..< _index(at: offsets.upperBound) diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift similarity index 100% rename from Sources/_CollectionsTestSupport/AssertionContexts/Assertions.swift rename to Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift b/Tests/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift similarity index 100% rename from Sources/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift rename to Tests/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift similarity index 100% rename from Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift rename to Tests/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/TestContext.swift b/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift similarity index 100% rename from Sources/_CollectionsTestSupport/AssertionContexts/TestContext.swift rename to Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift similarity index 100% rename from Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift rename to Tests/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift similarity index 100% rename from Sources/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift rename to Tests/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift similarity index 100% rename from Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift rename to Tests/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift similarity index 100% rename from Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift rename to Tests/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift similarity index 100% rename from Sources/_CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift rename to Tests/_CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift similarity index 100% rename from Sources/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift rename to Tests/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalIndex.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalIndex.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalIndex.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalIndex.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalIterator.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalIterator.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalIterator.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalIterator.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/ResettableValue.swift b/Tests/_CollectionsTestSupport/MinimalTypes/ResettableValue.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/ResettableValue.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/ResettableValue.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/_CollectionState.swift b/Tests/_CollectionsTestSupport/MinimalTypes/_CollectionState.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/_CollectionState.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/_CollectionState.swift diff --git a/Sources/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift b/Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift similarity index 100% rename from Sources/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift rename to Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/AllOnesRandomNumberGenerator.swift b/Tests/_CollectionsTestSupport/Utilities/AllOnesRandomNumberGenerator.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/AllOnesRandomNumberGenerator.swift rename to Tests/_CollectionsTestSupport/Utilities/AllOnesRandomNumberGenerator.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/Box.swift b/Tests/_CollectionsTestSupport/Utilities/Box.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/Box.swift rename to Tests/_CollectionsTestSupport/Utilities/Box.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift b/Tests/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift rename to Tests/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/HashableBox.swift b/Tests/_CollectionsTestSupport/Utilities/HashableBox.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/HashableBox.swift rename to Tests/_CollectionsTestSupport/Utilities/HashableBox.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift b/Tests/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift rename to Tests/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/Integer Square Root.swift b/Tests/_CollectionsTestSupport/Utilities/Integer Square Root.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/Integer Square Root.swift rename to Tests/_CollectionsTestSupport/Utilities/Integer Square Root.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/LifetimeTracked.swift b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/LifetimeTracked.swift rename to Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/LifetimeTracker.swift b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracker.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/LifetimeTracker.swift rename to Tests/_CollectionsTestSupport/Utilities/LifetimeTracker.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/RandomStableSample.swift b/Tests/_CollectionsTestSupport/Utilities/RandomStableSample.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/RandomStableSample.swift rename to Tests/_CollectionsTestSupport/Utilities/RandomStableSample.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/RepeatableRandomNumberGenerator.swift b/Tests/_CollectionsTestSupport/Utilities/RepeatableRandomNumberGenerator.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/RepeatableRandomNumberGenerator.swift rename to Tests/_CollectionsTestSupport/Utilities/RepeatableRandomNumberGenerator.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift b/Tests/_CollectionsTestSupport/Utilities/SetAPIChecker.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/SetAPIChecker.swift rename to Tests/_CollectionsTestSupport/Utilities/SetAPIChecker.swift diff --git a/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift b/Tests/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift similarity index 95% rename from Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift rename to Tests/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift index 07c223a5..55c25422 100644 --- a/Sources/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift +++ b/Tests/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift @@ -9,7 +9,9 @@ // //===----------------------------------------------------------------------===// -#if !COLLECTIONS_SINGLE_MODULE +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else import _CollectionsUtilities #endif diff --git a/Sources/_CollectionsTestSupport/Utilities/StringConvertibleValue.swift b/Tests/_CollectionsTestSupport/Utilities/StringConvertibleValue.swift similarity index 100% rename from Sources/_CollectionsTestSupport/Utilities/StringConvertibleValue.swift rename to Tests/_CollectionsTestSupport/Utilities/StringConvertibleValue.swift From e6ecdac581c3f03f442111b87655702e0664df67 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 22 Mar 2023 21:45:46 -0700 Subject: [PATCH 089/113] Fix off by one error in BitSet --- Sources/BitCollections/BitSet/BitSet+Extras.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/BitCollections/BitSet/BitSet+Extras.swift b/Sources/BitCollections/BitSet/BitSet+Extras.swift index 5a6ba9d7..4543076a 100644 --- a/Sources/BitCollections/BitSet/BitSet+Extras.swift +++ b/Sources/BitCollections/BitSet/BitSet+Extras.swift @@ -69,7 +69,7 @@ extension BitSet { } if newValue { _ensureCapacity(forValue: member) - } else if member > _capacity { + } else if member >= _capacity { return } _updateThenShrink { handle, shrink in From 8a4c842ad391113d12971e93d4cbba6d2674f5ca Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 22 Mar 2023 22:04:47 -0700 Subject: [PATCH 090/113] Disable COLLECTIONS_SINGLE_MODULE by default Also, remove COLLECTIONS_ENABLE_UNSTABLE_MODULES as it is no longer doing anything. --- Package.swift | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Package.swift b/Package.swift index 3aefbde9..49fb019e 100644 --- a/Package.swift +++ b/Package.swift @@ -45,14 +45,11 @@ var defines: [String] = [ // Enables randomized testing of some data structure implementations. "COLLECTIONS_RANDOMIZED_TESTING", - // Enable modules that aren't source stable yet, and aren't ready for general use. -// "COLLECTIONS_ENABLE_UNSTABLE_MODULES", - // Enable this to build the sources as a single, large module. // This removes the distinct modules for each data structure, instead // putting them all directly into the `Collections` module. // Note: This is a source-incompatible variation of the default configuration. - "COLLECTIONS_SINGLE_MODULE", +// "COLLECTIONS_SINGLE_MODULE", ] var _settings: [SwiftSetting] = defines.map { .define($0) } From 0a55894501275f4e75a38fd186cea4a6dd242b7c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 23 Mar 2023 13:04:41 -0700 Subject: [PATCH 091/113] Add an Xcode project exercising a monomodule configuration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is going to ship as is, with no promises about it remaining in future versions. It is going to be a load bearing component of the package, though — just not necessary a stable one. --- Xcode/Collections.xcconfig | 22 + Xcode/Collections.xcodeproj/project.pbxproj | 2477 +++++++++++++++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + Xcode/CollectionsTests.xcconfig | 22 + Xcode/Shared.xcconfig | 79 + 6 files changed, 2615 insertions(+) create mode 100644 Xcode/Collections.xcconfig create mode 100644 Xcode/Collections.xcodeproj/project.pbxproj create mode 100644 Xcode/Collections.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 Xcode/Collections.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 Xcode/CollectionsTests.xcconfig create mode 100644 Xcode/Shared.xcconfig diff --git a/Xcode/Collections.xcconfig b/Xcode/Collections.xcconfig new file mode 100644 index 00000000..9a892a6b --- /dev/null +++ b/Xcode/Collections.xcconfig @@ -0,0 +1,22 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +PRODUCT_NAME = Collections +PRODUCT_BUNDLE_IDENTIFIER = org.swift.Collections + +SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator watchos watchsimulator appletvos appletvsimulator +ARCHS = $(ARCHS_STANDARD) + +DEFINES_MODULE = YES + +ENABLE_TESTABILITY = NO + + diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj new file mode 100644 index 00000000..ec50093b --- /dev/null +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -0,0 +1,2477 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + 7DE91B2F29CA6721004483EB /* Collections.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7DE91B2629CA6721004483EB /* Collections.framework */; }; + 7DE9200D29CA70F3004483EB /* OrderedDictionary+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7529CA70F3004483EB /* OrderedDictionary+Equatable.swift */; }; + 7DE9200E29CA70F3004483EB /* OrderedDictionary+ExpressibleByDictionaryLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7629CA70F3004483EB /* OrderedDictionary+ExpressibleByDictionaryLiteral.swift */; }; + 7DE9200F29CA70F3004483EB /* OrderedDictionary+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7729CA70F3004483EB /* OrderedDictionary+Hashable.swift */; }; + 7DE9201029CA70F3004483EB /* OrderedDictionary+Deprecations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7829CA70F3004483EB /* OrderedDictionary+Deprecations.swift */; }; + 7DE9201129CA70F3004483EB /* OrderedDictionary+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7929CA70F3004483EB /* OrderedDictionary+Initializers.swift */; }; + 7DE9201229CA70F3004483EB /* OrderedDictionary+Elements.SubSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7A29CA70F3004483EB /* OrderedDictionary+Elements.SubSequence.swift */; }; + 7DE9201329CA70F3004483EB /* OrderedDictionary+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7B29CA70F3004483EB /* OrderedDictionary+CustomReflectable.swift */; }; + 7DE9201429CA70F3004483EB /* OrderedDictionary+Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7C29CA70F3004483EB /* OrderedDictionary+Sequence.swift */; }; + 7DE9201529CA70F3004483EB /* OrderedDictionary+Partial RangeReplaceableCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7D29CA70F3004483EB /* OrderedDictionary+Partial RangeReplaceableCollection.swift */; }; + 7DE9201629CA70F3004483EB /* OrderedDictionary+Elements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7E29CA70F3004483EB /* OrderedDictionary+Elements.swift */; }; + 7DE9201729CA70F3004483EB /* OrderedDictionary+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7F29CA70F3004483EB /* OrderedDictionary+Codable.swift */; }; + 7DE9201829CA70F3004483EB /* OrderedDictionary+Invariants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8029CA70F3004483EB /* OrderedDictionary+Invariants.swift */; }; + 7DE9201929CA70F3004483EB /* OrderedDictionary+Values.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8129CA70F3004483EB /* OrderedDictionary+Values.swift */; }; + 7DE9201A29CA70F3004483EB /* OrderedDictionary+Sendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8229CA70F3004483EB /* OrderedDictionary+Sendable.swift */; }; + 7DE9201B29CA70F3004483EB /* OrderedDictionary+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8329CA70F3004483EB /* OrderedDictionary+Descriptions.swift */; }; + 7DE9201C29CA70F3004483EB /* OrderedDictionary+Partial MutableCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8429CA70F3004483EB /* OrderedDictionary+Partial MutableCollection.swift */; }; + 7DE9201D29CA70F3004483EB /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8529CA70F3004483EB /* OrderedDictionary.swift */; }; + 7DE9201E29CA70F3004483EB /* OrderedSet+Partial SetAlgebra symmetricDifference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8729CA70F3004483EB /* OrderedSet+Partial SetAlgebra symmetricDifference.swift */; }; + 7DE9201F29CA70F3004483EB /* OrderedSet+RandomAccessCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8829CA70F3004483EB /* OrderedSet+RandomAccessCollection.swift */; }; + 7DE9202029CA70F3004483EB /* OrderedSet+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8929CA70F3004483EB /* OrderedSet+Descriptions.swift */; }; + 7DE9202129CA70F3004483EB /* OrderedSet+Partial SetAlgebra isEqualSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8A29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isEqualSet.swift */; }; + 7DE9202229CA70F3004483EB /* OrderedSet+Diffing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8B29CA70F3004483EB /* OrderedSet+Diffing.swift */; }; + 7DE9202329CA70F3004483EB /* OrderedSet+UnstableInternals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8C29CA70F3004483EB /* OrderedSet+UnstableInternals.swift */; }; + 7DE9202429CA70F3004483EB /* OrderedSet+Invariants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8D29CA70F3004483EB /* OrderedSet+Invariants.swift */; }; + 7DE9202529CA70F3004483EB /* OrderedSet+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8E29CA70F3004483EB /* OrderedSet+Hashable.swift */; }; + 7DE9202629CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSubset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E8F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSubset.swift */; }; + 7DE9202729CA70F3004483EB /* OrderedSet+Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9029CA70F3004483EB /* OrderedSet+Insertions.swift */; }; + 7DE9202829CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSubset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9129CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSubset.swift */; }; + 7DE9202929CA70F3004483EB /* OrderedSet+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9229CA70F3004483EB /* OrderedSet+Codable.swift */; }; + 7DE9202A29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSuperset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9329CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSuperset.swift */; }; + 7DE9202B29CA70F3004483EB /* OrderedSet+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9429CA70F3004483EB /* OrderedSet+Equatable.swift */; }; + 7DE9202C29CA70F3004483EB /* OrderedSet+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9529CA70F3004483EB /* OrderedSet+Initializers.swift */; }; + 7DE9202D29CA70F3004483EB /* OrderedSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9629CA70F3004483EB /* OrderedSet.swift */; }; + 7DE9202E29CA70F3004483EB /* OrderedSet+UnorderedView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9729CA70F3004483EB /* OrderedSet+UnorderedView.swift */; }; + 7DE9202F29CA70F3004483EB /* OrderedSet+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9829CA70F3004483EB /* OrderedSet+ExpressibleByArrayLiteral.swift */; }; + 7DE9203029CA70F3004483EB /* OrderedSet+SubSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9929CA70F3004483EB /* OrderedSet+SubSequence.swift */; }; + 7DE9203129CA70F3004483EB /* OrderedSet+Partial MutableCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9A29CA70F3004483EB /* OrderedSet+Partial MutableCollection.swift */; }; + 7DE9203229CA70F3004483EB /* OrderedSet+Sendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9B29CA70F3004483EB /* OrderedSet+Sendable.swift */; }; + 7DE9203329CA70F3004483EB /* OrderedSet+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9C29CA70F3004483EB /* OrderedSet+Testing.swift */; }; + 7DE9203429CA70F3004483EB /* OrderedSet+Partial SetAlgebra formUnion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9D29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formUnion.swift */; }; + 7DE9203529CA70F3004483EB /* OrderedSet+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9E29CA70F3004483EB /* OrderedSet+CustomReflectable.swift */; }; + 7DE9203629CA70F3004483EB /* OrderedSet+ReserveCapacity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E9F29CA70F3004483EB /* OrderedSet+ReserveCapacity.swift */; }; + 7DE9203729CA70F3004483EB /* OrderedSet+Partial SetAlgebra union.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA029CA70F3004483EB /* OrderedSet+Partial SetAlgebra union.swift */; }; + 7DE9203829CA70F3004483EB /* OrderedSet+Partial SetAlgebra formIntersection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA129CA70F3004483EB /* OrderedSet+Partial SetAlgebra formIntersection.swift */; }; + 7DE9203929CA70F3004483EB /* OrderedSet+Partial RangeReplaceableCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA229CA70F3004483EB /* OrderedSet+Partial RangeReplaceableCollection.swift */; }; + 7DE9203A29CA70F3004483EB /* OrderedSet+Partial SetAlgebra+Basics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA329CA70F3004483EB /* OrderedSet+Partial SetAlgebra+Basics.swift */; }; + 7DE9203B29CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtracting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA429CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtracting.swift */; }; + 7DE9203C29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA529CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift */; }; + 7DE9203D29CA70F3004483EB /* OrderedSet+Partial SetAlgebra intersection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA629CA70F3004483EB /* OrderedSet+Partial SetAlgebra intersection.swift */; }; + 7DE9203E29CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtract.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA729CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtract.swift */; }; + 7DE9203F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA829CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift */; }; + 7DE9204029CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSuperset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EA929CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSuperset.swift */; }; + 7DE9204129CA70F3004483EB /* _UnsafeBitset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EAB29CA70F3004483EB /* _UnsafeBitset.swift */; }; + 7DE9204229CA70F3004483EB /* _HashTable+UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EAD29CA70F3004483EB /* _HashTable+UnsafeHandle.swift */; }; + 7DE9204329CA70F3004483EB /* _HashTable+Bucket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EAE29CA70F3004483EB /* _HashTable+Bucket.swift */; }; + 7DE9204429CA70F3004483EB /* _HashTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EAF29CA70F3004483EB /* _HashTable.swift */; }; + 7DE9204529CA70F3004483EB /* _HashTable+Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB029CA70F3004483EB /* _HashTable+Constants.swift */; }; + 7DE9204629CA70F3004483EB /* _Hashtable+Header.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB129CA70F3004483EB /* _Hashtable+Header.swift */; }; + 7DE9204729CA70F3004483EB /* _HashTable+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB229CA70F3004483EB /* _HashTable+Testing.swift */; }; + 7DE9204829CA70F3004483EB /* _HashTable+CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB329CA70F3004483EB /* _HashTable+CustomStringConvertible.swift */; }; + 7DE9204929CA70F3004483EB /* _HashTable+BucketIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB429CA70F3004483EB /* _HashTable+BucketIterator.swift */; }; + 7DE9204B29CA70F3004483EB /* _DequeBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB729CA70F3004483EB /* _DequeBuffer.swift */; }; + 7DE9204C29CA70F3004483EB /* Deque+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EB829CA70F3004483EB /* Deque+Collection.swift */; }; + 7DE9204E29CA70F3004483EB /* Deque+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBA29CA70F3004483EB /* Deque+CustomReflectable.swift */; }; + 7DE9204F29CA70F3004483EB /* Deque.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBB29CA70F3004483EB /* Deque.swift */; }; + 7DE9205029CA70F3004483EB /* _DequeSlot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBC29CA70F3004483EB /* _DequeSlot.swift */; }; + 7DE9205129CA70F3004483EB /* Deque+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBD29CA70F3004483EB /* Deque+Hashable.swift */; }; + 7DE9205229CA70F3004483EB /* _UnsafeWrappedBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBE29CA70F3004483EB /* _UnsafeWrappedBuffer.swift */; }; + 7DE9205329CA70F3004483EB /* _DequeBufferHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EBF29CA70F3004483EB /* _DequeBufferHeader.swift */; }; + 7DE9205429CA70F3004483EB /* Deque+Sendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC029CA70F3004483EB /* Deque+Sendable.swift */; }; + 7DE9205529CA70F3004483EB /* Deque+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC129CA70F3004483EB /* Deque+Codable.swift */; }; + 7DE9205629CA70F3004483EB /* Deque+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC229CA70F3004483EB /* Deque+Testing.swift */; }; + 7DE9205829CA70F3004483EB /* Deque._UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC429CA70F3004483EB /* Deque._UnsafeHandle.swift */; }; + 7DE9205929CA70F3004483EB /* Deque+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC529CA70F3004483EB /* Deque+Descriptions.swift */; }; + 7DE9205A29CA70F3004483EB /* Deque+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC629CA70F3004483EB /* Deque+Extras.swift */; }; + 7DE9205B29CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC729CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift */; }; + 7DE9205C29CA70F3004483EB /* Deque+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC829CA70F3004483EB /* Deque+Equatable.swift */; }; + 7DE9205D29CA70F4004483EB /* Deque._Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EC929CA70F3004483EB /* Deque._Storage.swift */; }; + 7DE9205E29CA70F4004483EB /* BigString+Metrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ECD29CA70F3004483EB /* BigString+Metrics.swift */; }; + 7DE9205F29CA70F4004483EB /* BigString+Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ECE29CA70F3004483EB /* BigString+Index.swift */; }; + 7DE9206029CA70F4004483EB /* BigString+Summary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ECF29CA70F3004483EB /* BigString+Summary.swift */; }; + 7DE9206129CA70F4004483EB /* BigString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ED029CA70F3004483EB /* BigString.swift */; }; + 7DE9206229CA70F4004483EB /* BigString+Iterators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ED129CA70F3004483EB /* BigString+Iterators.swift */; }; + 7DE9206329CA70F4004483EB /* BigString+Contents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ED229CA70F3004483EB /* BigString+Contents.swift */; }; + 7DE9206429CA70F4004483EB /* BigString+Invariants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ED329CA70F3004483EB /* BigString+Invariants.swift */; }; + 7DE9206529CA70F4004483EB /* BigString+Ingester.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ED429CA70F3004483EB /* BigString+Ingester.swift */; }; + 7DE9206629CA70F4004483EB /* BigString+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ED529CA70F3004483EB /* BigString+Debugging.swift */; }; + 7DE9206729CA70F4004483EB /* BigString+Builder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ED629CA70F3004483EB /* BigString+Builder.swift */; }; + 7DE9206829CA70F4004483EB /* BigString+Chunk+Append and Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ED829CA70F3004483EB /* BigString+Chunk+Append and Insert.swift */; }; + 7DE9206929CA70F4004483EB /* BigString+Chunk+Indexing by UTF16.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91ED929CA70F3004483EB /* BigString+Chunk+Indexing by UTF16.swift */; }; + 7DE9206A29CA70F4004483EB /* BigString+Chunk+Counts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EDA29CA70F3004483EB /* BigString+Chunk+Counts.swift */; }; + 7DE9206B29CA70F4004483EB /* BigString+Chunk+Indexing by Characters.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EDB29CA70F3004483EB /* BigString+Chunk+Indexing by Characters.swift */; }; + 7DE9206C29CA70F4004483EB /* BigString+Chunk.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EDC29CA70F3004483EB /* BigString+Chunk.swift */; }; + 7DE9206D29CA70F4004483EB /* BigString+Chunk+Description.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EDD29CA70F3004483EB /* BigString+Chunk+Description.swift */; }; + 7DE9206E29CA70F4004483EB /* BigString+Chunk+Splitting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EDE29CA70F3004483EB /* BigString+Chunk+Splitting.swift */; }; + 7DE9206F29CA70F4004483EB /* BigString+Chunk+Breaks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EDF29CA70F3004483EB /* BigString+Chunk+Breaks.swift */; }; + 7DE9207029CA70F4004483EB /* BigString+Chunk+RopeElement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EE029CA70F3004483EB /* BigString+Chunk+RopeElement.swift */; }; + 7DE9207129CA70F4004483EB /* BigString+Split.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EE229CA70F3004483EB /* BigString+Split.swift */; }; + 7DE9207229CA70F4004483EB /* BigString+Managing Breaks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EE329CA70F3004483EB /* BigString+Managing Breaks.swift */; }; + 7DE9207329CA70F4004483EB /* BigString+RemoveSubrange.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EE429CA70F3004483EB /* BigString+RemoveSubrange.swift */; }; + 7DE9207429CA70F4004483EB /* BigString+ReplaceSubrange.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EE529CA70F3004483EB /* BigString+ReplaceSubrange.swift */; }; + 7DE9207529CA70F4004483EB /* BigString+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EE629CA70F3004483EB /* BigString+Insert.swift */; }; + 7DE9207629CA70F4004483EB /* BigString+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EE729CA70F3004483EB /* BigString+Initializers.swift */; }; + 7DE9207729CA70F4004483EB /* Range+BigString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EE829CA70F3004483EB /* Range+BigString.swift */; }; + 7DE9207829CA70F4004483EB /* BigString+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EE929CA70F3004483EB /* BigString+Append.swift */; }; + 7DE9207929CA70F4004483EB /* BigString+UnicodeScalarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EEB29CA70F3004483EB /* BigString+UnicodeScalarView.swift */; }; + 7DE9207A29CA70F4004483EB /* BigString+UTF8View.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EEC29CA70F3004483EB /* BigString+UTF8View.swift */; }; + 7DE9207B29CA70F4004483EB /* BigSubstring+UnicodeScalarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EED29CA70F3004483EB /* BigSubstring+UnicodeScalarView.swift */; }; + 7DE9207C29CA70F4004483EB /* BigSubstring.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EEE29CA70F3004483EB /* BigSubstring.swift */; }; + 7DE9207D29CA70F4004483EB /* BigSubstring+UTF16View.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EEF29CA70F3004483EB /* BigSubstring+UTF16View.swift */; }; + 7DE9207E29CA70F4004483EB /* BigString+UTF16View.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EF029CA70F3004483EB /* BigString+UTF16View.swift */; }; + 7DE9207F29CA70F4004483EB /* BigSubstring+UTF8View.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EF129CA70F3004483EB /* BigSubstring+UTF8View.swift */; }; + 7DE9208029CA70F4004483EB /* BigString+Hashing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EF329CA70F3004483EB /* BigString+Hashing.swift */; }; + 7DE9208129CA70F4004483EB /* BigString+CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EF429CA70F3004483EB /* BigString+CustomStringConvertible.swift */; }; + 7DE9208229CA70F4004483EB /* BigString+BidirectionalCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EF529CA70F3004483EB /* BigString+BidirectionalCollection.swift */; }; + 7DE9208329CA70F4004483EB /* BigString+CustomDebugStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EF629CA70F3004483EB /* BigString+CustomDebugStringConvertible.swift */; }; + 7DE9208429CA70F4004483EB /* BigString+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EF729CA70F3004483EB /* BigString+Equatable.swift */; }; + 7DE9208529CA70F4004483EB /* BigString+TextOutputStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EF829CA70F3004483EB /* BigString+TextOutputStream.swift */; }; + 7DE9208629CA70F4004483EB /* BigString+LosslessStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EF929CA70F3004483EB /* BigString+LosslessStringConvertible.swift */; }; + 7DE9208729CA70F4004483EB /* BigString+Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EFA29CA70F3004483EB /* BigString+Sequence.swift */; }; + 7DE9208829CA70F4004483EB /* BigString+ExpressibleByStringLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EFB29CA70F3004483EB /* BigString+ExpressibleByStringLiteral.swift */; }; + 7DE9208929CA70F4004483EB /* BigString+RangeReplaceableCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EFC29CA70F3004483EB /* BigString+RangeReplaceableCollection.swift */; }; + 7DE9208A29CA70F4004483EB /* BigString+Comparable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91EFD29CA70F3004483EB /* BigString+Comparable.swift */; }; + 7DE9208B29CA70F4004483EB /* RopeMetric.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0029CA70F3004483EB /* RopeMetric.swift */; }; + 7DE9208C29CA70F4004483EB /* _RopeItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0129CA70F3004483EB /* _RopeItem.swift */; }; + 7DE9208D29CA70F4004483EB /* Rope+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0229CA70F3004483EB /* Rope+Debugging.swift */; }; + 7DE9208E29CA70F4004483EB /* _RopeVersion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0329CA70F3004483EB /* _RopeVersion.swift */; }; + 7DE9208F29CA70F4004483EB /* RopeElement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0429CA70F3004483EB /* RopeElement.swift */; }; + 7DE9209029CA70F4004483EB /* Rope.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0529CA70F3004483EB /* Rope.swift */; }; + 7DE9209129CA70F4004483EB /* Rope+_UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0629CA70F3004483EB /* Rope+_UnsafeHandle.swift */; }; + 7DE9209229CA70F4004483EB /* Rope+_Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0729CA70F3004483EB /* Rope+_Storage.swift */; }; + 7DE9209329CA70F4004483EB /* Rope+Invariants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0829CA70F3004483EB /* Rope+Invariants.swift */; }; + 7DE9209429CA70F4004483EB /* Rope+_UnmanagedLeaf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0929CA70F3004483EB /* Rope+_UnmanagedLeaf.swift */; }; + 7DE9209529CA70F4004483EB /* RopeSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0A29CA70F3004483EB /* RopeSummary.swift */; }; + 7DE9209629CA70F4004483EB /* Rope+Builder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0B29CA70F3004483EB /* Rope+Builder.swift */; }; + 7DE9209729CA70F4004483EB /* _RopePath.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0C29CA70F3004483EB /* _RopePath.swift */; }; + 7DE9209829CA70F4004483EB /* Rope+_Node.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0D29CA70F3004483EB /* Rope+_Node.swift */; }; + 7DE9209929CA70F4004483EB /* Rope+Extract.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F0F29CA70F3004483EB /* Rope+Extract.swift */; }; + 7DE9209A29CA70F4004483EB /* Rope+Append.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1029CA70F3004483EB /* Rope+Append.swift */; }; + 7DE9209B29CA70F4004483EB /* Rope+Split.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1129CA70F3004483EB /* Rope+Split.swift */; }; + 7DE9209C29CA70F4004483EB /* Rope+Find.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1229CA70F3004483EB /* Rope+Find.swift */; }; + 7DE9209D29CA70F4004483EB /* Rope+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1329CA70F3004483EB /* Rope+Insert.swift */; }; + 7DE9209E29CA70F4004483EB /* Rope+ForEachWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1429CA70F3004483EB /* Rope+ForEachWhile.swift */; }; + 7DE9209F29CA70F4004483EB /* Rope+MutatingForEach.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1529CA70F3004483EB /* Rope+MutatingForEach.swift */; }; + 7DE920A029CA70F4004483EB /* Rope+Join.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1629CA70F3004483EB /* Rope+Join.swift */; }; + 7DE920A129CA70F4004483EB /* Rope+Remove.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1729CA70F3004483EB /* Rope+Remove.swift */; }; + 7DE920A229CA70F4004483EB /* Rope+RemoveSubrange.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1829CA70F3004483EB /* Rope+RemoveSubrange.swift */; }; + 7DE920A329CA70F4004483EB /* Rope+Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1A29CA70F3004483EB /* Rope+Index.swift */; }; + 7DE920A429CA70F4004483EB /* Rope+Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1B29CA70F3004483EB /* Rope+Sequence.swift */; }; + 7DE920A529CA70F4004483EB /* Rope+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1C29CA70F3004483EB /* Rope+Collection.swift */; }; + 7DE920A629CA70F4004483EB /* String Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1E29CA70F3004483EB /* String Utilities.swift */; }; + 7DE920A729CA70F4004483EB /* _CharacterRecognizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F1F29CA70F3004483EB /* _CharacterRecognizer.swift */; }; + 7DE920A829CA70F4004483EB /* String.Index+ABI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F2029CA70F3004483EB /* String.Index+ABI.swift */; }; + 7DE920A929CA70F4004483EB /* Optional Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F2129CA70F3004483EB /* Optional Utilities.swift */; }; + 7DE920B529CA70F4004483EB /* _SortedCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F3029CA70F3004483EB /* _SortedCollection.swift */; }; + 7DE920BC29CA70F4004483EB /* _UniqueCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F3829CA70F3004483EB /* _UniqueCollection.swift */; }; + 7DE920BD29CA70F4004483EB /* BitSet+SetAlgebra symmetricDifference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F3B29CA70F3004483EB /* BitSet+SetAlgebra symmetricDifference.swift */; }; + 7DE920BE29CA70F4004483EB /* BitSet+SetAlgebra formIntersection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F3C29CA70F3004483EB /* BitSet+SetAlgebra formIntersection.swift */; }; + 7DE920BF29CA70F4004483EB /* BitSet+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F3D29CA70F3004483EB /* BitSet+Codable.swift */; }; + 7DE920C029CA70F4004483EB /* BitSet+SetAlgebra conformance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F3E29CA70F3004483EB /* BitSet+SetAlgebra conformance.swift */; }; + 7DE920C129CA70F4004483EB /* BitSet+SetAlgebra subtract.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F3F29CA70F3004483EB /* BitSet+SetAlgebra subtract.swift */; }; + 7DE920C229CA70F4004483EB /* BitSet+Sorted Collection APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4029CA70F3004483EB /* BitSet+Sorted Collection APIs.swift */; }; + 7DE920C329CA70F4004483EB /* BitSet+SetAlgebra formUnion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4129CA70F3004483EB /* BitSet+SetAlgebra formUnion.swift */; }; + 7DE920C429CA70F4004483EB /* BitSet+SetAlgebra isStrictSuperset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4229CA70F3004483EB /* BitSet+SetAlgebra isStrictSuperset.swift */; }; + 7DE920C529CA70F4004483EB /* BitSet+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4329CA70F3004483EB /* BitSet+Extras.swift */; }; + 7DE920C629CA70F4004483EB /* BitSet+SetAlgebra formSymmetricDifference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4429CA70F3004483EB /* BitSet+SetAlgebra formSymmetricDifference.swift */; }; + 7DE920C729CA70F4004483EB /* BitSet+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4529CA70F3004483EB /* BitSet+ExpressibleByArrayLiteral.swift */; }; + 7DE920C829CA70F4004483EB /* BitSet+SetAlgebra isEqualSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4629CA70F3004483EB /* BitSet+SetAlgebra isEqualSet.swift */; }; + 7DE920C929CA70F4004483EB /* BitSet+BidirectionalCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4729CA70F3004483EB /* BitSet+BidirectionalCollection.swift */; }; + 7DE920CA29CA70F4004483EB /* BitSet+CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4829CA70F3004483EB /* BitSet+CustomStringConvertible.swift */; }; + 7DE920CB29CA70F4004483EB /* BitSet+Random.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4929CA70F3004483EB /* BitSet+Random.swift */; }; + 7DE920CC29CA70F4004483EB /* BitSet.Counted.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4A29CA70F3004483EB /* BitSet.Counted.swift */; }; + 7DE920CD29CA70F4004483EB /* BitSet+CustomDebugStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4B29CA70F3004483EB /* BitSet+CustomDebugStringConvertible.swift */; }; + 7DE920CE29CA70F4004483EB /* BitSet+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4C29CA70F3004483EB /* BitSet+CustomReflectable.swift */; }; + 7DE920CF29CA70F4004483EB /* BitSet+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4D29CA70F3004483EB /* BitSet+Initializers.swift */; }; + 7DE920D029CA70F4004483EB /* BitSet+SetAlgebra isSubset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4E29CA70F3004483EB /* BitSet+SetAlgebra isSubset.swift */; }; + 7DE920D129CA70F4004483EB /* BitSet.Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F4F29CA70F3004483EB /* BitSet.Index.swift */; }; + 7DE920D229CA70F4004483EB /* BitSet+SetAlgebra basics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5029CA70F3004483EB /* BitSet+SetAlgebra basics.swift */; }; + 7DE920D329CA70F4004483EB /* BitSet+SetAlgebra isDisjoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5129CA70F3004483EB /* BitSet+SetAlgebra isDisjoint.swift */; }; + 7DE920D429CA70F4004483EB /* BitSet+SetAlgebra union.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5229CA70F3004483EB /* BitSet+SetAlgebra union.swift */; }; + 7DE920D529CA70F4004483EB /* BitSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5329CA70F3004483EB /* BitSet.swift */; }; + 7DE920D629CA70F4004483EB /* BitSet+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5429CA70F3004483EB /* BitSet+Equatable.swift */; }; + 7DE920D729CA70F4004483EB /* BitSet+SetAlgebra isSuperset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5529CA70F3004483EB /* BitSet+SetAlgebra isSuperset.swift */; }; + 7DE920D829CA70F4004483EB /* BitSet+SetAlgebra subtracting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5629CA70F3004483EB /* BitSet+SetAlgebra subtracting.swift */; }; + 7DE920D929CA70F4004483EB /* BitSet+SetAlgebra intersection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5729CA70F3004483EB /* BitSet+SetAlgebra intersection.swift */; }; + 7DE920DA29CA70F4004483EB /* BitSet._UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5829CA70F3004483EB /* BitSet._UnsafeHandle.swift */; }; + 7DE920DB29CA70F4004483EB /* BitSet+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5929CA70F3004483EB /* BitSet+Hashable.swift */; }; + 7DE920DC29CA70F4004483EB /* BitSet+Invariants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5A29CA70F3004483EB /* BitSet+Invariants.swift */; }; + 7DE920DD29CA70F4004483EB /* BitSet+SetAlgebra isStrictSubset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5B29CA70F3004483EB /* BitSet+SetAlgebra isStrictSubset.swift */; }; + 7DE920DF29CA70F4004483EB /* Slice+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5E29CA70F3004483EB /* Slice+Utilities.swift */; }; + 7DE920E029CA70F4004483EB /* Range+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5F29CA70F3004483EB /* Range+Utilities.swift */; }; + 7DE920E129CA70F4004483EB /* UInt+Tricks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6029CA70F3004483EB /* UInt+Tricks.swift */; }; + 7DE920E229CA70F4004483EB /* _Word.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6129CA70F3004483EB /* _Word.swift */; }; + 7DE920E529CA70F4004483EB /* BitArray+CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6529CA70F3004483EB /* BitArray+CustomStringConvertible.swift */; }; + 7DE920E629CA70F4004483EB /* BitArray+ChunkedBitsIterators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6629CA70F3004483EB /* BitArray+ChunkedBitsIterators.swift */; }; + 7DE920E729CA70F4004483EB /* BitArray+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6729CA70F3004483EB /* BitArray+CustomReflectable.swift */; }; + 7DE920E829CA70F4004483EB /* BitArray+BitwiseOperations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6829CA70F3004483EB /* BitArray+BitwiseOperations.swift */; }; + 7DE920E929CA70F4004483EB /* BitArray+Invariants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6929CA70F3004483EB /* BitArray+Invariants.swift */; }; + 7DE920EA29CA70F4004483EB /* BitArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6A29CA70F3004483EB /* BitArray.swift */; }; + 7DE920EB29CA70F4004483EB /* BitArray+Fill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6B29CA70F3004483EB /* BitArray+Fill.swift */; }; + 7DE920EC29CA70F4004483EB /* BitArray+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6C29CA70F3004483EB /* BitArray+Collection.swift */; }; + 7DE920ED29CA70F4004483EB /* BitArray+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6D29CA70F3004483EB /* BitArray+Extras.swift */; }; + 7DE920EE29CA70F4004483EB /* BitArray+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6E29CA70F3004483EB /* BitArray+ExpressibleByArrayLiteral.swift */; }; + 7DE920EF29CA70F4004483EB /* BitArray+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6F29CA70F3004483EB /* BitArray+Codable.swift */; }; + 7DE920F029CA70F4004483EB /* BitArray+RangeReplaceableCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7029CA70F3004483EB /* BitArray+RangeReplaceableCollection.swift */; }; + 7DE920F129CA70F4004483EB /* BitArray+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7129CA70F3004483EB /* BitArray+Initializers.swift */; }; + 7DE920F229CA70F4004483EB /* BitArray._UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7229CA70F3004483EB /* BitArray._UnsafeHandle.swift */; }; + 7DE920F329CA70F4004483EB /* BitArray+Copy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7329CA70F3004483EB /* BitArray+Copy.swift */; }; + 7DE920F429CA70F4004483EB /* BitArray+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7429CA70F3004483EB /* BitArray+Hashable.swift */; }; + 7DE920F529CA70F4004483EB /* BitArray+CustomDebugStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7529CA70F3004483EB /* BitArray+CustomDebugStringConvertible.swift */; }; + 7DE920F629CA70F4004483EB /* BitArray+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7629CA70F3004483EB /* BitArray+Equatable.swift */; }; + 7DE920F729CA70F4004483EB /* BitArray+Random.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7729CA70F3004483EB /* BitArray+Random.swift */; }; + 7DE920F829CA70F4004483EB /* BitArray+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7829CA70F3004483EB /* BitArray+Testing.swift */; }; + 7DE9212329CA70F4004483EB /* TreeSet+SetAlgebra isEqualSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FAB29CA70F3004483EB /* TreeSet+SetAlgebra isEqualSet.swift */; }; + 7DE9212429CA70F4004483EB /* TreeSet+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FAC29CA70F3004483EB /* TreeSet+Descriptions.swift */; }; + 7DE9212529CA70F4004483EB /* TreeSet+SetAlgebra isStrictSubset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FAD29CA70F3004483EB /* TreeSet+SetAlgebra isStrictSubset.swift */; }; + 7DE9212629CA70F4004483EB /* TreeSet+Sendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FAE29CA70F3004483EB /* TreeSet+Sendable.swift */; }; + 7DE9212729CA70F4004483EB /* TreeSet+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FAF29CA70F3004483EB /* TreeSet+Equatable.swift */; }; + 7DE9212829CA70F4004483EB /* TreeSet+SetAlgebra intersection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB029CA70F3004483EB /* TreeSet+SetAlgebra intersection.swift */; }; + 7DE9212929CA70F4004483EB /* TreeSet+SetAlgebra formUnion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB129CA70F3004483EB /* TreeSet+SetAlgebra formUnion.swift */; }; + 7DE9212A29CA70F4004483EB /* TreeSet+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB229CA70F3004483EB /* TreeSet+Extras.swift */; }; + 7DE9212B29CA70F4004483EB /* TreeSet+SetAlgebra subtracting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB329CA70F3004483EB /* TreeSet+SetAlgebra subtracting.swift */; }; + 7DE9212C29CA70F4004483EB /* TreeSet+SetAlgebra subtract.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB429CA70F3004483EB /* TreeSet+SetAlgebra subtract.swift */; }; + 7DE9212D29CA70F4004483EB /* TreeSet+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB529CA70F3004483EB /* TreeSet+Debugging.swift */; }; + 7DE9212E29CA70F4004483EB /* TreeSet+SetAlgebra isStrictSuperset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB629CA70F3004483EB /* TreeSet+SetAlgebra isStrictSuperset.swift */; }; + 7DE9212F29CA70F4004483EB /* TreeSet+SetAlgebra formIntersection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB729CA70F3004483EB /* TreeSet+SetAlgebra formIntersection.swift */; }; + 7DE9213029CA70F4004483EB /* TreeSet+SetAlgebra isSuperset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB829CA70F3004483EB /* TreeSet+SetAlgebra isSuperset.swift */; }; + 7DE9213129CA70F4004483EB /* TreeSet+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FB929CA70F3004483EB /* TreeSet+CustomReflectable.swift */; }; + 7DE9213229CA70F4004483EB /* TreeSet+SetAlgebra formSymmetricDifference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FBA29CA70F3004483EB /* TreeSet+SetAlgebra formSymmetricDifference.swift */; }; + 7DE9213329CA70F4004483EB /* TreeSet+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FBB29CA70F3004483EB /* TreeSet+Collection.swift */; }; + 7DE9213429CA70F4004483EB /* TreeSet+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FBC29CA70F3004483EB /* TreeSet+ExpressibleByArrayLiteral.swift */; }; + 7DE9213529CA70F4004483EB /* TreeSet+SetAlgebra symmetricDifference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FBD29CA70F3004483EB /* TreeSet+SetAlgebra symmetricDifference.swift */; }; + 7DE9213629CA70F4004483EB /* TreeSet+SetAlgebra basics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FBE29CA70F3004483EB /* TreeSet+SetAlgebra basics.swift */; }; + 7DE9213729CA70F4004483EB /* TreeSet+Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FBF29CA70F3004483EB /* TreeSet+Sequence.swift */; }; + 7DE9213829CA70F4004483EB /* TreeSet+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FC029CA70F3004483EB /* TreeSet+Filter.swift */; }; + 7DE9213929CA70F4004483EB /* TreeSet+SetAlgebra Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FC129CA70F3004483EB /* TreeSet+SetAlgebra Initializers.swift */; }; + 7DE9213A29CA70F4004483EB /* TreeSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FC229CA70F3004483EB /* TreeSet.swift */; }; + 7DE9213B29CA70F4004483EB /* TreeSet+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FC329CA70F3004483EB /* TreeSet+Hashable.swift */; }; + 7DE9213C29CA70F4004483EB /* TreeSet+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FC429CA70F3004483EB /* TreeSet+Codable.swift */; }; + 7DE9213D29CA70F4004483EB /* TreeSet+SetAlgebra isSubset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FC529CA70F3004483EB /* TreeSet+SetAlgebra isSubset.swift */; }; + 7DE9213E29CA70F4004483EB /* TreeSet+SetAlgebra union.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FC629CA70F3004483EB /* TreeSet+SetAlgebra union.swift */; }; + 7DE9213F29CA70F4004483EB /* TreeSet+SetAlgebra isDisjoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FC729CA70F3004483EB /* TreeSet+SetAlgebra isDisjoint.swift */; }; + 7DE9214029CA70F4004483EB /* _Hash.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FC929CA70F3004483EB /* _Hash.swift */; }; + 7DE9214129CA70F4004483EB /* _HashNode+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FCA29CA70F3004483EB /* _HashNode+Initializers.swift */; }; + 7DE9214229CA70F4004483EB /* _HashStack.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FCB29CA70F3004483EB /* _HashStack.swift */; }; + 7DE9214329CA70F4004483EB /* _HashNode+Subtree Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FCC29CA70F3004483EB /* _HashNode+Subtree Removals.swift */; }; + 7DE9214429CA70F4004483EB /* _HashTreeIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FCD29CA70F3004483EB /* _HashTreeIterator.swift */; }; + 7DE9214529CA70F4004483EB /* _HashNode+Structural symmetricDifference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FCE29CA70F3004483EB /* _HashNode+Structural symmetricDifference.swift */; }; + 7DE9214629CA70F4004483EB /* _HashSlot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FCF29CA70F3004483EB /* _HashSlot.swift */; }; + 7DE9214729CA70F4004483EB /* _HashNode+Primitive Replacement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD029CA70F3004483EB /* _HashNode+Primitive Replacement.swift */; }; + 7DE9214829CA70F4004483EB /* _HashNode+Primitive Removals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD129CA70F3004483EB /* _HashNode+Primitive Removals.swift */; }; + 7DE9214929CA70F4004483EB /* _HashNode+Structural isEqualSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD229CA70F3004483EB /* _HashNode+Structural isEqualSet.swift */; }; + 7DE9214A29CA70F4004483EB /* _HashNode+Subtree Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD329CA70F3004483EB /* _HashNode+Subtree Insertions.swift */; }; + 7DE9214B29CA70F4004483EB /* _HashTreeStatistics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD429CA70F3004483EB /* _HashTreeStatistics.swift */; }; + 7DE9214C29CA70F4004483EB /* _HashNode+Primitive Insertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD529CA70F3004483EB /* _HashNode+Primitive Insertions.swift */; }; + 7DE9214D29CA70F4004483EB /* _HashNode+Structural filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD629CA70F3004483EB /* _HashNode+Structural filter.swift */; }; + 7DE9214E29CA70F4004483EB /* _HashNode+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD729CA70F3004483EB /* _HashNode+Debugging.swift */; }; + 7DE9214F29CA70F4004483EB /* _Bucket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD829CA70F3004483EB /* _Bucket.swift */; }; + 7DE9215029CA70F4004483EB /* _UnmanagedHashNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FD929CA70F3004483EB /* _UnmanagedHashNode.swift */; }; + 7DE9215129CA70F4004483EB /* _HashNode+Subtree Modify.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FDA29CA70F3004483EB /* _HashNode+Subtree Modify.swift */; }; + 7DE9215229CA70F4004483EB /* _HashNode+Builder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FDB29CA70F3004483EB /* _HashNode+Builder.swift */; }; + 7DE9215329CA70F4004483EB /* _HashNode+Invariants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FDC29CA70F3004483EB /* _HashNode+Invariants.swift */; }; + 7DE9215429CA70F4004483EB /* _HashNode+UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FDD29CA70F3004483EB /* _HashNode+UnsafeHandle.swift */; }; + 7DE9215529CA70F4004483EB /* _RawHashNode+UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FDE29CA70F3004483EB /* _RawHashNode+UnsafeHandle.swift */; }; + 7DE9215629CA70F4004483EB /* _HashNode+Structural compactMapValues.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FDF29CA70F3004483EB /* _HashNode+Structural compactMapValues.swift */; }; + 7DE9215729CA70F4004483EB /* _RawHashNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE029CA70F3004483EB /* _RawHashNode.swift */; }; + 7DE9215829CA70F4004483EB /* _HashNode+Structural union.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE129CA70F3004483EB /* _HashNode+Structural union.swift */; }; + 7DE9215929CA70F4004483EB /* _HashNode+Structural isSubset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE229CA70F3004483EB /* _HashNode+Structural isSubset.swift */; }; + 7DE9215A29CA70F4004483EB /* _HashNode+Structural subtracting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE329CA70F3004483EB /* _HashNode+Structural subtracting.swift */; }; + 7DE9215B29CA70F4004483EB /* _HashNode+Structural mapValues.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE429CA70F3004483EB /* _HashNode+Structural mapValues.swift */; }; + 7DE9215C29CA70F4004483EB /* _Bitmap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE529CA70F3004483EB /* _Bitmap.swift */; }; + 7DE9215D29CA70F4004483EB /* _StorageHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE629CA70F3004483EB /* _StorageHeader.swift */; }; + 7DE9215E29CA70F4004483EB /* _HashNode+Lookups.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE729CA70F3004483EB /* _HashNode+Lookups.swift */; }; + 7DE9215F29CA70F4004483EB /* _UnsafePath.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE829CA70F3004483EB /* _UnsafePath.swift */; }; + 7DE9216029CA70F4004483EB /* _HashNode+Structural isDisjoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE929CA70F3004483EB /* _HashNode+Structural isDisjoint.swift */; }; + 7DE9216129CA70F4004483EB /* _HashNode+Structural merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FEA29CA70F3004483EB /* _HashNode+Structural merge.swift */; }; + 7DE9216229CA70F4004483EB /* _AncestorHashSlots.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FEB29CA70F3004483EB /* _AncestorHashSlots.swift */; }; + 7DE9216329CA70F4004483EB /* _HashLevel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FEC29CA70F3004483EB /* _HashLevel.swift */; }; + 7DE9216429CA70F4004483EB /* _HashNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FED29CA70F3004483EB /* _HashNode.swift */; }; + 7DE9216529CA70F4004483EB /* _HashNode+Structural intersection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FEE29CA70F3004483EB /* _HashNode+Structural intersection.swift */; }; + 7DE9216629CA70F4004483EB /* _HashNode+Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FEF29CA70F3004483EB /* _HashNode+Storage.swift */; }; + 7DE9216729CA70F4004483EB /* TreeDictionary+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FF129CA70F3004483EB /* TreeDictionary+Equatable.swift */; }; + 7DE9216829CA70F4004483EB /* TreeDictionary+Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FF229CA70F3004483EB /* TreeDictionary+Sequence.swift */; }; + 7DE9216929CA70F4004483EB /* TreeDictionary+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FF329CA70F3004483EB /* TreeDictionary+Filter.swift */; }; + 7DE9216A29CA70F4004483EB /* TreeDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FF429CA70F3004483EB /* TreeDictionary.swift */; }; + 7DE9216B29CA70F4004483EB /* TreeDictionary+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FF529CA70F3004483EB /* TreeDictionary+Codable.swift */; }; + 7DE9216C29CA70F4004483EB /* TreeDictionary+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FF629CA70F3004483EB /* TreeDictionary+Descriptions.swift */; }; + 7DE9216D29CA70F4004483EB /* TreeDictionary+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FF729CA70F3004483EB /* TreeDictionary+Debugging.swift */; }; + 7DE9216E29CA70F4004483EB /* TreeDictionary+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FF829CA70F3004483EB /* TreeDictionary+Hashable.swift */; }; + 7DE9216F29CA70F4004483EB /* TreeDictionary+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FF929CA70F3004483EB /* TreeDictionary+CustomReflectable.swift */; }; + 7DE9217029CA70F4004483EB /* TreeDictionary+ExpressibleByDictionaryLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FFA29CA70F3004483EB /* TreeDictionary+ExpressibleByDictionaryLiteral.swift */; }; + 7DE9217129CA70F4004483EB /* TreeDictionary+Values.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FFB29CA70F3004483EB /* TreeDictionary+Values.swift */; }; + 7DE9217229CA70F4004483EB /* TreeDictionary+Sendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FFC29CA70F3004483EB /* TreeDictionary+Sendable.swift */; }; + 7DE9217329CA70F4004483EB /* TreeDictionary+Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FFD29CA70F3004483EB /* TreeDictionary+Merge.swift */; }; + 7DE9217429CA70F4004483EB /* TreeDictionary+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FFE29CA70F3004483EB /* TreeDictionary+Collection.swift */; }; + 7DE9217529CA70F4004483EB /* TreeDictionary+MapValues.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FFF29CA70F3004483EB /* TreeDictionary+MapValues.swift */; }; + 7DE9217629CA70F4004483EB /* TreeDictionary+Initializers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE9200029CA70F3004483EB /* TreeDictionary+Initializers.swift */; }; + 7DE9217729CA70F4004483EB /* TreeDictionary+Keys.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE9200129CA70F3004483EB /* TreeDictionary+Keys.swift */; }; + 7DE9217929CA70F4004483EB /* Heap+UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE9200429CA70F3004483EB /* Heap+UnsafeHandle.swift */; }; + 7DE9217A29CA70F4004483EB /* Heap+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE9200529CA70F3004483EB /* Heap+Descriptions.swift */; }; + 7DE9217B29CA70F4004483EB /* Heap+Invariants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE9200629CA70F3004483EB /* Heap+Invariants.swift */; }; + 7DE9217D29CA70F4004483EB /* Heap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE9200829CA70F3004483EB /* Heap.swift */; }; + 7DE9217E29CA70F4004483EB /* Heap+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE9200929CA70F3004483EB /* Heap+ExpressibleByArrayLiteral.swift */; }; + 7DE9217F29CA70F4004483EB /* _HeapNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE9200A29CA70F3004483EB /* _HeapNode.swift */; }; + 7DE921B929CA81DC004483EB /* _SortedCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F3029CA70F3004483EB /* _SortedCollection.swift */; }; + 7DE921C829CA81DC004483EB /* _UniqueCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F3829CA70F3004483EB /* _UniqueCollection.swift */; }; + 7DE921FA29CA8576004483EB /* UtilitiesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921CC29CA8575004483EB /* UtilitiesTests.swift */; }; + 7DE921FB29CA8576004483EB /* MinimalTypeConformances.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921CD29CA8575004483EB /* MinimalTypeConformances.swift */; }; + 7DE921FC29CA8576004483EB /* IndexRangeCollectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921CE29CA8575004483EB /* IndexRangeCollectionTests.swift */; }; + 7DE921FD29CA8576004483EB /* CombinatoricsChecks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921CF29CA8575004483EB /* CombinatoricsChecks.swift */; }; + 7DE921FE29CA8576004483EB /* Hash.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921D129CA8575004483EB /* Hash.swift */; }; + 7DE921FF29CA8576004483EB /* Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921D229CA8575004483EB /* Utilities.swift */; }; + 7DE9220029CA8576004483EB /* TreeDictionary Smoke Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921D329CA8575004483EB /* TreeDictionary Smoke Tests.swift */; }; + 7DE9220129CA8576004483EB /* TreeDictionary.Keys Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921D429CA8575004483EB /* TreeDictionary.Keys Tests.swift */; }; + 7DE9220229CA8576004483EB /* TreeDictionary Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921D529CA8575004483EB /* TreeDictionary Tests.swift */; }; + 7DE9220329CA8576004483EB /* Colliders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921D629CA8575004483EB /* Colliders.swift */; }; + 7DE9220429CA8576004483EB /* TreeHashedCollections Fixtures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921D729CA8575004483EB /* TreeHashedCollections Fixtures.swift */; }; + 7DE9220529CA8576004483EB /* TreeDictionary.Values Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921D829CA8575004483EB /* TreeDictionary.Values Tests.swift */; }; + 7DE9220629CA8576004483EB /* TreeSet Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921D929CA8575004483EB /* TreeSet Tests.swift */; }; + 7DE9220729CA8576004483EB /* BitSet.Counted Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921DB29CA8575004483EB /* BitSet.Counted Tests.swift */; }; + 7DE9220829CA8576004483EB /* BitSetTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921DC29CA8575004483EB /* BitSetTests.swift */; }; + 7DE9220929CA8576004483EB /* BitArrayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921DD29CA8575004483EB /* BitArrayTests.swift */; }; + 7DE9220A29CA8576004483EB /* TestRope.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921DF29CA8575004483EB /* TestRope.swift */; }; + 7DE9220C29CA8576004483EB /* Availability.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921E129CA8575004483EB /* Availability.swift */; }; + 7DE9220D29CA8576004483EB /* TestBigString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921E229CA8575004483EB /* TestBigString.swift */; }; + 7DE9220E29CA8576004483EB /* SampleStrings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921E329CA8575004483EB /* SampleStrings.swift */; }; + 7DE9220F29CA8576004483EB /* OrderedDictionary Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921E629CA8575004483EB /* OrderedDictionary Tests.swift */; }; + 7DE9221029CA8576004483EB /* OrderedDictionary Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921E729CA8575004483EB /* OrderedDictionary Utils.swift */; }; + 7DE9221129CA8576004483EB /* OrderedDictionary+Values Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921E829CA8575004483EB /* OrderedDictionary+Values Tests.swift */; }; + 7DE9221229CA8576004483EB /* OrderedDictionary+Elements Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921E929CA8575004483EB /* OrderedDictionary+Elements Tests.swift */; }; + 7DE9221329CA8576004483EB /* OrderedSetInternals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921EB29CA8575004483EB /* OrderedSetInternals.swift */; }; + 7DE9221429CA8576004483EB /* OrderedSet Diffing Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921EC29CA8575004483EB /* OrderedSet Diffing Tests.swift */; }; + 7DE9221529CA8576004483EB /* RandomAccessCollection+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921ED29CA8575004483EB /* RandomAccessCollection+Extras.swift */; }; + 7DE9221629CA8576004483EB /* OrderedSet.UnorderedView Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921EE29CA8575004483EB /* OrderedSet.UnorderedView Tests.swift */; }; + 7DE9221729CA8576004483EB /* OrderedSetTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921EF29CA8575004483EB /* OrderedSetTests.swift */; }; + 7DE9221829CA8576004483EB /* HashTableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921F129CA8575004483EB /* HashTableTests.swift */; }; + 7DE9221929CA8576004483EB /* HeapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921F329CA8575004483EB /* HeapTests.swift */; }; + 7DE9221A29CA8576004483EB /* HeapNodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921F429CA8575004483EB /* HeapNodeTests.swift */; }; + 7DE9221B29CA8576004483EB /* DequeInternals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921F629CA8576004483EB /* DequeInternals.swift */; }; + 7DE9221C29CA8576004483EB /* RangeReplaceableCollectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921F729CA8576004483EB /* RangeReplaceableCollectionTests.swift */; }; + 7DE9221D29CA8576004483EB /* DequeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921F829CA8576004483EB /* DequeTests.swift */; }; + 7DE9221E29CA8576004483EB /* MutableCollectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE921F929CA8576004483EB /* MutableCollectionTests.swift */; }; + 7DEBDAF229CBEE5300ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDACD29CBEE5200ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift */; }; + 7DEBDAF329CBEE5300ADC226 /* Array+WithContiguousStorage Compatibility.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDACE29CBEE5200ADC226 /* Array+WithContiguousStorage Compatibility.swift */; }; + 7DEBDAF429CBEE5300ADC226 /* UnsafeMutablePointer+SE-0370.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDACF29CBEE5200ADC226 /* UnsafeMutablePointer+SE-0370.swift */; }; + 7DEBDAF529CBEE5300ADC226 /* UnsafeRawPointer extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD029CBEE5200ADC226 /* UnsafeRawPointer extensions.swift */; }; + 7DEBDAF829CBEE5300ADC226 /* UnsafeMutableBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD429CBEE5300ADC226 /* UnsafeMutableBufferPointer+Extras.swift */; }; + 7DEBDAF929CBEE5300ADC226 /* UnsafeBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD529CBEE5300ADC226 /* UnsafeBufferPointer+Extras.swift */; }; + 7DEBDAFA29CBEE5300ADC226 /* RandomAccessCollection+Offsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD629CBEE5300ADC226 /* RandomAccessCollection+Offsets.swift */; }; + 7DEBDAFB29CBEE5300ADC226 /* Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD729CBEE5300ADC226 /* Descriptions.swift */; }; + 7DEBDAFC29CBEE5300ADC226 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD829CBEE5300ADC226 /* Debugging.swift */; }; + 7DEBDB0129CBEE5300ADC226 /* _UnsafeBitSet+Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDADF29CBEE5300ADC226 /* _UnsafeBitSet+Index.swift */; }; + 7DEBDB0229CBEE5300ADC226 /* _UnsafeBitSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAE029CBEE5300ADC226 /* _UnsafeBitSet.swift */; }; + 7DEBDB0329CBEE5300ADC226 /* _UnsafeBitSet+_Word.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAE129CBEE5300ADC226 /* _UnsafeBitSet+_Word.swift */; }; + 7DEBDB0829CBEE5300ADC226 /* UInt+reversed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAE829CBEE5300ADC226 /* UInt+reversed.swift */; }; + 7DEBDB0929CBEE5300ADC226 /* Integer rank.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAE929CBEE5300ADC226 /* Integer rank.swift */; }; + 7DEBDB0A29CBEE5300ADC226 /* UInt+first and last set bit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAEA29CBEE5300ADC226 /* UInt+first and last set bit.swift */; }; + 7DEBDB0B29CBEE5300ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAEB29CBEE5300ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */; }; + 7DEBDB0E29CBF68900ADC226 /* Integer rank.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAE929CBEE5300ADC226 /* Integer rank.swift */; }; + 7DEBDB0F29CBF68900ADC226 /* UInt+reversed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAE829CBEE5300ADC226 /* UInt+reversed.swift */; }; + 7DEBDB1029CBF68900ADC226 /* UInt+first and last set bit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAEA29CBEE5300ADC226 /* UInt+first and last set bit.swift */; }; + 7DEBDB1129CBF68900ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAEB29CBEE5300ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */; }; + 7DEBDB1229CBF68D00ADC226 /* UnsafeMutablePointer+SE-0370.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDACF29CBEE5200ADC226 /* UnsafeMutablePointer+SE-0370.swift */; }; + 7DEBDB1329CBF68D00ADC226 /* Array+WithContiguousStorage Compatibility.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDACE29CBEE5200ADC226 /* Array+WithContiguousStorage Compatibility.swift */; }; + 7DEBDB1429CBF68D00ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDACD29CBEE5200ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift */; }; + 7DEBDB1529CBF68D00ADC226 /* UnsafeRawPointer extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD029CBEE5200ADC226 /* UnsafeRawPointer extensions.swift */; }; + 7DEBDB1629CBF69F00ADC226 /* _UnsafeBitSet+Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDADF29CBEE5300ADC226 /* _UnsafeBitSet+Index.swift */; }; + 7DEBDB1729CBF69F00ADC226 /* _UnsafeBitSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAE029CBEE5300ADC226 /* _UnsafeBitSet.swift */; }; + 7DEBDB1829CBF69F00ADC226 /* _UnsafeBitSet+_Word.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAE129CBEE5300ADC226 /* _UnsafeBitSet+_Word.swift */; }; + 7DEBDB1A29CBF6B200ADC226 /* Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD729CBEE5300ADC226 /* Descriptions.swift */; }; + 7DEBDB1B29CBF6B200ADC226 /* UnsafeBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD529CBEE5300ADC226 /* UnsafeBufferPointer+Extras.swift */; }; + 7DEBDB1C29CBF6B200ADC226 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD829CBEE5300ADC226 /* Debugging.swift */; }; + 7DEBDB1D29CBF6B200ADC226 /* RandomAccessCollection+Offsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD629CBEE5300ADC226 /* RandomAccessCollection+Offsets.swift */; }; + 7DEBDB1E29CBF6B200ADC226 /* UnsafeMutableBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDAD429CBEE5300ADC226 /* UnsafeMutableBufferPointer+Extras.swift */; }; + 7DEBDB6E29CCE44A00ADC226 /* SortedCollectionAPIChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3029CCE43600ADC226 /* SortedCollectionAPIChecker.swift */; }; + 7DEBDB6F29CCE44A00ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3F29CCE43600ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift */; }; + 7DEBDB7029CCE44A00ADC226 /* ResettableValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4229CCE43600ADC226 /* ResettableValue.swift */; }; + 7DEBDB7129CCE44A00ADC226 /* MinimalEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4429CCE43600ADC226 /* MinimalEncoder.swift */; }; + 7DEBDB7229CCE44A00ADC226 /* MinimalBidirectionalCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4029CCE43600ADC226 /* MinimalBidirectionalCollection.swift */; }; + 7DEBDB7329CCE44A00ADC226 /* _MinimalCollectionCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4629CCE43600ADC226 /* _MinimalCollectionCore.swift */; }; + 7DEBDB7429CCE44A00ADC226 /* DictionaryAPIChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2A29CCE43600ADC226 /* DictionaryAPIChecker.swift */; }; + 7DEBDB7529CCE44A00ADC226 /* MinimalCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4829CCE43600ADC226 /* MinimalCollection.swift */; }; + 7DEBDB7629CCE44A00ADC226 /* MinimalIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4129CCE43600ADC226 /* MinimalIndex.swift */; }; + 7DEBDB7729CCE44A00ADC226 /* HashableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3129CCE43600ADC226 /* HashableBox.swift */; }; + 7DEBDB7829CCE44A00ADC226 /* Assertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2329CCE43600ADC226 /* Assertions.swift */; }; + 7DEBDB7929CCE44A00ADC226 /* LifetimeTracked.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2729CCE43600ADC226 /* LifetimeTracked.swift */; }; + 7DEBDB7A29CCE44A00ADC226 /* SetAPIChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3229CCE43600ADC226 /* SetAPIChecker.swift */; }; + 7DEBDB7B29CCE44A00ADC226 /* IndexRangeCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2829CCE43600ADC226 /* IndexRangeCollection.swift */; }; + 7DEBDB7C29CCE44A00ADC226 /* MinimalDecoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4729CCE43600ADC226 /* MinimalDecoder.swift */; }; + 7DEBDB7D29CCE44A00ADC226 /* MinimalRangeReplaceableRandomAccessCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4329CCE43600ADC226 /* MinimalRangeReplaceableRandomAccessCollection.swift */; }; + 7DEBDB7E29CCE44A00ADC226 /* CheckComparable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3629CCE43600ADC226 /* CheckComparable.swift */; }; + 7DEBDB7F29CCE44A00ADC226 /* CheckBidirectionalCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3929CCE43600ADC226 /* CheckBidirectionalCollection.swift */; }; + 7DEBDB8029CCE44A00ADC226 /* MinimalRandomAccessCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3C29CCE43600ADC226 /* MinimalRandomAccessCollection.swift */; }; + 7DEBDB8129CCE44A00ADC226 /* CheckCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3429CCE43600ADC226 /* CheckCollection.swift */; }; + 7DEBDB8229CCE44A00ADC226 /* RepeatableRandomNumberGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2F29CCE43600ADC226 /* RepeatableRandomNumberGenerator.swift */; }; + 7DEBDB8329CCE44A00ADC226 /* CheckHashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3529CCE43600ADC226 /* CheckHashable.swift */; }; + 7DEBDB8429CCE44A00ADC226 /* CheckSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3829CCE43600ADC226 /* CheckSequence.swift */; }; + 7DEBDB8529CCE44A00ADC226 /* AllOnesRandomNumberGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2C29CCE43600ADC226 /* AllOnesRandomNumberGenerator.swift */; }; + 7DEBDB8629CCE44A00ADC226 /* LifetimeTracker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2E29CCE43600ADC226 /* LifetimeTracker.swift */; }; + 7DEBDB8729CCE44A00ADC226 /* MinimalMutableRandomAccessCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3D29CCE43600ADC226 /* MinimalMutableRandomAccessCollection.swift */; }; + 7DEBDB8829CCE44A00ADC226 /* MinimalSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3E29CCE43600ADC226 /* MinimalSequence.swift */; }; + 7DEBDB8929CCE44A00ADC226 /* Combinatorics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2129CCE43600ADC226 /* Combinatorics.swift */; }; + 7DEBDB8A29CCE44A00ADC226 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2D29CCE43600ADC226 /* Box.swift */; }; + 7DEBDB8B29CCE44A00ADC226 /* _CollectionState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3B29CCE43600ADC226 /* _CollectionState.swift */; }; + 7DEBDB8C29CCE44A00ADC226 /* MinimalIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4529CCE43600ADC226 /* MinimalIterator.swift */; }; + 7DEBDB8D29CCE44A00ADC226 /* RandomStableSample.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2629CCE43600ADC226 /* RandomStableSample.swift */; }; + 7DEBDB8E29CCE44A00ADC226 /* Integer Square Root.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2929CCE43600ADC226 /* Integer Square Root.swift */; }; + 7DEBDB8F29CCE44A00ADC226 /* CheckEquatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3729CCE43600ADC226 /* CheckEquatable.swift */; }; + 7DEBDB9029CCE44A00ADC226 /* TestContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2229CCE43600ADC226 /* TestContext.swift */; }; + 7DEBDB9129CCE44A00ADC226 /* CollectionTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2429CCE43600ADC226 /* CollectionTestCase.swift */; }; + 7DEBDB9229CCE44A00ADC226 /* StringConvertibleValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB2B29CCE43600ADC226 /* StringConvertibleValue.swift */; }; + 7DEBDB9D29CCE73D00ADC226 /* Collections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7B29CA70F3004483EB /* Collections.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 7DE91B3029CA6721004483EB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 7DE91B1D29CA6721004483EB /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7DE91B2529CA6721004483EB; + remoteInfo = Collections; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 7D5A64D229CCE8CC00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; + 7D5A64D329CCEE9A00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; + 7D5A64D429CCEF1500CB2595 /* generate-sources.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "generate-sources.sh"; sourceTree = ""; }; + 7D5A64D529CCEF1500CB2595 /* gyb_utils.py */ = {isa = PBXFileReference; lastKnownFileType = text.script.python; path = gyb_utils.py; sourceTree = ""; }; + 7D5A64D629CCEF1500CB2595 /* gyb */ = {isa = PBXFileReference; lastKnownFileType = text; path = gyb; sourceTree = ""; }; + 7D5A64D729CCEF1500CB2595 /* gyb.py */ = {isa = PBXFileReference; lastKnownFileType = text.script.python; path = gyb.py; sourceTree = ""; }; + 7D5A64D829CCF0FE00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; + 7DE91B2629CA6721004483EB /* Collections.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Collections.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 7DE91B2E29CA6721004483EB /* CollectionsTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CollectionsTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 7DE91E7229CA70F3004483EB /* OrderedCollections.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = OrderedCollections.docc; sourceTree = ""; }; + 7DE91E7329CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7DE91E7529CA70F3004483EB /* OrderedDictionary+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Equatable.swift"; sourceTree = ""; }; + 7DE91E7629CA70F3004483EB /* OrderedDictionary+ExpressibleByDictionaryLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+ExpressibleByDictionaryLiteral.swift"; sourceTree = ""; }; + 7DE91E7729CA70F3004483EB /* OrderedDictionary+Hashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Hashable.swift"; sourceTree = ""; }; + 7DE91E7829CA70F3004483EB /* OrderedDictionary+Deprecations.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Deprecations.swift"; sourceTree = ""; }; + 7DE91E7929CA70F3004483EB /* OrderedDictionary+Initializers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Initializers.swift"; sourceTree = ""; }; + 7DE91E7A29CA70F3004483EB /* OrderedDictionary+Elements.SubSequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Elements.SubSequence.swift"; sourceTree = ""; }; + 7DE91E7B29CA70F3004483EB /* OrderedDictionary+CustomReflectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+CustomReflectable.swift"; sourceTree = ""; }; + 7DE91E7C29CA70F3004483EB /* OrderedDictionary+Sequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Sequence.swift"; sourceTree = ""; }; + 7DE91E7D29CA70F3004483EB /* OrderedDictionary+Partial RangeReplaceableCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Partial RangeReplaceableCollection.swift"; sourceTree = ""; }; + 7DE91E7E29CA70F3004483EB /* OrderedDictionary+Elements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Elements.swift"; sourceTree = ""; }; + 7DE91E7F29CA70F3004483EB /* OrderedDictionary+Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Codable.swift"; sourceTree = ""; }; + 7DE91E8029CA70F3004483EB /* OrderedDictionary+Invariants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Invariants.swift"; sourceTree = ""; }; + 7DE91E8129CA70F3004483EB /* OrderedDictionary+Values.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Values.swift"; sourceTree = ""; }; + 7DE91E8229CA70F3004483EB /* OrderedDictionary+Sendable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Sendable.swift"; sourceTree = ""; }; + 7DE91E8329CA70F3004483EB /* OrderedDictionary+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Descriptions.swift"; sourceTree = ""; }; + 7DE91E8429CA70F3004483EB /* OrderedDictionary+Partial MutableCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Partial MutableCollection.swift"; sourceTree = ""; }; + 7DE91E8529CA70F3004483EB /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; + 7DE91E8729CA70F3004483EB /* OrderedSet+Partial SetAlgebra symmetricDifference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra symmetricDifference.swift"; sourceTree = ""; }; + 7DE91E8829CA70F3004483EB /* OrderedSet+RandomAccessCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+RandomAccessCollection.swift"; sourceTree = ""; }; + 7DE91E8929CA70F3004483EB /* OrderedSet+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Descriptions.swift"; sourceTree = ""; }; + 7DE91E8A29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isEqualSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra isEqualSet.swift"; sourceTree = ""; }; + 7DE91E8B29CA70F3004483EB /* OrderedSet+Diffing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Diffing.swift"; sourceTree = ""; }; + 7DE91E8C29CA70F3004483EB /* OrderedSet+UnstableInternals.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+UnstableInternals.swift"; sourceTree = ""; }; + 7DE91E8D29CA70F3004483EB /* OrderedSet+Invariants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Invariants.swift"; sourceTree = ""; }; + 7DE91E8E29CA70F3004483EB /* OrderedSet+Hashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Hashable.swift"; sourceTree = ""; }; + 7DE91E8F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSubset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra isStrictSubset.swift"; sourceTree = ""; }; + 7DE91E9029CA70F3004483EB /* OrderedSet+Insertions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Insertions.swift"; sourceTree = ""; }; + 7DE91E9129CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSubset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra isSubset.swift"; sourceTree = ""; }; + 7DE91E9229CA70F3004483EB /* OrderedSet+Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Codable.swift"; sourceTree = ""; }; + 7DE91E9329CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSuperset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra isSuperset.swift"; sourceTree = ""; }; + 7DE91E9429CA70F3004483EB /* OrderedSet+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Equatable.swift"; sourceTree = ""; }; + 7DE91E9529CA70F3004483EB /* OrderedSet+Initializers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Initializers.swift"; sourceTree = ""; }; + 7DE91E9629CA70F3004483EB /* OrderedSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedSet.swift; sourceTree = ""; }; + 7DE91E9729CA70F3004483EB /* OrderedSet+UnorderedView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+UnorderedView.swift"; sourceTree = ""; }; + 7DE91E9829CA70F3004483EB /* OrderedSet+ExpressibleByArrayLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+ExpressibleByArrayLiteral.swift"; sourceTree = ""; }; + 7DE91E9929CA70F3004483EB /* OrderedSet+SubSequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+SubSequence.swift"; sourceTree = ""; }; + 7DE91E9A29CA70F3004483EB /* OrderedSet+Partial MutableCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial MutableCollection.swift"; sourceTree = ""; }; + 7DE91E9B29CA70F3004483EB /* OrderedSet+Sendable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Sendable.swift"; sourceTree = ""; }; + 7DE91E9C29CA70F3004483EB /* OrderedSet+Testing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Testing.swift"; sourceTree = ""; }; + 7DE91E9D29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formUnion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra formUnion.swift"; sourceTree = ""; }; + 7DE91E9E29CA70F3004483EB /* OrderedSet+CustomReflectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+CustomReflectable.swift"; sourceTree = ""; }; + 7DE91E9F29CA70F3004483EB /* OrderedSet+ReserveCapacity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+ReserveCapacity.swift"; sourceTree = ""; }; + 7DE91EA029CA70F3004483EB /* OrderedSet+Partial SetAlgebra union.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra union.swift"; sourceTree = ""; }; + 7DE91EA129CA70F3004483EB /* OrderedSet+Partial SetAlgebra formIntersection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra formIntersection.swift"; sourceTree = ""; }; + 7DE91EA229CA70F3004483EB /* OrderedSet+Partial RangeReplaceableCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial RangeReplaceableCollection.swift"; sourceTree = ""; }; + 7DE91EA329CA70F3004483EB /* OrderedSet+Partial SetAlgebra+Basics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra+Basics.swift"; sourceTree = ""; }; + 7DE91EA429CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtracting.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra subtracting.swift"; sourceTree = ""; }; + 7DE91EA529CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra formSymmetricDifference.swift"; sourceTree = ""; }; + 7DE91EA629CA70F3004483EB /* OrderedSet+Partial SetAlgebra intersection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra intersection.swift"; sourceTree = ""; }; + 7DE91EA729CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtract.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra subtract.swift"; sourceTree = ""; }; + 7DE91EA829CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra isDisjoint.swift"; sourceTree = ""; }; + 7DE91EA929CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSuperset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Partial SetAlgebra isStrictSuperset.swift"; sourceTree = ""; }; + 7DE91EAB29CA70F3004483EB /* _UnsafeBitset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _UnsafeBitset.swift; sourceTree = ""; }; + 7DE91EAD29CA70F3004483EB /* _HashTable+UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashTable+UnsafeHandle.swift"; sourceTree = ""; }; + 7DE91EAE29CA70F3004483EB /* _HashTable+Bucket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashTable+Bucket.swift"; sourceTree = ""; }; + 7DE91EAF29CA70F3004483EB /* _HashTable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _HashTable.swift; sourceTree = ""; }; + 7DE91EB029CA70F3004483EB /* _HashTable+Constants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashTable+Constants.swift"; sourceTree = ""; }; + 7DE91EB129CA70F3004483EB /* _Hashtable+Header.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_Hashtable+Header.swift"; sourceTree = ""; }; + 7DE91EB229CA70F3004483EB /* _HashTable+Testing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashTable+Testing.swift"; sourceTree = ""; }; + 7DE91EB329CA70F3004483EB /* _HashTable+CustomStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashTable+CustomStringConvertible.swift"; sourceTree = ""; }; + 7DE91EB429CA70F3004483EB /* _HashTable+BucketIterator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashTable+BucketIterator.swift"; sourceTree = ""; }; + 7DE91EB529CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7DE91EB729CA70F3004483EB /* _DequeBuffer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _DequeBuffer.swift; sourceTree = ""; }; + 7DE91EB829CA70F3004483EB /* Deque+Collection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Collection.swift"; sourceTree = ""; }; + 7DE91EB929CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7DE91EBA29CA70F3004483EB /* Deque+CustomReflectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+CustomReflectable.swift"; sourceTree = ""; }; + 7DE91EBB29CA70F3004483EB /* Deque.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Deque.swift; sourceTree = ""; }; + 7DE91EBC29CA70F3004483EB /* _DequeSlot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _DequeSlot.swift; sourceTree = ""; }; + 7DE91EBD29CA70F3004483EB /* Deque+Hashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Hashable.swift"; sourceTree = ""; }; + 7DE91EBE29CA70F3004483EB /* _UnsafeWrappedBuffer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _UnsafeWrappedBuffer.swift; sourceTree = ""; }; + 7DE91EBF29CA70F3004483EB /* _DequeBufferHeader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _DequeBufferHeader.swift; sourceTree = ""; }; + 7DE91EC029CA70F3004483EB /* Deque+Sendable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Sendable.swift"; sourceTree = ""; }; + 7DE91EC129CA70F3004483EB /* Deque+Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Codable.swift"; sourceTree = ""; }; + 7DE91EC229CA70F3004483EB /* Deque+Testing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Testing.swift"; sourceTree = ""; }; + 7DE91EC329CA70F3004483EB /* DequeModule.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = DequeModule.docc; sourceTree = ""; }; + 7DE91EC429CA70F3004483EB /* Deque._UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Deque._UnsafeHandle.swift; sourceTree = ""; }; + 7DE91EC529CA70F3004483EB /* Deque+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Descriptions.swift"; sourceTree = ""; }; + 7DE91EC629CA70F3004483EB /* Deque+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Extras.swift"; sourceTree = ""; }; + 7DE91EC729CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+ExpressibleByArrayLiteral.swift"; sourceTree = ""; }; + 7DE91EC829CA70F3004483EB /* Deque+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Deque+Equatable.swift"; sourceTree = ""; }; + 7DE91EC929CA70F3004483EB /* Deque._Storage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Deque._Storage.swift; sourceTree = ""; }; + 7DE91ECD29CA70F3004483EB /* BigString+Metrics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Metrics.swift"; sourceTree = ""; }; + 7DE91ECE29CA70F3004483EB /* BigString+Index.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Index.swift"; sourceTree = ""; }; + 7DE91ECF29CA70F3004483EB /* BigString+Summary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Summary.swift"; sourceTree = ""; }; + 7DE91ED029CA70F3004483EB /* BigString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BigString.swift; sourceTree = ""; }; + 7DE91ED129CA70F3004483EB /* BigString+Iterators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Iterators.swift"; sourceTree = ""; }; + 7DE91ED229CA70F3004483EB /* BigString+Contents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Contents.swift"; sourceTree = ""; }; + 7DE91ED329CA70F3004483EB /* BigString+Invariants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Invariants.swift"; sourceTree = ""; }; + 7DE91ED429CA70F3004483EB /* BigString+Ingester.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Ingester.swift"; sourceTree = ""; }; + 7DE91ED529CA70F3004483EB /* BigString+Debugging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Debugging.swift"; sourceTree = ""; }; + 7DE91ED629CA70F3004483EB /* BigString+Builder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Builder.swift"; sourceTree = ""; }; + 7DE91ED829CA70F3004483EB /* BigString+Chunk+Append and Insert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Append and Insert.swift"; sourceTree = ""; }; + 7DE91ED929CA70F3004483EB /* BigString+Chunk+Indexing by UTF16.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Indexing by UTF16.swift"; sourceTree = ""; }; + 7DE91EDA29CA70F3004483EB /* BigString+Chunk+Counts.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Counts.swift"; sourceTree = ""; }; + 7DE91EDB29CA70F3004483EB /* BigString+Chunk+Indexing by Characters.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Indexing by Characters.swift"; sourceTree = ""; }; + 7DE91EDC29CA70F3004483EB /* BigString+Chunk.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk.swift"; sourceTree = ""; }; + 7DE91EDD29CA70F3004483EB /* BigString+Chunk+Description.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Description.swift"; sourceTree = ""; }; + 7DE91EDE29CA70F3004483EB /* BigString+Chunk+Splitting.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Splitting.swift"; sourceTree = ""; }; + 7DE91EDF29CA70F3004483EB /* BigString+Chunk+Breaks.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Breaks.swift"; sourceTree = ""; }; + 7DE91EE029CA70F3004483EB /* BigString+Chunk+RopeElement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+RopeElement.swift"; sourceTree = ""; }; + 7DE91EE229CA70F3004483EB /* BigString+Split.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Split.swift"; sourceTree = ""; }; + 7DE91EE329CA70F3004483EB /* BigString+Managing Breaks.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Managing Breaks.swift"; sourceTree = ""; }; + 7DE91EE429CA70F3004483EB /* BigString+RemoveSubrange.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+RemoveSubrange.swift"; sourceTree = ""; }; + 7DE91EE529CA70F3004483EB /* BigString+ReplaceSubrange.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+ReplaceSubrange.swift"; sourceTree = ""; }; + 7DE91EE629CA70F3004483EB /* BigString+Insert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Insert.swift"; sourceTree = ""; }; + 7DE91EE729CA70F3004483EB /* BigString+Initializers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Initializers.swift"; sourceTree = ""; }; + 7DE91EE829CA70F3004483EB /* Range+BigString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Range+BigString.swift"; sourceTree = ""; }; + 7DE91EE929CA70F3004483EB /* BigString+Append.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Append.swift"; sourceTree = ""; }; + 7DE91EEB29CA70F3004483EB /* BigString+UnicodeScalarView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+UnicodeScalarView.swift"; sourceTree = ""; }; + 7DE91EEC29CA70F3004483EB /* BigString+UTF8View.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+UTF8View.swift"; sourceTree = ""; }; + 7DE91EED29CA70F3004483EB /* BigSubstring+UnicodeScalarView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigSubstring+UnicodeScalarView.swift"; sourceTree = ""; }; + 7DE91EEE29CA70F3004483EB /* BigSubstring.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BigSubstring.swift; sourceTree = ""; }; + 7DE91EEF29CA70F3004483EB /* BigSubstring+UTF16View.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigSubstring+UTF16View.swift"; sourceTree = ""; }; + 7DE91EF029CA70F3004483EB /* BigString+UTF16View.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+UTF16View.swift"; sourceTree = ""; }; + 7DE91EF129CA70F3004483EB /* BigSubstring+UTF8View.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigSubstring+UTF8View.swift"; sourceTree = ""; }; + 7DE91EF329CA70F3004483EB /* BigString+Hashing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Hashing.swift"; sourceTree = ""; }; + 7DE91EF429CA70F3004483EB /* BigString+CustomStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+CustomStringConvertible.swift"; sourceTree = ""; }; + 7DE91EF529CA70F3004483EB /* BigString+BidirectionalCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+BidirectionalCollection.swift"; sourceTree = ""; }; + 7DE91EF629CA70F3004483EB /* BigString+CustomDebugStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+CustomDebugStringConvertible.swift"; sourceTree = ""; }; + 7DE91EF729CA70F3004483EB /* BigString+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Equatable.swift"; sourceTree = ""; }; + 7DE91EF829CA70F3004483EB /* BigString+TextOutputStream.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+TextOutputStream.swift"; sourceTree = ""; }; + 7DE91EF929CA70F3004483EB /* BigString+LosslessStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+LosslessStringConvertible.swift"; sourceTree = ""; }; + 7DE91EFA29CA70F3004483EB /* BigString+Sequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Sequence.swift"; sourceTree = ""; }; + 7DE91EFB29CA70F3004483EB /* BigString+ExpressibleByStringLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+ExpressibleByStringLiteral.swift"; sourceTree = ""; }; + 7DE91EFC29CA70F3004483EB /* BigString+RangeReplaceableCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+RangeReplaceableCollection.swift"; sourceTree = ""; }; + 7DE91EFD29CA70F3004483EB /* BigString+Comparable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BigString+Comparable.swift"; sourceTree = ""; }; + 7DE91F0029CA70F3004483EB /* RopeMetric.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RopeMetric.swift; sourceTree = ""; }; + 7DE91F0129CA70F3004483EB /* _RopeItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _RopeItem.swift; sourceTree = ""; }; + 7DE91F0229CA70F3004483EB /* Rope+Debugging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Debugging.swift"; sourceTree = ""; }; + 7DE91F0329CA70F3004483EB /* _RopeVersion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _RopeVersion.swift; sourceTree = ""; }; + 7DE91F0429CA70F3004483EB /* RopeElement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RopeElement.swift; sourceTree = ""; }; + 7DE91F0529CA70F3004483EB /* Rope.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Rope.swift; sourceTree = ""; }; + 7DE91F0629CA70F3004483EB /* Rope+_UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+_UnsafeHandle.swift"; sourceTree = ""; }; + 7DE91F0729CA70F3004483EB /* Rope+_Storage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+_Storage.swift"; sourceTree = ""; }; + 7DE91F0829CA70F3004483EB /* Rope+Invariants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Invariants.swift"; sourceTree = ""; }; + 7DE91F0929CA70F3004483EB /* Rope+_UnmanagedLeaf.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+_UnmanagedLeaf.swift"; sourceTree = ""; }; + 7DE91F0A29CA70F3004483EB /* RopeSummary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RopeSummary.swift; sourceTree = ""; }; + 7DE91F0B29CA70F3004483EB /* Rope+Builder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Builder.swift"; sourceTree = ""; }; + 7DE91F0C29CA70F3004483EB /* _RopePath.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _RopePath.swift; sourceTree = ""; }; + 7DE91F0D29CA70F3004483EB /* Rope+_Node.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+_Node.swift"; sourceTree = ""; }; + 7DE91F0F29CA70F3004483EB /* Rope+Extract.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Extract.swift"; sourceTree = ""; }; + 7DE91F1029CA70F3004483EB /* Rope+Append.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Append.swift"; sourceTree = ""; }; + 7DE91F1129CA70F3004483EB /* Rope+Split.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Split.swift"; sourceTree = ""; }; + 7DE91F1229CA70F3004483EB /* Rope+Find.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Find.swift"; sourceTree = ""; }; + 7DE91F1329CA70F3004483EB /* Rope+Insert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Insert.swift"; sourceTree = ""; }; + 7DE91F1429CA70F3004483EB /* Rope+ForEachWhile.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+ForEachWhile.swift"; sourceTree = ""; }; + 7DE91F1529CA70F3004483EB /* Rope+MutatingForEach.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+MutatingForEach.swift"; sourceTree = ""; }; + 7DE91F1629CA70F3004483EB /* Rope+Join.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Join.swift"; sourceTree = ""; }; + 7DE91F1729CA70F3004483EB /* Rope+Remove.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Remove.swift"; sourceTree = ""; }; + 7DE91F1829CA70F3004483EB /* Rope+RemoveSubrange.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+RemoveSubrange.swift"; sourceTree = ""; }; + 7DE91F1A29CA70F3004483EB /* Rope+Index.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Index.swift"; sourceTree = ""; }; + 7DE91F1B29CA70F3004483EB /* Rope+Sequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Sequence.swift"; sourceTree = ""; }; + 7DE91F1C29CA70F3004483EB /* Rope+Collection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rope+Collection.swift"; sourceTree = ""; }; + 7DE91F1E29CA70F3004483EB /* String Utilities.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "String Utilities.swift"; sourceTree = ""; }; + 7DE91F1F29CA70F3004483EB /* _CharacterRecognizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _CharacterRecognizer.swift; sourceTree = ""; }; + 7DE91F2029CA70F3004483EB /* String.Index+ABI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "String.Index+ABI.swift"; sourceTree = ""; }; + 7DE91F2129CA70F3004483EB /* Optional Utilities.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Optional Utilities.swift"; sourceTree = ""; }; + 7DE91F2E29CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7DE91F3029CA70F3004483EB /* _SortedCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _SortedCollection.swift; sourceTree = ""; }; + 7DE91F3829CA70F3004483EB /* _UniqueCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _UniqueCollection.swift; sourceTree = ""; }; + 7DE91F3B29CA70F3004483EB /* BitSet+SetAlgebra symmetricDifference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra symmetricDifference.swift"; sourceTree = ""; }; + 7DE91F3C29CA70F3004483EB /* BitSet+SetAlgebra formIntersection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra formIntersection.swift"; sourceTree = ""; }; + 7DE91F3D29CA70F3004483EB /* BitSet+Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+Codable.swift"; sourceTree = ""; }; + 7DE91F3E29CA70F3004483EB /* BitSet+SetAlgebra conformance.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra conformance.swift"; sourceTree = ""; }; + 7DE91F3F29CA70F3004483EB /* BitSet+SetAlgebra subtract.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra subtract.swift"; sourceTree = ""; }; + 7DE91F4029CA70F3004483EB /* BitSet+Sorted Collection APIs.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+Sorted Collection APIs.swift"; sourceTree = ""; }; + 7DE91F4129CA70F3004483EB /* BitSet+SetAlgebra formUnion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra formUnion.swift"; sourceTree = ""; }; + 7DE91F4229CA70F3004483EB /* BitSet+SetAlgebra isStrictSuperset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra isStrictSuperset.swift"; sourceTree = ""; }; + 7DE91F4329CA70F3004483EB /* BitSet+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+Extras.swift"; sourceTree = ""; }; + 7DE91F4429CA70F3004483EB /* BitSet+SetAlgebra formSymmetricDifference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra formSymmetricDifference.swift"; sourceTree = ""; }; + 7DE91F4529CA70F3004483EB /* BitSet+ExpressibleByArrayLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+ExpressibleByArrayLiteral.swift"; sourceTree = ""; }; + 7DE91F4629CA70F3004483EB /* BitSet+SetAlgebra isEqualSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra isEqualSet.swift"; sourceTree = ""; }; + 7DE91F4729CA70F3004483EB /* BitSet+BidirectionalCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+BidirectionalCollection.swift"; sourceTree = ""; }; + 7DE91F4829CA70F3004483EB /* BitSet+CustomStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+CustomStringConvertible.swift"; sourceTree = ""; }; + 7DE91F4929CA70F3004483EB /* BitSet+Random.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+Random.swift"; sourceTree = ""; }; + 7DE91F4A29CA70F3004483EB /* BitSet.Counted.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitSet.Counted.swift; sourceTree = ""; }; + 7DE91F4B29CA70F3004483EB /* BitSet+CustomDebugStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+CustomDebugStringConvertible.swift"; sourceTree = ""; }; + 7DE91F4C29CA70F3004483EB /* BitSet+CustomReflectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+CustomReflectable.swift"; sourceTree = ""; }; + 7DE91F4D29CA70F3004483EB /* BitSet+Initializers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+Initializers.swift"; sourceTree = ""; }; + 7DE91F4E29CA70F3004483EB /* BitSet+SetAlgebra isSubset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra isSubset.swift"; sourceTree = ""; }; + 7DE91F4F29CA70F3004483EB /* BitSet.Index.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitSet.Index.swift; sourceTree = ""; }; + 7DE91F5029CA70F3004483EB /* BitSet+SetAlgebra basics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra basics.swift"; sourceTree = ""; }; + 7DE91F5129CA70F3004483EB /* BitSet+SetAlgebra isDisjoint.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra isDisjoint.swift"; sourceTree = ""; }; + 7DE91F5229CA70F3004483EB /* BitSet+SetAlgebra union.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra union.swift"; sourceTree = ""; }; + 7DE91F5329CA70F3004483EB /* BitSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitSet.swift; sourceTree = ""; }; + 7DE91F5429CA70F3004483EB /* BitSet+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+Equatable.swift"; sourceTree = ""; }; + 7DE91F5529CA70F3004483EB /* BitSet+SetAlgebra isSuperset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra isSuperset.swift"; sourceTree = ""; }; + 7DE91F5629CA70F3004483EB /* BitSet+SetAlgebra subtracting.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra subtracting.swift"; sourceTree = ""; }; + 7DE91F5729CA70F3004483EB /* BitSet+SetAlgebra intersection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra intersection.swift"; sourceTree = ""; }; + 7DE91F5829CA70F3004483EB /* BitSet._UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitSet._UnsafeHandle.swift; sourceTree = ""; }; + 7DE91F5929CA70F3004483EB /* BitSet+Hashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+Hashable.swift"; sourceTree = ""; }; + 7DE91F5A29CA70F3004483EB /* BitSet+Invariants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+Invariants.swift"; sourceTree = ""; }; + 7DE91F5B29CA70F3004483EB /* BitSet+SetAlgebra isStrictSubset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra isStrictSubset.swift"; sourceTree = ""; }; + 7DE91F5C29CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7DE91F5E29CA70F3004483EB /* Slice+Utilities.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Slice+Utilities.swift"; sourceTree = ""; }; + 7DE91F5F29CA70F3004483EB /* Range+Utilities.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Range+Utilities.swift"; sourceTree = ""; }; + 7DE91F6029CA70F3004483EB /* UInt+Tricks.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UInt+Tricks.swift"; sourceTree = ""; }; + 7DE91F6129CA70F3004483EB /* _Word.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _Word.swift; sourceTree = ""; }; + 7DE91F6229CA70F3004483EB /* BitCollections.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = BitCollections.docc; sourceTree = ""; }; + 7DE91F6529CA70F3004483EB /* BitArray+CustomStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+CustomStringConvertible.swift"; sourceTree = ""; }; + 7DE91F6629CA70F3004483EB /* BitArray+ChunkedBitsIterators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+ChunkedBitsIterators.swift"; sourceTree = ""; }; + 7DE91F6729CA70F3004483EB /* BitArray+CustomReflectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+CustomReflectable.swift"; sourceTree = ""; }; + 7DE91F6829CA70F3004483EB /* BitArray+BitwiseOperations.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+BitwiseOperations.swift"; sourceTree = ""; }; + 7DE91F6929CA70F3004483EB /* BitArray+Invariants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Invariants.swift"; sourceTree = ""; }; + 7DE91F6A29CA70F3004483EB /* BitArray.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitArray.swift; sourceTree = ""; }; + 7DE91F6B29CA70F3004483EB /* BitArray+Fill.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Fill.swift"; sourceTree = ""; }; + 7DE91F6C29CA70F3004483EB /* BitArray+Collection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Collection.swift"; sourceTree = ""; }; + 7DE91F6D29CA70F3004483EB /* BitArray+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Extras.swift"; sourceTree = ""; }; + 7DE91F6E29CA70F3004483EB /* BitArray+ExpressibleByArrayLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+ExpressibleByArrayLiteral.swift"; sourceTree = ""; }; + 7DE91F6F29CA70F3004483EB /* BitArray+Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Codable.swift"; sourceTree = ""; }; + 7DE91F7029CA70F3004483EB /* BitArray+RangeReplaceableCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+RangeReplaceableCollection.swift"; sourceTree = ""; }; + 7DE91F7129CA70F3004483EB /* BitArray+Initializers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Initializers.swift"; sourceTree = ""; }; + 7DE91F7229CA70F3004483EB /* BitArray._UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitArray._UnsafeHandle.swift; sourceTree = ""; }; + 7DE91F7329CA70F3004483EB /* BitArray+Copy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Copy.swift"; sourceTree = ""; }; + 7DE91F7429CA70F3004483EB /* BitArray+Hashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Hashable.swift"; sourceTree = ""; }; + 7DE91F7529CA70F3004483EB /* BitArray+CustomDebugStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+CustomDebugStringConvertible.swift"; sourceTree = ""; }; + 7DE91F7629CA70F3004483EB /* BitArray+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Equatable.swift"; sourceTree = ""; }; + 7DE91F7729CA70F3004483EB /* BitArray+Random.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Random.swift"; sourceTree = ""; }; + 7DE91F7829CA70F3004483EB /* BitArray+Testing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Testing.swift"; sourceTree = ""; }; + 7DE91F7A29CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7DE91F7B29CA70F3004483EB /* Collections.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Collections.swift; sourceTree = ""; }; + 7DE91F7C29CA70F3004483EB /* Collections.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = Collections.docc; sourceTree = ""; }; + 7DE91FA829CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7DE91FA929CA70F3004483EB /* HashTreeCollections.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = HashTreeCollections.docc; sourceTree = ""; }; + 7DE91FAB29CA70F3004483EB /* TreeSet+SetAlgebra isEqualSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra isEqualSet.swift"; sourceTree = ""; }; + 7DE91FAC29CA70F3004483EB /* TreeSet+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Descriptions.swift"; sourceTree = ""; }; + 7DE91FAD29CA70F3004483EB /* TreeSet+SetAlgebra isStrictSubset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra isStrictSubset.swift"; sourceTree = ""; }; + 7DE91FAE29CA70F3004483EB /* TreeSet+Sendable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Sendable.swift"; sourceTree = ""; }; + 7DE91FAF29CA70F3004483EB /* TreeSet+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Equatable.swift"; sourceTree = ""; }; + 7DE91FB029CA70F3004483EB /* TreeSet+SetAlgebra intersection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra intersection.swift"; sourceTree = ""; }; + 7DE91FB129CA70F3004483EB /* TreeSet+SetAlgebra formUnion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra formUnion.swift"; sourceTree = ""; }; + 7DE91FB229CA70F3004483EB /* TreeSet+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Extras.swift"; sourceTree = ""; }; + 7DE91FB329CA70F3004483EB /* TreeSet+SetAlgebra subtracting.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra subtracting.swift"; sourceTree = ""; }; + 7DE91FB429CA70F3004483EB /* TreeSet+SetAlgebra subtract.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra subtract.swift"; sourceTree = ""; }; + 7DE91FB529CA70F3004483EB /* TreeSet+Debugging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Debugging.swift"; sourceTree = ""; }; + 7DE91FB629CA70F3004483EB /* TreeSet+SetAlgebra isStrictSuperset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra isStrictSuperset.swift"; sourceTree = ""; }; + 7DE91FB729CA70F3004483EB /* TreeSet+SetAlgebra formIntersection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra formIntersection.swift"; sourceTree = ""; }; + 7DE91FB829CA70F3004483EB /* TreeSet+SetAlgebra isSuperset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra isSuperset.swift"; sourceTree = ""; }; + 7DE91FB929CA70F3004483EB /* TreeSet+CustomReflectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+CustomReflectable.swift"; sourceTree = ""; }; + 7DE91FBA29CA70F3004483EB /* TreeSet+SetAlgebra formSymmetricDifference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra formSymmetricDifference.swift"; sourceTree = ""; }; + 7DE91FBB29CA70F3004483EB /* TreeSet+Collection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Collection.swift"; sourceTree = ""; }; + 7DE91FBC29CA70F3004483EB /* TreeSet+ExpressibleByArrayLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+ExpressibleByArrayLiteral.swift"; sourceTree = ""; }; + 7DE91FBD29CA70F3004483EB /* TreeSet+SetAlgebra symmetricDifference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra symmetricDifference.swift"; sourceTree = ""; }; + 7DE91FBE29CA70F3004483EB /* TreeSet+SetAlgebra basics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra basics.swift"; sourceTree = ""; }; + 7DE91FBF29CA70F3004483EB /* TreeSet+Sequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Sequence.swift"; sourceTree = ""; }; + 7DE91FC029CA70F3004483EB /* TreeSet+Filter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Filter.swift"; sourceTree = ""; }; + 7DE91FC129CA70F3004483EB /* TreeSet+SetAlgebra Initializers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra Initializers.swift"; sourceTree = ""; }; + 7DE91FC229CA70F3004483EB /* TreeSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TreeSet.swift; sourceTree = ""; }; + 7DE91FC329CA70F3004483EB /* TreeSet+Hashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Hashable.swift"; sourceTree = ""; }; + 7DE91FC429CA70F3004483EB /* TreeSet+Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+Codable.swift"; sourceTree = ""; }; + 7DE91FC529CA70F3004483EB /* TreeSet+SetAlgebra isSubset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra isSubset.swift"; sourceTree = ""; }; + 7DE91FC629CA70F3004483EB /* TreeSet+SetAlgebra union.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra union.swift"; sourceTree = ""; }; + 7DE91FC729CA70F3004483EB /* TreeSet+SetAlgebra isDisjoint.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet+SetAlgebra isDisjoint.swift"; sourceTree = ""; }; + 7DE91FC929CA70F3004483EB /* _Hash.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _Hash.swift; sourceTree = ""; }; + 7DE91FCA29CA70F3004483EB /* _HashNode+Initializers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Initializers.swift"; sourceTree = ""; }; + 7DE91FCB29CA70F3004483EB /* _HashStack.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _HashStack.swift; sourceTree = ""; }; + 7DE91FCC29CA70F3004483EB /* _HashNode+Subtree Removals.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Subtree Removals.swift"; sourceTree = ""; }; + 7DE91FCD29CA70F3004483EB /* _HashTreeIterator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _HashTreeIterator.swift; sourceTree = ""; }; + 7DE91FCE29CA70F3004483EB /* _HashNode+Structural symmetricDifference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural symmetricDifference.swift"; sourceTree = ""; }; + 7DE91FCF29CA70F3004483EB /* _HashSlot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _HashSlot.swift; sourceTree = ""; }; + 7DE91FD029CA70F3004483EB /* _HashNode+Primitive Replacement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Primitive Replacement.swift"; sourceTree = ""; }; + 7DE91FD129CA70F3004483EB /* _HashNode+Primitive Removals.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Primitive Removals.swift"; sourceTree = ""; }; + 7DE91FD229CA70F3004483EB /* _HashNode+Structural isEqualSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural isEqualSet.swift"; sourceTree = ""; }; + 7DE91FD329CA70F3004483EB /* _HashNode+Subtree Insertions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Subtree Insertions.swift"; sourceTree = ""; }; + 7DE91FD429CA70F3004483EB /* _HashTreeStatistics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _HashTreeStatistics.swift; sourceTree = ""; }; + 7DE91FD529CA70F3004483EB /* _HashNode+Primitive Insertions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Primitive Insertions.swift"; sourceTree = ""; }; + 7DE91FD629CA70F3004483EB /* _HashNode+Structural filter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural filter.swift"; sourceTree = ""; }; + 7DE91FD729CA70F3004483EB /* _HashNode+Debugging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Debugging.swift"; sourceTree = ""; }; + 7DE91FD829CA70F3004483EB /* _Bucket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _Bucket.swift; sourceTree = ""; }; + 7DE91FD929CA70F3004483EB /* _UnmanagedHashNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _UnmanagedHashNode.swift; sourceTree = ""; }; + 7DE91FDA29CA70F3004483EB /* _HashNode+Subtree Modify.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Subtree Modify.swift"; sourceTree = ""; }; + 7DE91FDB29CA70F3004483EB /* _HashNode+Builder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Builder.swift"; sourceTree = ""; }; + 7DE91FDC29CA70F3004483EB /* _HashNode+Invariants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Invariants.swift"; sourceTree = ""; }; + 7DE91FDD29CA70F3004483EB /* _HashNode+UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+UnsafeHandle.swift"; sourceTree = ""; }; + 7DE91FDE29CA70F3004483EB /* _RawHashNode+UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_RawHashNode+UnsafeHandle.swift"; sourceTree = ""; }; + 7DE91FDF29CA70F3004483EB /* _HashNode+Structural compactMapValues.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural compactMapValues.swift"; sourceTree = ""; }; + 7DE91FE029CA70F3004483EB /* _RawHashNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _RawHashNode.swift; sourceTree = ""; }; + 7DE91FE129CA70F3004483EB /* _HashNode+Structural union.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural union.swift"; sourceTree = ""; }; + 7DE91FE229CA70F3004483EB /* _HashNode+Structural isSubset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural isSubset.swift"; sourceTree = ""; }; + 7DE91FE329CA70F3004483EB /* _HashNode+Structural subtracting.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural subtracting.swift"; sourceTree = ""; }; + 7DE91FE429CA70F3004483EB /* _HashNode+Structural mapValues.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural mapValues.swift"; sourceTree = ""; }; + 7DE91FE529CA70F3004483EB /* _Bitmap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _Bitmap.swift; sourceTree = ""; }; + 7DE91FE629CA70F3004483EB /* _StorageHeader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _StorageHeader.swift; sourceTree = ""; }; + 7DE91FE729CA70F3004483EB /* _HashNode+Lookups.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Lookups.swift"; sourceTree = ""; }; + 7DE91FE829CA70F3004483EB /* _UnsafePath.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _UnsafePath.swift; sourceTree = ""; }; + 7DE91FE929CA70F3004483EB /* _HashNode+Structural isDisjoint.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural isDisjoint.swift"; sourceTree = ""; }; + 7DE91FEA29CA70F3004483EB /* _HashNode+Structural merge.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural merge.swift"; sourceTree = ""; }; + 7DE91FEB29CA70F3004483EB /* _AncestorHashSlots.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _AncestorHashSlots.swift; sourceTree = ""; }; + 7DE91FEC29CA70F3004483EB /* _HashLevel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _HashLevel.swift; sourceTree = ""; }; + 7DE91FED29CA70F3004483EB /* _HashNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _HashNode.swift; sourceTree = ""; }; + 7DE91FEE29CA70F3004483EB /* _HashNode+Structural intersection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Structural intersection.swift"; sourceTree = ""; }; + 7DE91FEF29CA70F3004483EB /* _HashNode+Storage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_HashNode+Storage.swift"; sourceTree = ""; }; + 7DE91FF129CA70F3004483EB /* TreeDictionary+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Equatable.swift"; sourceTree = ""; }; + 7DE91FF229CA70F3004483EB /* TreeDictionary+Sequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Sequence.swift"; sourceTree = ""; }; + 7DE91FF329CA70F3004483EB /* TreeDictionary+Filter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Filter.swift"; sourceTree = ""; }; + 7DE91FF429CA70F3004483EB /* TreeDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TreeDictionary.swift; sourceTree = ""; }; + 7DE91FF529CA70F3004483EB /* TreeDictionary+Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Codable.swift"; sourceTree = ""; }; + 7DE91FF629CA70F3004483EB /* TreeDictionary+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Descriptions.swift"; sourceTree = ""; }; + 7DE91FF729CA70F3004483EB /* TreeDictionary+Debugging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Debugging.swift"; sourceTree = ""; }; + 7DE91FF829CA70F3004483EB /* TreeDictionary+Hashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Hashable.swift"; sourceTree = ""; }; + 7DE91FF929CA70F3004483EB /* TreeDictionary+CustomReflectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+CustomReflectable.swift"; sourceTree = ""; }; + 7DE91FFA29CA70F3004483EB /* TreeDictionary+ExpressibleByDictionaryLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+ExpressibleByDictionaryLiteral.swift"; sourceTree = ""; }; + 7DE91FFB29CA70F3004483EB /* TreeDictionary+Values.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Values.swift"; sourceTree = ""; }; + 7DE91FFC29CA70F3004483EB /* TreeDictionary+Sendable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Sendable.swift"; sourceTree = ""; }; + 7DE91FFD29CA70F3004483EB /* TreeDictionary+Merge.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Merge.swift"; sourceTree = ""; }; + 7DE91FFE29CA70F3004483EB /* TreeDictionary+Collection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Collection.swift"; sourceTree = ""; }; + 7DE91FFF29CA70F3004483EB /* TreeDictionary+MapValues.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+MapValues.swift"; sourceTree = ""; }; + 7DE9200029CA70F3004483EB /* TreeDictionary+Initializers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Initializers.swift"; sourceTree = ""; }; + 7DE9200129CA70F3004483EB /* TreeDictionary+Keys.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary+Keys.swift"; sourceTree = ""; }; + 7DE9200329CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7DE9200429CA70F3004483EB /* Heap+UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Heap+UnsafeHandle.swift"; sourceTree = ""; }; + 7DE9200529CA70F3004483EB /* Heap+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Heap+Descriptions.swift"; sourceTree = ""; }; + 7DE9200629CA70F3004483EB /* Heap+Invariants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Heap+Invariants.swift"; sourceTree = ""; }; + 7DE9200729CA70F3004483EB /* HeapModule.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = HeapModule.docc; sourceTree = ""; }; + 7DE9200829CA70F3004483EB /* Heap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Heap.swift; sourceTree = ""; }; + 7DE9200929CA70F3004483EB /* Heap+ExpressibleByArrayLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Heap+ExpressibleByArrayLiteral.swift"; sourceTree = ""; }; + 7DE9200A29CA70F3004483EB /* _HeapNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _HeapNode.swift; sourceTree = ""; }; + 7DE921A529CA782F004483EB /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = README.md; path = ../README.md; sourceTree = ""; }; + 7DE921A629CA782F004483EB /* CONTRIBUTING.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = CONTRIBUTING.md; path = ../CONTRIBUTING.md; sourceTree = ""; }; + 7DE921A729CA782F004483EB /* CODEOWNERS */ = {isa = PBXFileReference; lastKnownFileType = text; name = CODEOWNERS; path = ../CODEOWNERS; sourceTree = ""; }; + 7DE921A829CA782F004483EB /* CODE_OF_CONDUCT.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = CODE_OF_CONDUCT.md; path = ../CODE_OF_CONDUCT.md; sourceTree = ""; }; + 7DE921A929CA782F004483EB /* Package.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = Package.swift; path = ../Package.swift; sourceTree = ""; }; + 7DE921AA29CA782F004483EB /* LICENSE.txt */ = {isa = PBXFileReference; lastKnownFileType = text; name = LICENSE.txt; path = ../LICENSE.txt; sourceTree = ""; }; + 7DE921AB29CA782F004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; name = CMakeLists.txt; path = ../CMakeLists.txt; sourceTree = ""; }; + 7DE921AD29CA78B2004483EB /* run-benchmarks.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "run-benchmarks.sh"; sourceTree = ""; }; + 7DE921B229CA78B2004483EB /* shuffle-sources.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "shuffle-sources.sh"; sourceTree = ""; }; + 7DE921B329CA78B2004483EB /* run-full-tests.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "run-full-tests.sh"; sourceTree = ""; }; + 7DE921B629CA78B2004483EB /* generate-docs.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "generate-docs.sh"; sourceTree = ""; }; + 7DE921CC29CA8575004483EB /* UtilitiesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UtilitiesTests.swift; sourceTree = ""; }; + 7DE921CD29CA8575004483EB /* MinimalTypeConformances.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalTypeConformances.swift; sourceTree = ""; }; + 7DE921CE29CA8575004483EB /* IndexRangeCollectionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexRangeCollectionTests.swift; sourceTree = ""; }; + 7DE921CF29CA8575004483EB /* CombinatoricsChecks.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CombinatoricsChecks.swift; sourceTree = ""; }; + 7DE921D129CA8575004483EB /* Hash.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Hash.swift; sourceTree = ""; }; + 7DE921D229CA8575004483EB /* Utilities.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utilities.swift; sourceTree = ""; }; + 7DE921D329CA8575004483EB /* TreeDictionary Smoke Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary Smoke Tests.swift"; sourceTree = ""; }; + 7DE921D429CA8575004483EB /* TreeDictionary.Keys Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary.Keys Tests.swift"; sourceTree = ""; }; + 7DE921D529CA8575004483EB /* TreeDictionary Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary Tests.swift"; sourceTree = ""; }; + 7DE921D629CA8575004483EB /* Colliders.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Colliders.swift; sourceTree = ""; }; + 7DE921D729CA8575004483EB /* TreeHashedCollections Fixtures.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeHashedCollections Fixtures.swift"; sourceTree = ""; }; + 7DE921D829CA8575004483EB /* TreeDictionary.Values Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeDictionary.Values Tests.swift"; sourceTree = ""; }; + 7DE921D929CA8575004483EB /* TreeSet Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TreeSet Tests.swift"; sourceTree = ""; }; + 7DE921DB29CA8575004483EB /* BitSet.Counted Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet.Counted Tests.swift"; sourceTree = ""; }; + 7DE921DC29CA8575004483EB /* BitSetTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitSetTests.swift; sourceTree = ""; }; + 7DE921DD29CA8575004483EB /* BitArrayTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitArrayTests.swift; sourceTree = ""; }; + 7DE921DF29CA8575004483EB /* TestRope.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestRope.swift; sourceTree = ""; }; + 7DE921E129CA8575004483EB /* Availability.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Availability.swift; sourceTree = ""; }; + 7DE921E229CA8575004483EB /* TestBigString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestBigString.swift; sourceTree = ""; }; + 7DE921E329CA8575004483EB /* SampleStrings.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SampleStrings.swift; sourceTree = ""; }; + 7DE921E629CA8575004483EB /* OrderedDictionary Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary Tests.swift"; sourceTree = ""; }; + 7DE921E729CA8575004483EB /* OrderedDictionary Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary Utils.swift"; sourceTree = ""; }; + 7DE921E829CA8575004483EB /* OrderedDictionary+Values Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Values Tests.swift"; sourceTree = ""; }; + 7DE921E929CA8575004483EB /* OrderedDictionary+Elements Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Elements Tests.swift"; sourceTree = ""; }; + 7DE921EB29CA8575004483EB /* OrderedSetInternals.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedSetInternals.swift; sourceTree = ""; }; + 7DE921EC29CA8575004483EB /* OrderedSet Diffing Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet Diffing Tests.swift"; sourceTree = ""; }; + 7DE921ED29CA8575004483EB /* RandomAccessCollection+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RandomAccessCollection+Extras.swift"; sourceTree = ""; }; + 7DE921EE29CA8575004483EB /* OrderedSet.UnorderedView Tests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "OrderedSet.UnorderedView Tests.swift"; sourceTree = ""; }; + 7DE921EF29CA8575004483EB /* OrderedSetTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedSetTests.swift; sourceTree = ""; }; + 7DE921F129CA8575004483EB /* HashTableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HashTableTests.swift; sourceTree = ""; }; + 7DE921F329CA8575004483EB /* HeapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HeapTests.swift; sourceTree = ""; }; + 7DE921F429CA8575004483EB /* HeapNodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HeapNodeTests.swift; sourceTree = ""; }; + 7DE921F629CA8576004483EB /* DequeInternals.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DequeInternals.swift; sourceTree = ""; }; + 7DE921F729CA8576004483EB /* RangeReplaceableCollectionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RangeReplaceableCollectionTests.swift; sourceTree = ""; }; + 7DE921F829CA8576004483EB /* DequeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DequeTests.swift; sourceTree = ""; }; + 7DE921F929CA8576004483EB /* MutableCollectionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableCollectionTests.swift; sourceTree = ""; }; + 7DEBDAC829CBEE5200ADC226 /* UnsafeMutablePointer+SE-0370.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "UnsafeMutablePointer+SE-0370.swift.gyb"; sourceTree = ""; }; + 7DEBDAC929CBEE5200ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "UnsafeMutableBufferPointer+SE-0370.swift.gyb"; sourceTree = ""; }; + 7DEBDACA29CBEE5200ADC226 /* Array+WithContiguousStorage Compatibility.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "Array+WithContiguousStorage Compatibility.swift.gyb"; sourceTree = ""; }; + 7DEBDACB29CBEE5200ADC226 /* UnsafeRawPointer extensions.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "UnsafeRawPointer extensions.swift.gyb"; sourceTree = ""; }; + 7DEBDACD29CBEE5200ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UnsafeMutableBufferPointer+SE-0370.swift"; sourceTree = ""; }; + 7DEBDACE29CBEE5200ADC226 /* Array+WithContiguousStorage Compatibility.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Array+WithContiguousStorage Compatibility.swift"; sourceTree = ""; }; + 7DEBDACF29CBEE5200ADC226 /* UnsafeMutablePointer+SE-0370.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UnsafeMutablePointer+SE-0370.swift"; sourceTree = ""; }; + 7DEBDAD029CBEE5200ADC226 /* UnsafeRawPointer extensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UnsafeRawPointer extensions.swift"; sourceTree = ""; }; + 7DEBDAD129CBEE5200ADC226 /* Descriptions.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Descriptions.swift.gyb; sourceTree = ""; }; + 7DEBDAD229CBEE5200ADC226 /* RandomAccessCollection+Offsets.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "RandomAccessCollection+Offsets.swift.gyb"; sourceTree = ""; }; + 7DEBDAD429CBEE5300ADC226 /* UnsafeMutableBufferPointer+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UnsafeMutableBufferPointer+Extras.swift"; sourceTree = ""; }; + 7DEBDAD529CBEE5300ADC226 /* UnsafeBufferPointer+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UnsafeBufferPointer+Extras.swift"; sourceTree = ""; }; + 7DEBDAD629CBEE5300ADC226 /* RandomAccessCollection+Offsets.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RandomAccessCollection+Offsets.swift"; sourceTree = ""; }; + 7DEBDAD729CBEE5300ADC226 /* Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Descriptions.swift; sourceTree = ""; }; + 7DEBDAD829CBEE5300ADC226 /* Debugging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Debugging.swift; sourceTree = ""; }; + 7DEBDAD929CBEE5300ADC226 /* UnsafeBufferPointer+Extras.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "UnsafeBufferPointer+Extras.swift.gyb"; sourceTree = ""; }; + 7DEBDADB29CBEE5300ADC226 /* _UnsafeBitSet.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = _UnsafeBitSet.swift.gyb; sourceTree = ""; }; + 7DEBDADC29CBEE5300ADC226 /* _UnsafeBitSet+_Word.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "_UnsafeBitSet+_Word.swift.gyb"; sourceTree = ""; }; + 7DEBDADD29CBEE5300ADC226 /* _UnsafeBitSet+Index.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "_UnsafeBitSet+Index.swift.gyb"; sourceTree = ""; }; + 7DEBDADF29CBEE5300ADC226 /* _UnsafeBitSet+Index.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_UnsafeBitSet+Index.swift"; sourceTree = ""; }; + 7DEBDAE029CBEE5300ADC226 /* _UnsafeBitSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _UnsafeBitSet.swift; sourceTree = ""; }; + 7DEBDAE129CBEE5300ADC226 /* _UnsafeBitSet+_Word.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "_UnsafeBitSet+_Word.swift"; sourceTree = ""; }; + 7DEBDAE329CBEE5300ADC226 /* UInt+reversed.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "UInt+reversed.swift.gyb"; sourceTree = ""; }; + 7DEBDAE429CBEE5300ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "FixedWidthInteger+roundUpToPowerOfTwo.swift.gyb"; sourceTree = ""; }; + 7DEBDAE529CBEE5300ADC226 /* UInt+first and last set bit.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "UInt+first and last set bit.swift.gyb"; sourceTree = ""; }; + 7DEBDAE629CBEE5300ADC226 /* Integer rank.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "Integer rank.swift.gyb"; sourceTree = ""; }; + 7DEBDAE829CBEE5300ADC226 /* UInt+reversed.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UInt+reversed.swift"; sourceTree = ""; }; + 7DEBDAE929CBEE5300ADC226 /* Integer rank.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Integer rank.swift"; sourceTree = ""; }; + 7DEBDAEA29CBEE5300ADC226 /* UInt+first and last set bit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UInt+first and last set bit.swift"; sourceTree = ""; }; + 7DEBDAEB29CBEE5300ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FixedWidthInteger+roundUpToPowerOfTwo.swift"; sourceTree = ""; }; + 7DEBDAEC29CBEE5300ADC226 /* UnsafeMutableBufferPointer+Extras.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "UnsafeMutableBufferPointer+Extras.swift.gyb"; sourceTree = ""; }; + 7DEBDAED29CBEE5300ADC226 /* Debugging.swift.gyb */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Debugging.swift.gyb; sourceTree = ""; }; + 7DEBDB2129CCE43600ADC226 /* Combinatorics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Combinatorics.swift; sourceTree = ""; }; + 7DEBDB2229CCE43600ADC226 /* TestContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestContext.swift; sourceTree = ""; }; + 7DEBDB2329CCE43600ADC226 /* Assertions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Assertions.swift; sourceTree = ""; }; + 7DEBDB2429CCE43600ADC226 /* CollectionTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollectionTestCase.swift; sourceTree = ""; }; + 7DEBDB2629CCE43600ADC226 /* RandomStableSample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RandomStableSample.swift; sourceTree = ""; }; + 7DEBDB2729CCE43600ADC226 /* LifetimeTracked.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LifetimeTracked.swift; sourceTree = ""; }; + 7DEBDB2829CCE43600ADC226 /* IndexRangeCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexRangeCollection.swift; sourceTree = ""; }; + 7DEBDB2929CCE43600ADC226 /* Integer Square Root.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Integer Square Root.swift"; sourceTree = ""; }; + 7DEBDB2A29CCE43600ADC226 /* DictionaryAPIChecker.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DictionaryAPIChecker.swift; sourceTree = ""; }; + 7DEBDB2B29CCE43600ADC226 /* StringConvertibleValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StringConvertibleValue.swift; sourceTree = ""; }; + 7DEBDB2C29CCE43600ADC226 /* AllOnesRandomNumberGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AllOnesRandomNumberGenerator.swift; sourceTree = ""; }; + 7DEBDB2D29CCE43600ADC226 /* Box.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Box.swift; sourceTree = ""; }; + 7DEBDB2E29CCE43600ADC226 /* LifetimeTracker.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LifetimeTracker.swift; sourceTree = ""; }; + 7DEBDB2F29CCE43600ADC226 /* RepeatableRandomNumberGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RepeatableRandomNumberGenerator.swift; sourceTree = ""; }; + 7DEBDB3029CCE43600ADC226 /* SortedCollectionAPIChecker.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SortedCollectionAPIChecker.swift; sourceTree = ""; }; + 7DEBDB3129CCE43600ADC226 /* HashableBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HashableBox.swift; sourceTree = ""; }; + 7DEBDB3229CCE43600ADC226 /* SetAPIChecker.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SetAPIChecker.swift; sourceTree = ""; }; + 7DEBDB3429CCE43600ADC226 /* CheckCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CheckCollection.swift; sourceTree = ""; }; + 7DEBDB3529CCE43600ADC226 /* CheckHashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CheckHashable.swift; sourceTree = ""; }; + 7DEBDB3629CCE43600ADC226 /* CheckComparable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CheckComparable.swift; sourceTree = ""; }; + 7DEBDB3729CCE43600ADC226 /* CheckEquatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CheckEquatable.swift; sourceTree = ""; }; + 7DEBDB3829CCE43600ADC226 /* CheckSequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CheckSequence.swift; sourceTree = ""; }; + 7DEBDB3929CCE43600ADC226 /* CheckBidirectionalCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CheckBidirectionalCollection.swift; sourceTree = ""; }; + 7DEBDB3B29CCE43600ADC226 /* _CollectionState.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _CollectionState.swift; sourceTree = ""; }; + 7DEBDB3C29CCE43600ADC226 /* MinimalRandomAccessCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalRandomAccessCollection.swift; sourceTree = ""; }; + 7DEBDB3D29CCE43600ADC226 /* MinimalMutableRandomAccessCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalMutableRandomAccessCollection.swift; sourceTree = ""; }; + 7DEBDB3E29CCE43600ADC226 /* MinimalSequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalSequence.swift; sourceTree = ""; }; + 7DEBDB3F29CCE43600ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalMutableRangeReplaceableRandomAccessCollection.swift; sourceTree = ""; }; + 7DEBDB4029CCE43600ADC226 /* MinimalBidirectionalCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalBidirectionalCollection.swift; sourceTree = ""; }; + 7DEBDB4129CCE43600ADC226 /* MinimalIndex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalIndex.swift; sourceTree = ""; }; + 7DEBDB4229CCE43600ADC226 /* ResettableValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResettableValue.swift; sourceTree = ""; }; + 7DEBDB4329CCE43600ADC226 /* MinimalRangeReplaceableRandomAccessCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalRangeReplaceableRandomAccessCollection.swift; sourceTree = ""; }; + 7DEBDB4429CCE43600ADC226 /* MinimalEncoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalEncoder.swift; sourceTree = ""; }; + 7DEBDB4529CCE43600ADC226 /* MinimalIterator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalIterator.swift; sourceTree = ""; }; + 7DEBDB4629CCE43600ADC226 /* _MinimalCollectionCore.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _MinimalCollectionCore.swift; sourceTree = ""; }; + 7DEBDB4729CCE43600ADC226 /* MinimalDecoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalDecoder.swift; sourceTree = ""; }; + 7DEBDB4829CCE43600ADC226 /* MinimalCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MinimalCollection.swift; sourceTree = ""; }; + 7DEBDB9729CCE4A600ADC226 /* CollectionsTests.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CollectionsTests.xcconfig; sourceTree = ""; }; + 7DEBDB9829CCE4A600ADC226 /* Shared.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Shared.xcconfig; sourceTree = ""; }; + 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Collections.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 7DE91B2329CA6721004483EB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7DE91B2B29CA6721004483EB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 7DE91B2F29CA6721004483EB /* Collections.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 7DE91B1C29CA6721004483EB = { + isa = PBXGroup; + children = ( + 7DE921A929CA782F004483EB /* Package.swift */, + 7DE921AB29CA782F004483EB /* CMakeLists.txt */, + 7DE921A829CA782F004483EB /* CODE_OF_CONDUCT.md */, + 7DE921A729CA782F004483EB /* CODEOWNERS */, + 7DE921A629CA782F004483EB /* CONTRIBUTING.md */, + 7DE921AA29CA782F004483EB /* LICENSE.txt */, + 7DE921A529CA782F004483EB /* README.md */, + 7DE91E7029CA70F3004483EB /* Sources */, + 7DE921CA29CA8575004483EB /* Tests */, + 7DE921AC29CA78B2004483EB /* Utils */, + 7DEBDB9329CCE4A600ADC226 /* Xcode */, + 7DE91B2729CA6721004483EB /* Products */, + ); + sourceTree = ""; + }; + 7DE91B2729CA6721004483EB /* Products */ = { + isa = PBXGroup; + children = ( + 7DE91B2629CA6721004483EB /* Collections.framework */, + 7DE91B2E29CA6721004483EB /* CollectionsTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 7DE91E7029CA70F3004483EB /* Sources */ = { + isa = PBXGroup; + children = ( + 7DE91F2229CA70F3004483EB /* _CollectionsUtilities */, + 7DE91F3929CA70F3004483EB /* BitCollections */, + 7DE91F7929CA70F3004483EB /* Collections */, + 7DE91EB629CA70F3004483EB /* DequeModule */, + 7DE91FA729CA70F3004483EB /* HashTreeCollections */, + 7DE9200229CA70F3004483EB /* HeapModule */, + 7DE91E7129CA70F3004483EB /* OrderedCollections */, + 7DE91ECA29CA70F3004483EB /* RopeModule */, + 7DE91EB529CA70F3004483EB /* CMakeLists.txt */, + ); + name = Sources; + path = ../Sources; + sourceTree = ""; + }; + 7DE91E7129CA70F3004483EB /* OrderedCollections */ = { + isa = PBXGroup; + children = ( + 7DE91EAC29CA70F3004483EB /* HashTable */, + 7DE91E7429CA70F3004483EB /* OrderedDictionary */, + 7DE91E8629CA70F3004483EB /* OrderedSet */, + 7DE91EAA29CA70F3004483EB /* Utilities */, + 7DE91E7229CA70F3004483EB /* OrderedCollections.docc */, + 7DE91E7329CA70F3004483EB /* CMakeLists.txt */, + ); + path = OrderedCollections; + sourceTree = ""; + }; + 7DE91E7429CA70F3004483EB /* OrderedDictionary */ = { + isa = PBXGroup; + children = ( + 7DE91E8529CA70F3004483EB /* OrderedDictionary.swift */, + 7DE91E7F29CA70F3004483EB /* OrderedDictionary+Codable.swift */, + 7DE91E7B29CA70F3004483EB /* OrderedDictionary+CustomReflectable.swift */, + 7DE91E7829CA70F3004483EB /* OrderedDictionary+Deprecations.swift */, + 7DE91E8329CA70F3004483EB /* OrderedDictionary+Descriptions.swift */, + 7DE91E7A29CA70F3004483EB /* OrderedDictionary+Elements.SubSequence.swift */, + 7DE91E7E29CA70F3004483EB /* OrderedDictionary+Elements.swift */, + 7DE91E7529CA70F3004483EB /* OrderedDictionary+Equatable.swift */, + 7DE91E7629CA70F3004483EB /* OrderedDictionary+ExpressibleByDictionaryLiteral.swift */, + 7DE91E7729CA70F3004483EB /* OrderedDictionary+Hashable.swift */, + 7DE91E7929CA70F3004483EB /* OrderedDictionary+Initializers.swift */, + 7DE91E8029CA70F3004483EB /* OrderedDictionary+Invariants.swift */, + 7DE91E8429CA70F3004483EB /* OrderedDictionary+Partial MutableCollection.swift */, + 7DE91E7D29CA70F3004483EB /* OrderedDictionary+Partial RangeReplaceableCollection.swift */, + 7DE91E8229CA70F3004483EB /* OrderedDictionary+Sendable.swift */, + 7DE91E7C29CA70F3004483EB /* OrderedDictionary+Sequence.swift */, + 7DE91E8129CA70F3004483EB /* OrderedDictionary+Values.swift */, + ); + path = OrderedDictionary; + sourceTree = ""; + }; + 7DE91E8629CA70F3004483EB /* OrderedSet */ = { + isa = PBXGroup; + children = ( + 7DE91E9629CA70F3004483EB /* OrderedSet.swift */, + 7DE91E9229CA70F3004483EB /* OrderedSet+Codable.swift */, + 7DE91E9E29CA70F3004483EB /* OrderedSet+CustomReflectable.swift */, + 7DE91E8929CA70F3004483EB /* OrderedSet+Descriptions.swift */, + 7DE91E8B29CA70F3004483EB /* OrderedSet+Diffing.swift */, + 7DE91E9429CA70F3004483EB /* OrderedSet+Equatable.swift */, + 7DE91E9829CA70F3004483EB /* OrderedSet+ExpressibleByArrayLiteral.swift */, + 7DE91E8E29CA70F3004483EB /* OrderedSet+Hashable.swift */, + 7DE91E9529CA70F3004483EB /* OrderedSet+Initializers.swift */, + 7DE91E9029CA70F3004483EB /* OrderedSet+Insertions.swift */, + 7DE91E8D29CA70F3004483EB /* OrderedSet+Invariants.swift */, + 7DE91E9A29CA70F3004483EB /* OrderedSet+Partial MutableCollection.swift */, + 7DE91EA229CA70F3004483EB /* OrderedSet+Partial RangeReplaceableCollection.swift */, + 7DE91EA129CA70F3004483EB /* OrderedSet+Partial SetAlgebra formIntersection.swift */, + 7DE91EA529CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift */, + 7DE91E9D29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formUnion.swift */, + 7DE91EA629CA70F3004483EB /* OrderedSet+Partial SetAlgebra intersection.swift */, + 7DE91EA829CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift */, + 7DE91E8A29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isEqualSet.swift */, + 7DE91E8F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSubset.swift */, + 7DE91EA929CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSuperset.swift */, + 7DE91E9129CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSubset.swift */, + 7DE91E9329CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSuperset.swift */, + 7DE91EA729CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtract.swift */, + 7DE91EA429CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtracting.swift */, + 7DE91E8729CA70F3004483EB /* OrderedSet+Partial SetAlgebra symmetricDifference.swift */, + 7DE91EA029CA70F3004483EB /* OrderedSet+Partial SetAlgebra union.swift */, + 7DE91EA329CA70F3004483EB /* OrderedSet+Partial SetAlgebra+Basics.swift */, + 7DE91E8829CA70F3004483EB /* OrderedSet+RandomAccessCollection.swift */, + 7DE91E9F29CA70F3004483EB /* OrderedSet+ReserveCapacity.swift */, + 7DE91E9B29CA70F3004483EB /* OrderedSet+Sendable.swift */, + 7DE91E9929CA70F3004483EB /* OrderedSet+SubSequence.swift */, + 7DE91E9C29CA70F3004483EB /* OrderedSet+Testing.swift */, + 7DE91E9729CA70F3004483EB /* OrderedSet+UnorderedView.swift */, + 7DE91E8C29CA70F3004483EB /* OrderedSet+UnstableInternals.swift */, + ); + path = OrderedSet; + sourceTree = ""; + }; + 7DE91EAA29CA70F3004483EB /* Utilities */ = { + isa = PBXGroup; + children = ( + 7DE91EAB29CA70F3004483EB /* _UnsafeBitset.swift */, + ); + path = Utilities; + sourceTree = ""; + }; + 7DE91EAC29CA70F3004483EB /* HashTable */ = { + isa = PBXGroup; + children = ( + 7DE91EAF29CA70F3004483EB /* _HashTable.swift */, + 7DE91EAE29CA70F3004483EB /* _HashTable+Bucket.swift */, + 7DE91EB429CA70F3004483EB /* _HashTable+BucketIterator.swift */, + 7DE91EB029CA70F3004483EB /* _HashTable+Constants.swift */, + 7DE91EB329CA70F3004483EB /* _HashTable+CustomStringConvertible.swift */, + 7DE91EB129CA70F3004483EB /* _Hashtable+Header.swift */, + 7DE91EB229CA70F3004483EB /* _HashTable+Testing.swift */, + 7DE91EAD29CA70F3004483EB /* _HashTable+UnsafeHandle.swift */, + ); + path = HashTable; + sourceTree = ""; + }; + 7DE91EB629CA70F3004483EB /* DequeModule */ = { + isa = PBXGroup; + children = ( + 7DE91EB729CA70F3004483EB /* _DequeBuffer.swift */, + 7DE91EBF29CA70F3004483EB /* _DequeBufferHeader.swift */, + 7DE91EBC29CA70F3004483EB /* _DequeSlot.swift */, + 7DE91EBE29CA70F3004483EB /* _UnsafeWrappedBuffer.swift */, + 7DE91EC929CA70F3004483EB /* Deque._Storage.swift */, + 7DE91EC429CA70F3004483EB /* Deque._UnsafeHandle.swift */, + 7DE91EBB29CA70F3004483EB /* Deque.swift */, + 7DE91EC129CA70F3004483EB /* Deque+Codable.swift */, + 7DE91EB829CA70F3004483EB /* Deque+Collection.swift */, + 7DE91EBA29CA70F3004483EB /* Deque+CustomReflectable.swift */, + 7DE91EC529CA70F3004483EB /* Deque+Descriptions.swift */, + 7DE91EC829CA70F3004483EB /* Deque+Equatable.swift */, + 7DE91EC729CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift */, + 7DE91EC629CA70F3004483EB /* Deque+Extras.swift */, + 7DE91EBD29CA70F3004483EB /* Deque+Hashable.swift */, + 7DE91EC029CA70F3004483EB /* Deque+Sendable.swift */, + 7DE91EC229CA70F3004483EB /* Deque+Testing.swift */, + 7DE91EC329CA70F3004483EB /* DequeModule.docc */, + 7DE91EB929CA70F3004483EB /* CMakeLists.txt */, + ); + path = DequeModule; + sourceTree = ""; + }; + 7DE91ECA29CA70F3004483EB /* RopeModule */ = { + isa = PBXGroup; + children = ( + 7DE91ECB29CA70F3004483EB /* BigString */, + 7DE91EFE29CA70F3004483EB /* Rope */, + 7DE91F1D29CA70F3004483EB /* Utilities */, + ); + path = RopeModule; + sourceTree = ""; + }; + 7DE91ECB29CA70F3004483EB /* BigString */ = { + isa = PBXGroup; + children = ( + 7DE91ECC29CA70F3004483EB /* Basics */, + 7DE91ED729CA70F3004483EB /* Chunk */, + 7DE91EE129CA70F3004483EB /* Operations */, + 7DE91EEA29CA70F3004483EB /* Views */, + 7DE91EF229CA70F3004483EB /* Conformances */, + ); + path = BigString; + sourceTree = ""; + }; + 7DE91ECC29CA70F3004483EB /* Basics */ = { + isa = PBXGroup; + children = ( + 7DE91ED029CA70F3004483EB /* BigString.swift */, + 7DE91ED629CA70F3004483EB /* BigString+Builder.swift */, + 7DE91ED229CA70F3004483EB /* BigString+Contents.swift */, + 7DE91ED529CA70F3004483EB /* BigString+Debugging.swift */, + 7DE91ECE29CA70F3004483EB /* BigString+Index.swift */, + 7DE91ED429CA70F3004483EB /* BigString+Ingester.swift */, + 7DE91ED329CA70F3004483EB /* BigString+Invariants.swift */, + 7DE91ED129CA70F3004483EB /* BigString+Iterators.swift */, + 7DE91ECD29CA70F3004483EB /* BigString+Metrics.swift */, + 7DE91ECF29CA70F3004483EB /* BigString+Summary.swift */, + ); + path = Basics; + sourceTree = ""; + }; + 7DE91ED729CA70F3004483EB /* Chunk */ = { + isa = PBXGroup; + children = ( + 7DE91EDC29CA70F3004483EB /* BigString+Chunk.swift */, + 7DE91ED829CA70F3004483EB /* BigString+Chunk+Append and Insert.swift */, + 7DE91EDF29CA70F3004483EB /* BigString+Chunk+Breaks.swift */, + 7DE91EDA29CA70F3004483EB /* BigString+Chunk+Counts.swift */, + 7DE91EDD29CA70F3004483EB /* BigString+Chunk+Description.swift */, + 7DE91EDB29CA70F3004483EB /* BigString+Chunk+Indexing by Characters.swift */, + 7DE91ED929CA70F3004483EB /* BigString+Chunk+Indexing by UTF16.swift */, + 7DE91EE029CA70F3004483EB /* BigString+Chunk+RopeElement.swift */, + 7DE91EDE29CA70F3004483EB /* BigString+Chunk+Splitting.swift */, + ); + path = Chunk; + sourceTree = ""; + }; + 7DE91EE129CA70F3004483EB /* Operations */ = { + isa = PBXGroup; + children = ( + 7DE91EE929CA70F3004483EB /* BigString+Append.swift */, + 7DE91EE729CA70F3004483EB /* BigString+Initializers.swift */, + 7DE91EE629CA70F3004483EB /* BigString+Insert.swift */, + 7DE91EE329CA70F3004483EB /* BigString+Managing Breaks.swift */, + 7DE91EE429CA70F3004483EB /* BigString+RemoveSubrange.swift */, + 7DE91EE529CA70F3004483EB /* BigString+ReplaceSubrange.swift */, + 7DE91EE229CA70F3004483EB /* BigString+Split.swift */, + 7DE91EE829CA70F3004483EB /* Range+BigString.swift */, + ); + path = Operations; + sourceTree = ""; + }; + 7DE91EEA29CA70F3004483EB /* Views */ = { + isa = PBXGroup; + children = ( + 7DE91EEB29CA70F3004483EB /* BigString+UnicodeScalarView.swift */, + 7DE91EEC29CA70F3004483EB /* BigString+UTF8View.swift */, + 7DE91EF029CA70F3004483EB /* BigString+UTF16View.swift */, + 7DE91EEE29CA70F3004483EB /* BigSubstring.swift */, + 7DE91EED29CA70F3004483EB /* BigSubstring+UnicodeScalarView.swift */, + 7DE91EF129CA70F3004483EB /* BigSubstring+UTF8View.swift */, + 7DE91EEF29CA70F3004483EB /* BigSubstring+UTF16View.swift */, + ); + path = Views; + sourceTree = ""; + }; + 7DE91EF229CA70F3004483EB /* Conformances */ = { + isa = PBXGroup; + children = ( + 7DE91EF529CA70F3004483EB /* BigString+BidirectionalCollection.swift */, + 7DE91EFD29CA70F3004483EB /* BigString+Comparable.swift */, + 7DE91EF629CA70F3004483EB /* BigString+CustomDebugStringConvertible.swift */, + 7DE91EF429CA70F3004483EB /* BigString+CustomStringConvertible.swift */, + 7DE91EF729CA70F3004483EB /* BigString+Equatable.swift */, + 7DE91EFB29CA70F3004483EB /* BigString+ExpressibleByStringLiteral.swift */, + 7DE91EF329CA70F3004483EB /* BigString+Hashing.swift */, + 7DE91EF929CA70F3004483EB /* BigString+LosslessStringConvertible.swift */, + 7DE91EFC29CA70F3004483EB /* BigString+RangeReplaceableCollection.swift */, + 7DE91EFA29CA70F3004483EB /* BigString+Sequence.swift */, + 7DE91EF829CA70F3004483EB /* BigString+TextOutputStream.swift */, + ); + path = Conformances; + sourceTree = ""; + }; + 7DE91EFE29CA70F3004483EB /* Rope */ = { + isa = PBXGroup; + children = ( + 7DE91EFF29CA70F3004483EB /* Basics */, + 7DE91F0E29CA70F3004483EB /* Operations */, + 7DE91F1929CA70F3004483EB /* Conformances */, + ); + path = Rope; + sourceTree = ""; + }; + 7DE91EFF29CA70F3004483EB /* Basics */ = { + isa = PBXGroup; + children = ( + 7DE91F0129CA70F3004483EB /* _RopeItem.swift */, + 7DE91F0C29CA70F3004483EB /* _RopePath.swift */, + 7DE91F0329CA70F3004483EB /* _RopeVersion.swift */, + 7DE91F0529CA70F3004483EB /* Rope.swift */, + 7DE91F0D29CA70F3004483EB /* Rope+_Node.swift */, + 7DE91F0729CA70F3004483EB /* Rope+_Storage.swift */, + 7DE91F0929CA70F3004483EB /* Rope+_UnmanagedLeaf.swift */, + 7DE91F0629CA70F3004483EB /* Rope+_UnsafeHandle.swift */, + 7DE91F0B29CA70F3004483EB /* Rope+Builder.swift */, + 7DE91F0229CA70F3004483EB /* Rope+Debugging.swift */, + 7DE91F0829CA70F3004483EB /* Rope+Invariants.swift */, + 7DE91F0429CA70F3004483EB /* RopeElement.swift */, + 7DE91F0029CA70F3004483EB /* RopeMetric.swift */, + 7DE91F0A29CA70F3004483EB /* RopeSummary.swift */, + ); + path = Basics; + sourceTree = ""; + }; + 7DE91F0E29CA70F3004483EB /* Operations */ = { + isa = PBXGroup; + children = ( + 7DE91F1029CA70F3004483EB /* Rope+Append.swift */, + 7DE91F0F29CA70F3004483EB /* Rope+Extract.swift */, + 7DE91F1229CA70F3004483EB /* Rope+Find.swift */, + 7DE91F1429CA70F3004483EB /* Rope+ForEachWhile.swift */, + 7DE91F1329CA70F3004483EB /* Rope+Insert.swift */, + 7DE91F1629CA70F3004483EB /* Rope+Join.swift */, + 7DE91F1529CA70F3004483EB /* Rope+MutatingForEach.swift */, + 7DE91F1729CA70F3004483EB /* Rope+Remove.swift */, + 7DE91F1829CA70F3004483EB /* Rope+RemoveSubrange.swift */, + 7DE91F1129CA70F3004483EB /* Rope+Split.swift */, + ); + path = Operations; + sourceTree = ""; + }; + 7DE91F1929CA70F3004483EB /* Conformances */ = { + isa = PBXGroup; + children = ( + 7DE91F1C29CA70F3004483EB /* Rope+Collection.swift */, + 7DE91F1A29CA70F3004483EB /* Rope+Index.swift */, + 7DE91F1B29CA70F3004483EB /* Rope+Sequence.swift */, + ); + path = Conformances; + sourceTree = ""; + }; + 7DE91F1D29CA70F3004483EB /* Utilities */ = { + isa = PBXGroup; + children = ( + 7DE91F1F29CA70F3004483EB /* _CharacterRecognizer.swift */, + 7DE91F2129CA70F3004483EB /* Optional Utilities.swift */, + 7DE91F1E29CA70F3004483EB /* String Utilities.swift */, + 7DE91F2029CA70F3004483EB /* String.Index+ABI.swift */, + ); + path = Utilities; + sourceTree = ""; + }; + 7DE91F2229CA70F3004483EB /* _CollectionsUtilities */ = { + isa = PBXGroup; + children = ( + 7DEBDAD329CBEE5300ADC226 /* autogenerated */, + 7DEBDAC729CBEE5200ADC226 /* Compatibility */, + 7DEBDAE229CBEE5300ADC226 /* IntegerTricks */, + 7DEBDADA29CBEE5300ADC226 /* UnsafeBitSet */, + 7DE91F3029CA70F3004483EB /* _SortedCollection.swift */, + 7DE91F3829CA70F3004483EB /* _UniqueCollection.swift */, + 7DEBDAED29CBEE5300ADC226 /* Debugging.swift.gyb */, + 7DEBDAD129CBEE5200ADC226 /* Descriptions.swift.gyb */, + 7DEBDAD229CBEE5200ADC226 /* RandomAccessCollection+Offsets.swift.gyb */, + 7DEBDAD929CBEE5300ADC226 /* UnsafeBufferPointer+Extras.swift.gyb */, + 7DEBDAEC29CBEE5300ADC226 /* UnsafeMutableBufferPointer+Extras.swift.gyb */, + 7DE91F2E29CA70F3004483EB /* CMakeLists.txt */, + ); + path = _CollectionsUtilities; + sourceTree = ""; + }; + 7DE91F3929CA70F3004483EB /* BitCollections */ = { + isa = PBXGroup; + children = ( + 7DE91F6329CA70F3004483EB /* BitArray */, + 7DE91F3A29CA70F3004483EB /* BitSet */, + 7DE91F5D29CA70F3004483EB /* Shared */, + 7DE91F6229CA70F3004483EB /* BitCollections.docc */, + 7DE91F5C29CA70F3004483EB /* CMakeLists.txt */, + ); + path = BitCollections; + sourceTree = ""; + }; + 7DE91F3A29CA70F3004483EB /* BitSet */ = { + isa = PBXGroup; + children = ( + 7DE91F5829CA70F3004483EB /* BitSet._UnsafeHandle.swift */, + 7DE91F4A29CA70F3004483EB /* BitSet.Counted.swift */, + 7DE91F4F29CA70F3004483EB /* BitSet.Index.swift */, + 7DE91F5329CA70F3004483EB /* BitSet.swift */, + 7DE91F4729CA70F3004483EB /* BitSet+BidirectionalCollection.swift */, + 7DE91F3D29CA70F3004483EB /* BitSet+Codable.swift */, + 7DE91F4B29CA70F3004483EB /* BitSet+CustomDebugStringConvertible.swift */, + 7DE91F4C29CA70F3004483EB /* BitSet+CustomReflectable.swift */, + 7DE91F4829CA70F3004483EB /* BitSet+CustomStringConvertible.swift */, + 7DE91F5429CA70F3004483EB /* BitSet+Equatable.swift */, + 7DE91F4529CA70F3004483EB /* BitSet+ExpressibleByArrayLiteral.swift */, + 7DE91F4329CA70F3004483EB /* BitSet+Extras.swift */, + 7DE91F5929CA70F3004483EB /* BitSet+Hashable.swift */, + 7DE91F4D29CA70F3004483EB /* BitSet+Initializers.swift */, + 7DE91F5A29CA70F3004483EB /* BitSet+Invariants.swift */, + 7DE91F4929CA70F3004483EB /* BitSet+Random.swift */, + 7DE91F5029CA70F3004483EB /* BitSet+SetAlgebra basics.swift */, + 7DE91F3E29CA70F3004483EB /* BitSet+SetAlgebra conformance.swift */, + 7DE91F3C29CA70F3004483EB /* BitSet+SetAlgebra formIntersection.swift */, + 7DE91F4429CA70F3004483EB /* BitSet+SetAlgebra formSymmetricDifference.swift */, + 7DE91F4129CA70F3004483EB /* BitSet+SetAlgebra formUnion.swift */, + 7DE91F5729CA70F3004483EB /* BitSet+SetAlgebra intersection.swift */, + 7DE91F5129CA70F3004483EB /* BitSet+SetAlgebra isDisjoint.swift */, + 7DE91F4629CA70F3004483EB /* BitSet+SetAlgebra isEqualSet.swift */, + 7DE91F5B29CA70F3004483EB /* BitSet+SetAlgebra isStrictSubset.swift */, + 7DE91F4229CA70F3004483EB /* BitSet+SetAlgebra isStrictSuperset.swift */, + 7DE91F4E29CA70F3004483EB /* BitSet+SetAlgebra isSubset.swift */, + 7DE91F5529CA70F3004483EB /* BitSet+SetAlgebra isSuperset.swift */, + 7DE91F3F29CA70F3004483EB /* BitSet+SetAlgebra subtract.swift */, + 7DE91F5629CA70F3004483EB /* BitSet+SetAlgebra subtracting.swift */, + 7DE91F3B29CA70F3004483EB /* BitSet+SetAlgebra symmetricDifference.swift */, + 7DE91F5229CA70F3004483EB /* BitSet+SetAlgebra union.swift */, + 7DE91F4029CA70F3004483EB /* BitSet+Sorted Collection APIs.swift */, + ); + path = BitSet; + sourceTree = ""; + }; + 7DE91F5D29CA70F3004483EB /* Shared */ = { + isa = PBXGroup; + children = ( + 7DE91F6129CA70F3004483EB /* _Word.swift */, + 7DE91F5F29CA70F3004483EB /* Range+Utilities.swift */, + 7DE91F5E29CA70F3004483EB /* Slice+Utilities.swift */, + 7DE91F6029CA70F3004483EB /* UInt+Tricks.swift */, + ); + path = Shared; + sourceTree = ""; + }; + 7DE91F6329CA70F3004483EB /* BitArray */ = { + isa = PBXGroup; + children = ( + 7DE91F7229CA70F3004483EB /* BitArray._UnsafeHandle.swift */, + 7DE91F6A29CA70F3004483EB /* BitArray.swift */, + 7DE91F6829CA70F3004483EB /* BitArray+BitwiseOperations.swift */, + 7DE91F6629CA70F3004483EB /* BitArray+ChunkedBitsIterators.swift */, + 7DE91F6F29CA70F3004483EB /* BitArray+Codable.swift */, + 7DE91F6C29CA70F3004483EB /* BitArray+Collection.swift */, + 7DE91F7329CA70F3004483EB /* BitArray+Copy.swift */, + 7DE91F7529CA70F3004483EB /* BitArray+CustomDebugStringConvertible.swift */, + 7DE91F6729CA70F3004483EB /* BitArray+CustomReflectable.swift */, + 7DE91F6529CA70F3004483EB /* BitArray+CustomStringConvertible.swift */, + 7DE91F7629CA70F3004483EB /* BitArray+Equatable.swift */, + 7DE91F6E29CA70F3004483EB /* BitArray+ExpressibleByArrayLiteral.swift */, + 7DE91F6D29CA70F3004483EB /* BitArray+Extras.swift */, + 7DE91F6B29CA70F3004483EB /* BitArray+Fill.swift */, + 7DE91F7429CA70F3004483EB /* BitArray+Hashable.swift */, + 7DE91F7129CA70F3004483EB /* BitArray+Initializers.swift */, + 7DE91F6929CA70F3004483EB /* BitArray+Invariants.swift */, + 7DE91F7729CA70F3004483EB /* BitArray+Random.swift */, + 7DE91F7029CA70F3004483EB /* BitArray+RangeReplaceableCollection.swift */, + 7DE91F7829CA70F3004483EB /* BitArray+Testing.swift */, + ); + path = BitArray; + sourceTree = ""; + }; + 7DE91F7929CA70F3004483EB /* Collections */ = { + isa = PBXGroup; + children = ( + 7DE91F7B29CA70F3004483EB /* Collections.swift */, + 7DE91F7C29CA70F3004483EB /* Collections.docc */, + 7DE91F7A29CA70F3004483EB /* CMakeLists.txt */, + ); + path = Collections; + sourceTree = ""; + }; + 7DE91FA729CA70F3004483EB /* HashTreeCollections */ = { + isa = PBXGroup; + children = ( + 7DE91FC829CA70F3004483EB /* HashNode */, + 7DE91FF029CA70F3004483EB /* TreeDictionary */, + 7DE91FAA29CA70F3004483EB /* TreeSet */, + 7DE91FA929CA70F3004483EB /* HashTreeCollections.docc */, + 7DE91FA829CA70F3004483EB /* CMakeLists.txt */, + ); + path = HashTreeCollections; + sourceTree = ""; + }; + 7DE91FAA29CA70F3004483EB /* TreeSet */ = { + isa = PBXGroup; + children = ( + 7DE91FC229CA70F3004483EB /* TreeSet.swift */, + 7DE91FC429CA70F3004483EB /* TreeSet+Codable.swift */, + 7DE91FBB29CA70F3004483EB /* TreeSet+Collection.swift */, + 7DE91FB929CA70F3004483EB /* TreeSet+CustomReflectable.swift */, + 7DE91FB529CA70F3004483EB /* TreeSet+Debugging.swift */, + 7DE91FAC29CA70F3004483EB /* TreeSet+Descriptions.swift */, + 7DE91FAF29CA70F3004483EB /* TreeSet+Equatable.swift */, + 7DE91FBC29CA70F3004483EB /* TreeSet+ExpressibleByArrayLiteral.swift */, + 7DE91FB229CA70F3004483EB /* TreeSet+Extras.swift */, + 7DE91FC029CA70F3004483EB /* TreeSet+Filter.swift */, + 7DE91FC329CA70F3004483EB /* TreeSet+Hashable.swift */, + 7DE91FAE29CA70F3004483EB /* TreeSet+Sendable.swift */, + 7DE91FBF29CA70F3004483EB /* TreeSet+Sequence.swift */, + 7DE91FBE29CA70F3004483EB /* TreeSet+SetAlgebra basics.swift */, + 7DE91FB729CA70F3004483EB /* TreeSet+SetAlgebra formIntersection.swift */, + 7DE91FBA29CA70F3004483EB /* TreeSet+SetAlgebra formSymmetricDifference.swift */, + 7DE91FB129CA70F3004483EB /* TreeSet+SetAlgebra formUnion.swift */, + 7DE91FC129CA70F3004483EB /* TreeSet+SetAlgebra Initializers.swift */, + 7DE91FB029CA70F3004483EB /* TreeSet+SetAlgebra intersection.swift */, + 7DE91FC729CA70F3004483EB /* TreeSet+SetAlgebra isDisjoint.swift */, + 7DE91FAB29CA70F3004483EB /* TreeSet+SetAlgebra isEqualSet.swift */, + 7DE91FAD29CA70F3004483EB /* TreeSet+SetAlgebra isStrictSubset.swift */, + 7DE91FB629CA70F3004483EB /* TreeSet+SetAlgebra isStrictSuperset.swift */, + 7DE91FC529CA70F3004483EB /* TreeSet+SetAlgebra isSubset.swift */, + 7DE91FB829CA70F3004483EB /* TreeSet+SetAlgebra isSuperset.swift */, + 7DE91FB429CA70F3004483EB /* TreeSet+SetAlgebra subtract.swift */, + 7DE91FB329CA70F3004483EB /* TreeSet+SetAlgebra subtracting.swift */, + 7DE91FBD29CA70F3004483EB /* TreeSet+SetAlgebra symmetricDifference.swift */, + 7DE91FC629CA70F3004483EB /* TreeSet+SetAlgebra union.swift */, + ); + path = TreeSet; + sourceTree = ""; + }; + 7DE91FC829CA70F3004483EB /* HashNode */ = { + isa = PBXGroup; + children = ( + 7DE91FEB29CA70F3004483EB /* _AncestorHashSlots.swift */, + 7DE91FE529CA70F3004483EB /* _Bitmap.swift */, + 7DE91FD829CA70F3004483EB /* _Bucket.swift */, + 7DE91FC929CA70F3004483EB /* _Hash.swift */, + 7DE91FCD29CA70F3004483EB /* _HashTreeIterator.swift */, + 7DE91FD429CA70F3004483EB /* _HashTreeStatistics.swift */, + 7DE91FEC29CA70F3004483EB /* _HashLevel.swift */, + 7DE91FED29CA70F3004483EB /* _HashNode.swift */, + 7DE91FDB29CA70F3004483EB /* _HashNode+Builder.swift */, + 7DE91FD729CA70F3004483EB /* _HashNode+Debugging.swift */, + 7DE91FCA29CA70F3004483EB /* _HashNode+Initializers.swift */, + 7DE91FDC29CA70F3004483EB /* _HashNode+Invariants.swift */, + 7DE91FE729CA70F3004483EB /* _HashNode+Lookups.swift */, + 7DE91FD529CA70F3004483EB /* _HashNode+Primitive Insertions.swift */, + 7DE91FD129CA70F3004483EB /* _HashNode+Primitive Removals.swift */, + 7DE91FD029CA70F3004483EB /* _HashNode+Primitive Replacement.swift */, + 7DE91FEF29CA70F3004483EB /* _HashNode+Storage.swift */, + 7DE91FDF29CA70F3004483EB /* _HashNode+Structural compactMapValues.swift */, + 7DE91FD629CA70F3004483EB /* _HashNode+Structural filter.swift */, + 7DE91FEE29CA70F3004483EB /* _HashNode+Structural intersection.swift */, + 7DE91FE929CA70F3004483EB /* _HashNode+Structural isDisjoint.swift */, + 7DE91FD229CA70F3004483EB /* _HashNode+Structural isEqualSet.swift */, + 7DE91FE229CA70F3004483EB /* _HashNode+Structural isSubset.swift */, + 7DE91FE429CA70F3004483EB /* _HashNode+Structural mapValues.swift */, + 7DE91FEA29CA70F3004483EB /* _HashNode+Structural merge.swift */, + 7DE91FE329CA70F3004483EB /* _HashNode+Structural subtracting.swift */, + 7DE91FCE29CA70F3004483EB /* _HashNode+Structural symmetricDifference.swift */, + 7DE91FE129CA70F3004483EB /* _HashNode+Structural union.swift */, + 7DE91FD329CA70F3004483EB /* _HashNode+Subtree Insertions.swift */, + 7DE91FDA29CA70F3004483EB /* _HashNode+Subtree Modify.swift */, + 7DE91FCC29CA70F3004483EB /* _HashNode+Subtree Removals.swift */, + 7DE91FDD29CA70F3004483EB /* _HashNode+UnsafeHandle.swift */, + 7DE91FE029CA70F3004483EB /* _RawHashNode.swift */, + 7DE91FDE29CA70F3004483EB /* _RawHashNode+UnsafeHandle.swift */, + 7DE91FCF29CA70F3004483EB /* _HashSlot.swift */, + 7DE91FCB29CA70F3004483EB /* _HashStack.swift */, + 7DE91FE629CA70F3004483EB /* _StorageHeader.swift */, + 7DE91FD929CA70F3004483EB /* _UnmanagedHashNode.swift */, + 7DE91FE829CA70F3004483EB /* _UnsafePath.swift */, + ); + path = HashNode; + sourceTree = ""; + }; + 7DE91FF029CA70F3004483EB /* TreeDictionary */ = { + isa = PBXGroup; + children = ( + 7DE91FF429CA70F3004483EB /* TreeDictionary.swift */, + 7DE91FF529CA70F3004483EB /* TreeDictionary+Codable.swift */, + 7DE91FFE29CA70F3004483EB /* TreeDictionary+Collection.swift */, + 7DE91FF929CA70F3004483EB /* TreeDictionary+CustomReflectable.swift */, + 7DE91FF729CA70F3004483EB /* TreeDictionary+Debugging.swift */, + 7DE91FF629CA70F3004483EB /* TreeDictionary+Descriptions.swift */, + 7DE91FF129CA70F3004483EB /* TreeDictionary+Equatable.swift */, + 7DE91FFA29CA70F3004483EB /* TreeDictionary+ExpressibleByDictionaryLiteral.swift */, + 7DE91FF329CA70F3004483EB /* TreeDictionary+Filter.swift */, + 7DE91FF829CA70F3004483EB /* TreeDictionary+Hashable.swift */, + 7DE9200029CA70F3004483EB /* TreeDictionary+Initializers.swift */, + 7DE9200129CA70F3004483EB /* TreeDictionary+Keys.swift */, + 7DE91FFF29CA70F3004483EB /* TreeDictionary+MapValues.swift */, + 7DE91FFD29CA70F3004483EB /* TreeDictionary+Merge.swift */, + 7DE91FFC29CA70F3004483EB /* TreeDictionary+Sendable.swift */, + 7DE91FF229CA70F3004483EB /* TreeDictionary+Sequence.swift */, + 7DE91FFB29CA70F3004483EB /* TreeDictionary+Values.swift */, + ); + path = TreeDictionary; + sourceTree = ""; + }; + 7DE9200229CA70F3004483EB /* HeapModule */ = { + isa = PBXGroup; + children = ( + 7DE9200A29CA70F3004483EB /* _HeapNode.swift */, + 7DE9200829CA70F3004483EB /* Heap.swift */, + 7DE9200529CA70F3004483EB /* Heap+Descriptions.swift */, + 7DE9200929CA70F3004483EB /* Heap+ExpressibleByArrayLiteral.swift */, + 7DE9200629CA70F3004483EB /* Heap+Invariants.swift */, + 7DE9200429CA70F3004483EB /* Heap+UnsafeHandle.swift */, + 7DE9200329CA70F3004483EB /* CMakeLists.txt */, + 7DE9200729CA70F3004483EB /* HeapModule.docc */, + ); + path = HeapModule; + sourceTree = ""; + }; + 7DE921AC29CA78B2004483EB /* Utils */ = { + isa = PBXGroup; + children = ( + 7D5A64D429CCEF1500CB2595 /* generate-sources.sh */, + 7D5A64D629CCEF1500CB2595 /* gyb */, + 7D5A64D529CCEF1500CB2595 /* gyb_utils.py */, + 7D5A64D729CCEF1500CB2595 /* gyb.py */, + 7D5A64D329CCEE9A00CB2595 /* README.md */, + 7DE921B629CA78B2004483EB /* generate-docs.sh */, + 7DE921AD29CA78B2004483EB /* run-benchmarks.sh */, + 7DE921B329CA78B2004483EB /* run-full-tests.sh */, + 7DE921B229CA78B2004483EB /* shuffle-sources.sh */, + ); + name = Utils; + path = ../Utils; + sourceTree = ""; + }; + 7DE921CA29CA8575004483EB /* Tests */ = { + isa = PBXGroup; + children = ( + 7DEBDB1F29CCE43600ADC226 /* _CollectionsTestSupport */, + 7DE921DA29CA8575004483EB /* BitCollectionsTests */, + 7DE921CB29CA8575004483EB /* CollectionsTestSupportTests */, + 7DE921F529CA8575004483EB /* DequeTests */, + 7DE921D029CA8575004483EB /* HashTreeCollectionsTests */, + 7DE921F229CA8575004483EB /* HeapTests */, + 7DE921E429CA8575004483EB /* OrderedCollectionsTests */, + 7DE921DE29CA8575004483EB /* RopeModuleTests */, + 7D5A64D829CCF0FE00CB2595 /* README.md */, + ); + name = Tests; + path = ../Tests; + sourceTree = ""; + }; + 7DE921CB29CA8575004483EB /* CollectionsTestSupportTests */ = { + isa = PBXGroup; + children = ( + 7DE921CF29CA8575004483EB /* CombinatoricsChecks.swift */, + 7DE921CE29CA8575004483EB /* IndexRangeCollectionTests.swift */, + 7DE921CD29CA8575004483EB /* MinimalTypeConformances.swift */, + 7DE921CC29CA8575004483EB /* UtilitiesTests.swift */, + ); + path = CollectionsTestSupportTests; + sourceTree = ""; + }; + 7DE921D029CA8575004483EB /* HashTreeCollectionsTests */ = { + isa = PBXGroup; + children = ( + 7DE921D629CA8575004483EB /* Colliders.swift */, + 7DE921D129CA8575004483EB /* Hash.swift */, + 7DE921D329CA8575004483EB /* TreeDictionary Smoke Tests.swift */, + 7DE921D529CA8575004483EB /* TreeDictionary Tests.swift */, + 7DE921D429CA8575004483EB /* TreeDictionary.Keys Tests.swift */, + 7DE921D829CA8575004483EB /* TreeDictionary.Values Tests.swift */, + 7DE921D729CA8575004483EB /* TreeHashedCollections Fixtures.swift */, + 7DE921D929CA8575004483EB /* TreeSet Tests.swift */, + 7DE921D229CA8575004483EB /* Utilities.swift */, + ); + path = HashTreeCollectionsTests; + sourceTree = ""; + }; + 7DE921DA29CA8575004483EB /* BitCollectionsTests */ = { + isa = PBXGroup; + children = ( + 7DE921DD29CA8575004483EB /* BitArrayTests.swift */, + 7DE921DB29CA8575004483EB /* BitSet.Counted Tests.swift */, + 7DE921DC29CA8575004483EB /* BitSetTests.swift */, + ); + path = BitCollectionsTests; + sourceTree = ""; + }; + 7DE921DE29CA8575004483EB /* RopeModuleTests */ = { + isa = PBXGroup; + children = ( + 7DE921DF29CA8575004483EB /* TestRope.swift */, + 7DE921E129CA8575004483EB /* Availability.swift */, + 7DE921E229CA8575004483EB /* TestBigString.swift */, + 7DE921E329CA8575004483EB /* SampleStrings.swift */, + ); + path = RopeModuleTests; + sourceTree = ""; + }; + 7DE921E429CA8575004483EB /* OrderedCollectionsTests */ = { + isa = PBXGroup; + children = ( + 7DE921E529CA8575004483EB /* OrderedDictionary */, + 7DE921EA29CA8575004483EB /* OrderedSet */, + 7DE921F029CA8575004483EB /* HashTable */, + ); + path = OrderedCollectionsTests; + sourceTree = ""; + }; + 7DE921E529CA8575004483EB /* OrderedDictionary */ = { + isa = PBXGroup; + children = ( + 7DE921E629CA8575004483EB /* OrderedDictionary Tests.swift */, + 7DE921E729CA8575004483EB /* OrderedDictionary Utils.swift */, + 7DE921E929CA8575004483EB /* OrderedDictionary+Elements Tests.swift */, + 7DE921E829CA8575004483EB /* OrderedDictionary+Values Tests.swift */, + ); + path = OrderedDictionary; + sourceTree = ""; + }; + 7DE921EA29CA8575004483EB /* OrderedSet */ = { + isa = PBXGroup; + children = ( + 7DE921EC29CA8575004483EB /* OrderedSet Diffing Tests.swift */, + 7DE921EE29CA8575004483EB /* OrderedSet.UnorderedView Tests.swift */, + 7DE921EB29CA8575004483EB /* OrderedSetInternals.swift */, + 7DE921EF29CA8575004483EB /* OrderedSetTests.swift */, + 7DE921ED29CA8575004483EB /* RandomAccessCollection+Extras.swift */, + ); + path = OrderedSet; + sourceTree = ""; + }; + 7DE921F029CA8575004483EB /* HashTable */ = { + isa = PBXGroup; + children = ( + 7DE921F129CA8575004483EB /* HashTableTests.swift */, + ); + path = HashTable; + sourceTree = ""; + }; + 7DE921F229CA8575004483EB /* HeapTests */ = { + isa = PBXGroup; + children = ( + 7DE921F329CA8575004483EB /* HeapTests.swift */, + 7DE921F429CA8575004483EB /* HeapNodeTests.swift */, + ); + path = HeapTests; + sourceTree = ""; + }; + 7DE921F529CA8575004483EB /* DequeTests */ = { + isa = PBXGroup; + children = ( + 7DE921F629CA8576004483EB /* DequeInternals.swift */, + 7DE921F829CA8576004483EB /* DequeTests.swift */, + 7DE921F929CA8576004483EB /* MutableCollectionTests.swift */, + 7DE921F729CA8576004483EB /* RangeReplaceableCollectionTests.swift */, + ); + path = DequeTests; + sourceTree = ""; + }; + 7DEBDAC729CBEE5200ADC226 /* Compatibility */ = { + isa = PBXGroup; + children = ( + 7DEBDACC29CBEE5200ADC226 /* autogenerated */, + 7DEBDACA29CBEE5200ADC226 /* Array+WithContiguousStorage Compatibility.swift.gyb */, + 7DEBDAC929CBEE5200ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift.gyb */, + 7DEBDAC829CBEE5200ADC226 /* UnsafeMutablePointer+SE-0370.swift.gyb */, + 7DEBDACB29CBEE5200ADC226 /* UnsafeRawPointer extensions.swift.gyb */, + ); + path = Compatibility; + sourceTree = ""; + }; + 7DEBDACC29CBEE5200ADC226 /* autogenerated */ = { + isa = PBXGroup; + children = ( + 7DEBDACE29CBEE5200ADC226 /* Array+WithContiguousStorage Compatibility.swift */, + 7DEBDACD29CBEE5200ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift */, + 7DEBDACF29CBEE5200ADC226 /* UnsafeMutablePointer+SE-0370.swift */, + 7DEBDAD029CBEE5200ADC226 /* UnsafeRawPointer extensions.swift */, + ); + path = autogenerated; + sourceTree = ""; + }; + 7DEBDAD329CBEE5300ADC226 /* autogenerated */ = { + isa = PBXGroup; + children = ( + 7DEBDAD829CBEE5300ADC226 /* Debugging.swift */, + 7DEBDAD729CBEE5300ADC226 /* Descriptions.swift */, + 7DEBDAD629CBEE5300ADC226 /* RandomAccessCollection+Offsets.swift */, + 7DEBDAD529CBEE5300ADC226 /* UnsafeBufferPointer+Extras.swift */, + 7DEBDAD429CBEE5300ADC226 /* UnsafeMutableBufferPointer+Extras.swift */, + ); + path = autogenerated; + sourceTree = ""; + }; + 7DEBDADA29CBEE5300ADC226 /* UnsafeBitSet */ = { + isa = PBXGroup; + children = ( + 7DEBDADE29CBEE5300ADC226 /* autogenerated */, + 7DEBDADB29CBEE5300ADC226 /* _UnsafeBitSet.swift.gyb */, + 7DEBDADC29CBEE5300ADC226 /* _UnsafeBitSet+_Word.swift.gyb */, + 7DEBDADD29CBEE5300ADC226 /* _UnsafeBitSet+Index.swift.gyb */, + ); + path = UnsafeBitSet; + sourceTree = ""; + }; + 7DEBDADE29CBEE5300ADC226 /* autogenerated */ = { + isa = PBXGroup; + children = ( + 7DEBDAE029CBEE5300ADC226 /* _UnsafeBitSet.swift */, + 7DEBDAE129CBEE5300ADC226 /* _UnsafeBitSet+_Word.swift */, + 7DEBDADF29CBEE5300ADC226 /* _UnsafeBitSet+Index.swift */, + ); + path = autogenerated; + sourceTree = ""; + }; + 7DEBDAE229CBEE5300ADC226 /* IntegerTricks */ = { + isa = PBXGroup; + children = ( + 7DEBDAE729CBEE5300ADC226 /* autogenerated */, + 7DEBDAE429CBEE5300ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift.gyb */, + 7DEBDAE629CBEE5300ADC226 /* Integer rank.swift.gyb */, + 7DEBDAE529CBEE5300ADC226 /* UInt+first and last set bit.swift.gyb */, + 7DEBDAE329CBEE5300ADC226 /* UInt+reversed.swift.gyb */, + ); + path = IntegerTricks; + sourceTree = ""; + }; + 7DEBDAE729CBEE5300ADC226 /* autogenerated */ = { + isa = PBXGroup; + children = ( + 7DEBDAEB29CBEE5300ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */, + 7DEBDAE929CBEE5300ADC226 /* Integer rank.swift */, + 7DEBDAEA29CBEE5300ADC226 /* UInt+first and last set bit.swift */, + 7DEBDAE829CBEE5300ADC226 /* UInt+reversed.swift */, + ); + path = autogenerated; + sourceTree = ""; + }; + 7DEBDB1F29CCE43600ADC226 /* _CollectionsTestSupport */ = { + isa = PBXGroup; + children = ( + 7DEBDB2029CCE43600ADC226 /* AssertionContexts */, + 7DEBDB2529CCE43600ADC226 /* Utilities */, + 7DEBDB3329CCE43600ADC226 /* ConformanceCheckers */, + 7DEBDB3A29CCE43600ADC226 /* MinimalTypes */, + ); + path = _CollectionsTestSupport; + sourceTree = ""; + }; + 7DEBDB2029CCE43600ADC226 /* AssertionContexts */ = { + isa = PBXGroup; + children = ( + 7DEBDB2129CCE43600ADC226 /* Combinatorics.swift */, + 7DEBDB2229CCE43600ADC226 /* TestContext.swift */, + 7DEBDB2329CCE43600ADC226 /* Assertions.swift */, + 7DEBDB2429CCE43600ADC226 /* CollectionTestCase.swift */, + ); + path = AssertionContexts; + sourceTree = ""; + }; + 7DEBDB2529CCE43600ADC226 /* Utilities */ = { + isa = PBXGroup; + children = ( + 7DEBDB2629CCE43600ADC226 /* RandomStableSample.swift */, + 7DEBDB2729CCE43600ADC226 /* LifetimeTracked.swift */, + 7DEBDB2829CCE43600ADC226 /* IndexRangeCollection.swift */, + 7DEBDB2929CCE43600ADC226 /* Integer Square Root.swift */, + 7DEBDB2A29CCE43600ADC226 /* DictionaryAPIChecker.swift */, + 7DEBDB2B29CCE43600ADC226 /* StringConvertibleValue.swift */, + 7DEBDB2C29CCE43600ADC226 /* AllOnesRandomNumberGenerator.swift */, + 7DEBDB2D29CCE43600ADC226 /* Box.swift */, + 7DEBDB2E29CCE43600ADC226 /* LifetimeTracker.swift */, + 7DEBDB2F29CCE43600ADC226 /* RepeatableRandomNumberGenerator.swift */, + 7DEBDB3029CCE43600ADC226 /* SortedCollectionAPIChecker.swift */, + 7DEBDB3129CCE43600ADC226 /* HashableBox.swift */, + 7DEBDB3229CCE43600ADC226 /* SetAPIChecker.swift */, + ); + path = Utilities; + sourceTree = ""; + }; + 7DEBDB3329CCE43600ADC226 /* ConformanceCheckers */ = { + isa = PBXGroup; + children = ( + 7DEBDB3429CCE43600ADC226 /* CheckCollection.swift */, + 7DEBDB3529CCE43600ADC226 /* CheckHashable.swift */, + 7DEBDB3629CCE43600ADC226 /* CheckComparable.swift */, + 7DEBDB3729CCE43600ADC226 /* CheckEquatable.swift */, + 7DEBDB3829CCE43600ADC226 /* CheckSequence.swift */, + 7DEBDB3929CCE43600ADC226 /* CheckBidirectionalCollection.swift */, + ); + path = ConformanceCheckers; + sourceTree = ""; + }; + 7DEBDB3A29CCE43600ADC226 /* MinimalTypes */ = { + isa = PBXGroup; + children = ( + 7DEBDB3B29CCE43600ADC226 /* _CollectionState.swift */, + 7DEBDB3C29CCE43600ADC226 /* MinimalRandomAccessCollection.swift */, + 7DEBDB3D29CCE43600ADC226 /* MinimalMutableRandomAccessCollection.swift */, + 7DEBDB3E29CCE43600ADC226 /* MinimalSequence.swift */, + 7DEBDB3F29CCE43600ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift */, + 7DEBDB4029CCE43600ADC226 /* MinimalBidirectionalCollection.swift */, + 7DEBDB4129CCE43600ADC226 /* MinimalIndex.swift */, + 7DEBDB4229CCE43600ADC226 /* ResettableValue.swift */, + 7DEBDB4329CCE43600ADC226 /* MinimalRangeReplaceableRandomAccessCollection.swift */, + 7DEBDB4429CCE43600ADC226 /* MinimalEncoder.swift */, + 7DEBDB4529CCE43600ADC226 /* MinimalIterator.swift */, + 7DEBDB4629CCE43600ADC226 /* _MinimalCollectionCore.swift */, + 7DEBDB4729CCE43600ADC226 /* MinimalDecoder.swift */, + 7DEBDB4829CCE43600ADC226 /* MinimalCollection.swift */, + ); + path = MinimalTypes; + sourceTree = ""; + }; + 7DEBDB9329CCE4A600ADC226 /* Xcode */ = { + isa = PBXGroup; + children = ( + 7DEBDB9729CCE4A600ADC226 /* CollectionsTests.xcconfig */, + 7DEBDB9829CCE4A600ADC226 /* Shared.xcconfig */, + 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */, + 7D5A64D229CCE8CC00CB2595 /* README.md */, + ); + name = Xcode; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 7DE91B2129CA6721004483EB /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 7DE91B2529CA6721004483EB /* Collections */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7DE91B3829CA6721004483EB /* Build configuration list for PBXNativeTarget "Collections" */; + buildPhases = ( + 7DE91B2129CA6721004483EB /* Headers */, + 7DE91B2229CA6721004483EB /* Sources */, + 7DE91B2329CA6721004483EB /* Frameworks */, + 7DE91B2429CA6721004483EB /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Collections; + productName = Collections; + productReference = 7DE91B2629CA6721004483EB /* Collections.framework */; + productType = "com.apple.product-type.framework"; + }; + 7DE91B2D29CA6721004483EB /* CollectionsTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7DE91B3B29CA6721004483EB /* Build configuration list for PBXNativeTarget "CollectionsTests" */; + buildPhases = ( + 7DE91B2A29CA6721004483EB /* Sources */, + 7DE91B2B29CA6721004483EB /* Frameworks */, + 7DE91B2C29CA6721004483EB /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 7DE91B3129CA6721004483EB /* PBXTargetDependency */, + ); + name = CollectionsTests; + productName = CollectionsTests; + productReference = 7DE91B2E29CA6721004483EB /* CollectionsTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 7DE91B1D29CA6721004483EB /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1430; + LastUpgradeCheck = 1430; + TargetAttributes = { + 7DE91B2529CA6721004483EB = { + CreatedOnToolsVersion = 14.3; + }; + 7DE91B2D29CA6721004483EB = { + CreatedOnToolsVersion = 14.3; + }; + }; + }; + buildConfigurationList = 7DE91B2029CA6721004483EB /* Build configuration list for PBXProject "Collections" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 7DE91B1C29CA6721004483EB; + productRefGroup = 7DE91B2729CA6721004483EB /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 7DE91B2529CA6721004483EB /* Collections */, + 7DE91B2D29CA6721004483EB /* CollectionsTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 7DE91B2429CA6721004483EB /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7DE91B2C29CA6721004483EB /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 7DE91B2229CA6721004483EB /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7DE920F129CA70F4004483EB /* BitArray+Initializers.swift in Sources */, + 7DE9214529CA70F4004483EB /* _HashNode+Structural symmetricDifference.swift in Sources */, + 7DE9201029CA70F3004483EB /* OrderedDictionary+Deprecations.swift in Sources */, + 7DE9205929CA70F3004483EB /* Deque+Descriptions.swift in Sources */, + 7DEBDAF529CBEE5300ADC226 /* UnsafeRawPointer extensions.swift in Sources */, + 7DE9212729CA70F4004483EB /* TreeSet+Equatable.swift in Sources */, + 7DE9213429CA70F4004483EB /* TreeSet+ExpressibleByArrayLiteral.swift in Sources */, + 7DE9209729CA70F4004483EB /* _RopePath.swift in Sources */, + 7DE9216629CA70F4004483EB /* _HashNode+Storage.swift in Sources */, + 7DE920CE29CA70F4004483EB /* BitSet+CustomReflectable.swift in Sources */, + 7DE9215029CA70F4004483EB /* _UnmanagedHashNode.swift in Sources */, + 7DE920EF29CA70F4004483EB /* BitArray+Codable.swift in Sources */, + 7DE920C029CA70F4004483EB /* BitSet+SetAlgebra conformance.swift in Sources */, + 7DE9203C29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift in Sources */, + 7DE9209029CA70F4004483EB /* Rope.swift in Sources */, + 7DE9213B29CA70F4004483EB /* TreeSet+Hashable.swift in Sources */, + 7DE9200D29CA70F3004483EB /* OrderedDictionary+Equatable.swift in Sources */, + 7DE9207C29CA70F4004483EB /* BigSubstring.swift in Sources */, + 7DE9205F29CA70F4004483EB /* BigString+Index.swift in Sources */, + 7DE920C429CA70F4004483EB /* BitSet+SetAlgebra isStrictSuperset.swift in Sources */, + 7DE9216229CA70F4004483EB /* _AncestorHashSlots.swift in Sources */, + 7DE9216B29CA70F4004483EB /* TreeDictionary+Codable.swift in Sources */, + 7DE9201A29CA70F3004483EB /* OrderedDictionary+Sendable.swift in Sources */, + 7DE9205D29CA70F4004483EB /* Deque._Storage.swift in Sources */, + 7DE9203B29CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtracting.swift in Sources */, + 7DE9213A29CA70F4004483EB /* TreeSet.swift in Sources */, + 7DE9213829CA70F4004483EB /* TreeSet+Filter.swift in Sources */, + 7DE9206D29CA70F4004483EB /* BigString+Chunk+Description.swift in Sources */, + 7DE9208A29CA70F4004483EB /* BigString+Comparable.swift in Sources */, + 7DE9213629CA70F4004483EB /* TreeSet+SetAlgebra basics.swift in Sources */, + 7DE9202C29CA70F3004483EB /* OrderedSet+Initializers.swift in Sources */, + 7DE9213229CA70F4004483EB /* TreeSet+SetAlgebra formSymmetricDifference.swift in Sources */, + 7DE9203429CA70F3004483EB /* OrderedSet+Partial SetAlgebra formUnion.swift in Sources */, + 7DE9214A29CA70F4004483EB /* _HashNode+Subtree Insertions.swift in Sources */, + 7DE9215829CA70F4004483EB /* _HashNode+Structural union.swift in Sources */, + 7DE9204629CA70F3004483EB /* _Hashtable+Header.swift in Sources */, + 7DE9208129CA70F4004483EB /* BigString+CustomStringConvertible.swift in Sources */, + 7DE920A929CA70F4004483EB /* Optional Utilities.swift in Sources */, + 7DE920BD29CA70F4004483EB /* BitSet+SetAlgebra symmetricDifference.swift in Sources */, + 7DE9208229CA70F4004483EB /* BigString+BidirectionalCollection.swift in Sources */, + 7DE9203E29CA70F3004483EB /* OrderedSet+Partial SetAlgebra subtract.swift in Sources */, + 7DE9216929CA70F4004483EB /* TreeDictionary+Filter.swift in Sources */, + 7DE9203129CA70F3004483EB /* OrderedSet+Partial MutableCollection.swift in Sources */, + 7DE9209B29CA70F4004483EB /* Rope+Split.swift in Sources */, + 7DE9206629CA70F4004483EB /* BigString+Debugging.swift in Sources */, + 7DE9205229CA70F3004483EB /* _UnsafeWrappedBuffer.swift in Sources */, + 7DE9201129CA70F3004483EB /* OrderedDictionary+Initializers.swift in Sources */, + 7DE9212B29CA70F4004483EB /* TreeSet+SetAlgebra subtracting.swift in Sources */, + 7DE920F629CA70F4004483EB /* BitArray+Equatable.swift in Sources */, + 7DE9212329CA70F4004483EB /* TreeSet+SetAlgebra isEqualSet.swift in Sources */, + 7DE9214629CA70F4004483EB /* _HashSlot.swift in Sources */, + 7DEBDB0129CBEE5300ADC226 /* _UnsafeBitSet+Index.swift in Sources */, + 7DE9204129CA70F3004483EB /* _UnsafeBitset.swift in Sources */, + 7DE9208F29CA70F4004483EB /* RopeElement.swift in Sources */, + 7DE9207229CA70F4004483EB /* BigString+Managing Breaks.swift in Sources */, + 7DE9213F29CA70F4004483EB /* TreeSet+SetAlgebra isDisjoint.swift in Sources */, + 7DE9214D29CA70F4004483EB /* _HashNode+Structural filter.swift in Sources */, + 7DE9209F29CA70F4004483EB /* Rope+MutatingForEach.swift in Sources */, + 7DE9214E29CA70F4004483EB /* _HashNode+Debugging.swift in Sources */, + 7DE920A029CA70F4004483EB /* Rope+Join.swift in Sources */, + 7DE9213E29CA70F4004483EB /* TreeSet+SetAlgebra union.swift in Sources */, + 7DE9214829CA70F4004483EB /* _HashNode+Primitive Removals.swift in Sources */, + 7DE9216029CA70F4004483EB /* _HashNode+Structural isDisjoint.swift in Sources */, + 7DE9203529CA70F3004483EB /* OrderedSet+CustomReflectable.swift in Sources */, + 7DE920C929CA70F4004483EB /* BitSet+BidirectionalCollection.swift in Sources */, + 7DE920ED29CA70F4004483EB /* BitArray+Extras.swift in Sources */, + 7DE9206829CA70F4004483EB /* BigString+Chunk+Append and Insert.swift in Sources */, + 7DE9200E29CA70F3004483EB /* OrderedDictionary+ExpressibleByDictionaryLiteral.swift in Sources */, + 7DE920D229CA70F4004483EB /* BitSet+SetAlgebra basics.swift in Sources */, + 7DE9212A29CA70F4004483EB /* TreeSet+Extras.swift in Sources */, + 7DE9209A29CA70F4004483EB /* Rope+Append.swift in Sources */, + 7DE9203F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift in Sources */, + 7DE9208629CA70F4004483EB /* BigString+LosslessStringConvertible.swift in Sources */, + 7DE9204329CA70F3004483EB /* _HashTable+Bucket.swift in Sources */, + 7DE9216A29CA70F4004483EB /* TreeDictionary.swift in Sources */, + 7DEBDB9D29CCE73D00ADC226 /* Collections.swift in Sources */, + 7DE9215C29CA70F4004483EB /* _Bitmap.swift in Sources */, + 7DE9207029CA70F4004483EB /* BigString+Chunk+RopeElement.swift in Sources */, + 7DEBDB0B29CBEE5300ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift in Sources */, + 7DE9213729CA70F4004483EB /* TreeSet+Sequence.swift in Sources */, + 7DE9217629CA70F4004483EB /* TreeDictionary+Initializers.swift in Sources */, + 7DE9207E29CA70F4004483EB /* BigString+UTF16View.swift in Sources */, + 7DEBDAFA29CBEE5300ADC226 /* RandomAccessCollection+Offsets.swift in Sources */, + 7DE9216F29CA70F4004483EB /* TreeDictionary+CustomReflectable.swift in Sources */, + 7DE920D729CA70F4004483EB /* BitSet+SetAlgebra isSuperset.swift in Sources */, + 7DE920F429CA70F4004483EB /* BitArray+Hashable.swift in Sources */, + 7DE920E629CA70F4004483EB /* BitArray+ChunkedBitsIterators.swift in Sources */, + 7DE9206A29CA70F4004483EB /* BigString+Chunk+Counts.swift in Sources */, + 7DE9207529CA70F4004483EB /* BigString+Insert.swift in Sources */, + 7DE9216129CA70F4004483EB /* _HashNode+Structural merge.swift in Sources */, + 7DE9202F29CA70F3004483EB /* OrderedSet+ExpressibleByArrayLiteral.swift in Sources */, + 7DEBDAFC29CBEE5300ADC226 /* Debugging.swift in Sources */, + 7DE9202B29CA70F3004483EB /* OrderedSet+Equatable.swift in Sources */, + 7DE920EA29CA70F4004483EB /* BitArray.swift in Sources */, + 7DE920CB29CA70F4004483EB /* BitSet+Random.swift in Sources */, + 7DE9201629CA70F3004483EB /* OrderedDictionary+Elements.swift in Sources */, + 7DE9216D29CA70F4004483EB /* TreeDictionary+Debugging.swift in Sources */, + 7DE9213129CA70F4004483EB /* TreeSet+CustomReflectable.swift in Sources */, + 7DE9215329CA70F4004483EB /* _HashNode+Invariants.swift in Sources */, + 7DE9209629CA70F4004483EB /* Rope+Builder.swift in Sources */, + 7DE9215129CA70F4004483EB /* _HashNode+Subtree Modify.swift in Sources */, + 7DE9204729CA70F3004483EB /* _HashTable+Testing.swift in Sources */, + 7DE920E929CA70F4004483EB /* BitArray+Invariants.swift in Sources */, + 7DE9215429CA70F4004483EB /* _HashNode+UnsafeHandle.swift in Sources */, + 7DE9209829CA70F4004483EB /* Rope+_Node.swift in Sources */, + 7DE9204529CA70F3004483EB /* _HashTable+Constants.swift in Sources */, + 7DE9214229CA70F4004483EB /* _HashStack.swift in Sources */, + 7DE9206F29CA70F4004483EB /* BigString+Chunk+Breaks.swift in Sources */, + 7DE9202529CA70F3004483EB /* OrderedSet+Hashable.swift in Sources */, + 7DE9203A29CA70F3004483EB /* OrderedSet+Partial SetAlgebra+Basics.swift in Sources */, + 7DE920B529CA70F4004483EB /* _SortedCollection.swift in Sources */, + 7DE9206929CA70F4004483EB /* BigString+Chunk+Indexing by UTF16.swift in Sources */, + 7DE9202A29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSuperset.swift in Sources */, + 7DEBDAF229CBEE5300ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift in Sources */, + 7DE9207D29CA70F4004483EB /* BigSubstring+UTF16View.swift in Sources */, + 7DEBDAF829CBEE5300ADC226 /* UnsafeMutableBufferPointer+Extras.swift in Sources */, + 7DE9217229CA70F4004483EB /* TreeDictionary+Sendable.swift in Sources */, + 7DE920F529CA70F4004483EB /* BitArray+CustomDebugStringConvertible.swift in Sources */, + 7DE9207729CA70F4004483EB /* Range+BigString.swift in Sources */, + 7DE9204B29CA70F3004483EB /* _DequeBuffer.swift in Sources */, + 7DE920DF29CA70F4004483EB /* Slice+Utilities.swift in Sources */, + 7DE9215729CA70F4004483EB /* _RawHashNode.swift in Sources */, + 7DE9209529CA70F4004483EB /* RopeSummary.swift in Sources */, + 7DE920C229CA70F4004483EB /* BitSet+Sorted Collection APIs.swift in Sources */, + 7DE9205029CA70F3004483EB /* _DequeSlot.swift in Sources */, + 7DE920E229CA70F4004483EB /* _Word.swift in Sources */, + 7DE9201429CA70F3004483EB /* OrderedDictionary+Sequence.swift in Sources */, + 7DE920DB29CA70F4004483EB /* BitSet+Hashable.swift in Sources */, + 7DE9208C29CA70F4004483EB /* _RopeItem.swift in Sources */, + 7DEBDB0929CBEE5300ADC226 /* Integer rank.swift in Sources */, + 7DE920EC29CA70F4004483EB /* BitArray+Collection.swift in Sources */, + 7DE9201729CA70F3004483EB /* OrderedDictionary+Codable.swift in Sources */, + 7DE9208329CA70F4004483EB /* BigString+CustomDebugStringConvertible.swift in Sources */, + 7DE9215D29CA70F4004483EB /* _StorageHeader.swift in Sources */, + 7DE9213329CA70F4004483EB /* TreeSet+Collection.swift in Sources */, + 7DE9217929CA70F4004483EB /* Heap+UnsafeHandle.swift in Sources */, + 7DE920BC29CA70F4004483EB /* _UniqueCollection.swift in Sources */, + 7DE9216529CA70F4004483EB /* _HashNode+Structural intersection.swift in Sources */, + 7DEBDAF329CBEE5300ADC226 /* Array+WithContiguousStorage Compatibility.swift in Sources */, + 7DE920A629CA70F4004483EB /* String Utilities.swift in Sources */, + 7DE920E129CA70F4004483EB /* UInt+Tricks.swift in Sources */, + 7DE920EB29CA70F4004483EB /* BitArray+Fill.swift in Sources */, + 7DE9201929CA70F3004483EB /* OrderedDictionary+Values.swift in Sources */, + 7DE9213929CA70F4004483EB /* TreeSet+SetAlgebra Initializers.swift in Sources */, + 7DE9217729CA70F4004483EB /* TreeDictionary+Keys.swift in Sources */, + 7DE920DA29CA70F4004483EB /* BitSet._UnsafeHandle.swift in Sources */, + 7DE920D129CA70F4004483EB /* BitSet.Index.swift in Sources */, + 7DE9207429CA70F4004483EB /* BigString+ReplaceSubrange.swift in Sources */, + 7DE920DC29CA70F4004483EB /* BitSet+Invariants.swift in Sources */, + 7DE9216729CA70F4004483EB /* TreeDictionary+Equatable.swift in Sources */, + 7DE9204C29CA70F3004483EB /* Deque+Collection.swift in Sources */, + 7DE9201F29CA70F3004483EB /* OrderedSet+RandomAccessCollection.swift in Sources */, + 7DE9202E29CA70F3004483EB /* OrderedSet+UnorderedView.swift in Sources */, + 7DE9215F29CA70F4004483EB /* _UnsafePath.swift in Sources */, + 7DE9202829CA70F3004483EB /* OrderedSet+Partial SetAlgebra isSubset.swift in Sources */, + 7DE9204929CA70F3004483EB /* _HashTable+BucketIterator.swift in Sources */, + 7DE920F029CA70F4004483EB /* BitArray+RangeReplaceableCollection.swift in Sources */, + 7DE920C529CA70F4004483EB /* BitSet+Extras.swift in Sources */, + 7DE920CF29CA70F4004483EB /* BitSet+Initializers.swift in Sources */, + 7DE9201D29CA70F3004483EB /* OrderedDictionary.swift in Sources */, + 7DE920A529CA70F4004483EB /* Rope+Collection.swift in Sources */, + 7DE9203629CA70F3004483EB /* OrderedSet+ReserveCapacity.swift in Sources */, + 7DE9208D29CA70F4004483EB /* Rope+Debugging.swift in Sources */, + 7DE9208829CA70F4004483EB /* BigString+ExpressibleByStringLiteral.swift in Sources */, + 7DE9202329CA70F3004483EB /* OrderedSet+UnstableInternals.swift in Sources */, + 7DE9208529CA70F4004483EB /* BigString+TextOutputStream.swift in Sources */, + 7DE9212829CA70F4004483EB /* TreeSet+SetAlgebra intersection.swift in Sources */, + 7DE9200F29CA70F3004483EB /* OrderedDictionary+Hashable.swift in Sources */, + 7DE9206429CA70F4004483EB /* BigString+Invariants.swift in Sources */, + 7DE9212C29CA70F4004483EB /* TreeSet+SetAlgebra subtract.swift in Sources */, + 7DE9203D29CA70F3004483EB /* OrderedSet+Partial SetAlgebra intersection.swift in Sources */, + 7DE9214429CA70F4004483EB /* _HashTreeIterator.swift in Sources */, + 7DE9216829CA70F4004483EB /* TreeDictionary+Sequence.swift in Sources */, + 7DE9212D29CA70F4004483EB /* TreeSet+Debugging.swift in Sources */, + 7DE920D329CA70F4004483EB /* BitSet+SetAlgebra isDisjoint.swift in Sources */, + 7DE9203229CA70F3004483EB /* OrderedSet+Sendable.swift in Sources */, + 7DE9206E29CA70F4004483EB /* BigString+Chunk+Splitting.swift in Sources */, + 7DE920D829CA70F4004483EB /* BitSet+SetAlgebra subtracting.swift in Sources */, + 7DE9209E29CA70F4004483EB /* Rope+ForEachWhile.swift in Sources */, + 7DE9217B29CA70F4004483EB /* Heap+Invariants.swift in Sources */, + 7DE9212F29CA70F4004483EB /* TreeSet+SetAlgebra formIntersection.swift in Sources */, + 7DE920A329CA70F4004483EB /* Rope+Index.swift in Sources */, + 7DE9207329CA70F4004483EB /* BigString+RemoveSubrange.swift in Sources */, + 7DE9205829CA70F3004483EB /* Deque._UnsafeHandle.swift in Sources */, + 7DE9213529CA70F4004483EB /* TreeSet+SetAlgebra symmetricDifference.swift in Sources */, + 7DE920D429CA70F4004483EB /* BitSet+SetAlgebra union.swift in Sources */, + 7DE920C329CA70F4004483EB /* BitSet+SetAlgebra formUnion.swift in Sources */, + 7DE9217429CA70F4004483EB /* TreeDictionary+Collection.swift in Sources */, + 7DE9214729CA70F4004483EB /* _HashNode+Primitive Replacement.swift in Sources */, + 7DE9201229CA70F3004483EB /* OrderedDictionary+Elements.SubSequence.swift in Sources */, + 7DE9204429CA70F3004483EB /* _HashTable.swift in Sources */, + 7DE9206529CA70F4004483EB /* BigString+Ingester.swift in Sources */, + 7DEBDAFB29CBEE5300ADC226 /* Descriptions.swift in Sources */, + 7DE9209129CA70F4004483EB /* Rope+_UnsafeHandle.swift in Sources */, + 7DE920D529CA70F4004483EB /* BitSet.swift in Sources */, + 7DE9206B29CA70F4004483EB /* BigString+Chunk+Indexing by Characters.swift in Sources */, + 7DE9217D29CA70F4004483EB /* Heap.swift in Sources */, + 7DE9201529CA70F3004483EB /* OrderedDictionary+Partial RangeReplaceableCollection.swift in Sources */, + 7DE9208929CA70F4004483EB /* BigString+RangeReplaceableCollection.swift in Sources */, + 7DE9205E29CA70F4004483EB /* BigString+Metrics.swift in Sources */, + 7DE9213D29CA70F4004483EB /* TreeSet+SetAlgebra isSubset.swift in Sources */, + 7DE9203029CA70F3004483EB /* OrderedSet+SubSequence.swift in Sources */, + 7DE9215529CA70F4004483EB /* _RawHashNode+UnsafeHandle.swift in Sources */, + 7DE9209429CA70F4004483EB /* Rope+_UnmanagedLeaf.swift in Sources */, + 7DE9208429CA70F4004483EB /* BigString+Equatable.swift in Sources */, + 7DE9203729CA70F3004483EB /* OrderedSet+Partial SetAlgebra union.swift in Sources */, + 7DEBDAF929CBEE5300ADC226 /* UnsafeBufferPointer+Extras.swift in Sources */, + 7DE9215229CA70F4004483EB /* _HashNode+Builder.swift in Sources */, + 7DE9212929CA70F4004483EB /* TreeSet+SetAlgebra formUnion.swift in Sources */, + 7DE920C129CA70F4004483EB /* BitSet+SetAlgebra subtract.swift in Sources */, + 7DE9201B29CA70F3004483EB /* OrderedDictionary+Descriptions.swift in Sources */, + 7DE9213C29CA70F4004483EB /* TreeSet+Codable.swift in Sources */, + 7DE9207129CA70F4004483EB /* BigString+Split.swift in Sources */, + 7DE9214F29CA70F4004483EB /* _Bucket.swift in Sources */, + 7DE9208029CA70F4004483EB /* BigString+Hashing.swift in Sources */, + 7DE920F829CA70F4004483EB /* BitArray+Testing.swift in Sources */, + 7DE920D629CA70F4004483EB /* BitSet+Equatable.swift in Sources */, + 7DE9217A29CA70F4004483EB /* Heap+Descriptions.swift in Sources */, + 7DE9216429CA70F4004483EB /* _HashNode.swift in Sources */, + 7DE9201E29CA70F3004483EB /* OrderedSet+Partial SetAlgebra symmetricDifference.swift in Sources */, + 7DE9207A29CA70F4004483EB /* BigString+UTF8View.swift in Sources */, + 7DE9201329CA70F3004483EB /* OrderedDictionary+CustomReflectable.swift in Sources */, + 7DE9201C29CA70F3004483EB /* OrderedDictionary+Partial MutableCollection.swift in Sources */, + 7DE9202729CA70F3004483EB /* OrderedSet+Insertions.swift in Sources */, + 7DE9205B29CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift in Sources */, + 7DE9208729CA70F4004483EB /* BigString+Sequence.swift in Sources */, + 7DE9202229CA70F3004483EB /* OrderedSet+Diffing.swift in Sources */, + 7DE920CA29CA70F4004483EB /* BitSet+CustomStringConvertible.swift in Sources */, + 7DE9212E29CA70F4004483EB /* TreeSet+SetAlgebra isStrictSuperset.swift in Sources */, + 7DE920A829CA70F4004483EB /* String.Index+ABI.swift in Sources */, + 7DE9204F29CA70F3004483EB /* Deque.swift in Sources */, + 7DE9214129CA70F4004483EB /* _HashNode+Initializers.swift in Sources */, + 7DE9202D29CA70F3004483EB /* OrderedSet.swift in Sources */, + 7DEBDB0329CBEE5300ADC226 /* _UnsafeBitSet+_Word.swift in Sources */, + 7DE9216329CA70F4004483EB /* _HashLevel.swift in Sources */, + 7DE9216C29CA70F4004483EB /* TreeDictionary+Descriptions.swift in Sources */, + 7DE9205429CA70F3004483EB /* Deque+Sendable.swift in Sources */, + 7DE920A229CA70F4004483EB /* Rope+RemoveSubrange.swift in Sources */, + 7DE920E529CA70F4004483EB /* BitArray+CustomStringConvertible.swift in Sources */, + 7DE920C729CA70F4004483EB /* BitSet+ExpressibleByArrayLiteral.swift in Sources */, + 7DE9214929CA70F4004483EB /* _HashNode+Structural isEqualSet.swift in Sources */, + 7DE9206729CA70F4004483EB /* BigString+Builder.swift in Sources */, + 7DE9208B29CA70F4004483EB /* RopeMetric.swift in Sources */, + 7DE9205A29CA70F3004483EB /* Deque+Extras.swift in Sources */, + 7DEBDAF429CBEE5300ADC226 /* UnsafeMutablePointer+SE-0370.swift in Sources */, + 7DE9205129CA70F3004483EB /* Deque+Hashable.swift in Sources */, + 7DE9209929CA70F4004483EB /* Rope+Extract.swift in Sources */, + 7DE9202629CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSubset.swift in Sources */, + 7DE920E729CA70F4004483EB /* BitArray+CustomReflectable.swift in Sources */, + 7DE9207B29CA70F4004483EB /* BigSubstring+UnicodeScalarView.swift in Sources */, + 7DE9209D29CA70F4004483EB /* Rope+Insert.swift in Sources */, + 7DEBDB0229CBEE5300ADC226 /* _UnsafeBitSet.swift in Sources */, + 7DE9214329CA70F4004483EB /* _HashNode+Subtree Removals.swift in Sources */, + 7DE9207929CA70F4004483EB /* BigString+UnicodeScalarView.swift in Sources */, + 7DE9205329CA70F3004483EB /* _DequeBufferHeader.swift in Sources */, + 7DE9202429CA70F3004483EB /* OrderedSet+Invariants.swift in Sources */, + 7DE920A729CA70F4004483EB /* _CharacterRecognizer.swift in Sources */, + 7DE920A429CA70F4004483EB /* Rope+Sequence.swift in Sources */, + 7DE9201829CA70F3004483EB /* OrderedDictionary+Invariants.swift in Sources */, + 7DE920CD29CA70F4004483EB /* BitSet+CustomDebugStringConvertible.swift in Sources */, + 7DE9212529CA70F4004483EB /* TreeSet+SetAlgebra isStrictSubset.swift in Sources */, + 7DE9205C29CA70F3004483EB /* Deque+Equatable.swift in Sources */, + 7DE9209229CA70F4004483EB /* Rope+_Storage.swift in Sources */, + 7DE9203929CA70F3004483EB /* OrderedSet+Partial RangeReplaceableCollection.swift in Sources */, + 7DE9206329CA70F4004483EB /* BigString+Contents.swift in Sources */, + 7DE9215629CA70F4004483EB /* _HashNode+Structural compactMapValues.swift in Sources */, + 7DE920CC29CA70F4004483EB /* BitSet.Counted.swift in Sources */, + 7DE9207F29CA70F4004483EB /* BigSubstring+UTF8View.swift in Sources */, + 7DE920A129CA70F4004483EB /* Rope+Remove.swift in Sources */, + 7DE9215929CA70F4004483EB /* _HashNode+Structural isSubset.swift in Sources */, + 7DE920C629CA70F4004483EB /* BitSet+SetAlgebra formSymmetricDifference.swift in Sources */, + 7DE9202129CA70F3004483EB /* OrderedSet+Partial SetAlgebra isEqualSet.swift in Sources */, + 7DE9205529CA70F3004483EB /* Deque+Codable.swift in Sources */, + 7DE9206229CA70F4004483EB /* BigString+Iterators.swift in Sources */, + 7DE9206029CA70F4004483EB /* BigString+Summary.swift in Sources */, + 7DE9203829CA70F3004483EB /* OrderedSet+Partial SetAlgebra formIntersection.swift in Sources */, + 7DE9207629CA70F4004483EB /* BigString+Initializers.swift in Sources */, + 7DE9206129CA70F4004483EB /* BigString.swift in Sources */, + 7DE9215A29CA70F4004483EB /* _HashNode+Structural subtracting.swift in Sources */, + 7DE9217E29CA70F4004483EB /* Heap+ExpressibleByArrayLiteral.swift in Sources */, + 7DE9204029CA70F3004483EB /* OrderedSet+Partial SetAlgebra isStrictSuperset.swift in Sources */, + 7DE920BF29CA70F4004483EB /* BitSet+Codable.swift in Sources */, + 7DE9203329CA70F3004483EB /* OrderedSet+Testing.swift in Sources */, + 7DE9212429CA70F4004483EB /* TreeSet+Descriptions.swift in Sources */, + 7DE9217129CA70F4004483EB /* TreeDictionary+Values.swift in Sources */, + 7DE920D029CA70F4004483EB /* BitSet+SetAlgebra isSubset.swift in Sources */, + 7DE920C829CA70F4004483EB /* BitSet+SetAlgebra isEqualSet.swift in Sources */, + 7DE9215B29CA70F4004483EB /* _HashNode+Structural mapValues.swift in Sources */, + 7DE9217029CA70F4004483EB /* TreeDictionary+ExpressibleByDictionaryLiteral.swift in Sources */, + 7DE9216E29CA70F4004483EB /* TreeDictionary+Hashable.swift in Sources */, + 7DE9215E29CA70F4004483EB /* _HashNode+Lookups.swift in Sources */, + 7DE9202029CA70F3004483EB /* OrderedSet+Descriptions.swift in Sources */, + 7DE9214B29CA70F4004483EB /* _HashTreeStatistics.swift in Sources */, + 7DE920E029CA70F4004483EB /* Range+Utilities.swift in Sources */, + 7DE920D929CA70F4004483EB /* BitSet+SetAlgebra intersection.swift in Sources */, + 7DE920DD29CA70F4004483EB /* BitSet+SetAlgebra isStrictSubset.swift in Sources */, + 7DE920F229CA70F4004483EB /* BitArray._UnsafeHandle.swift in Sources */, + 7DE9204229CA70F3004483EB /* _HashTable+UnsafeHandle.swift in Sources */, + 7DE9208E29CA70F4004483EB /* _RopeVersion.swift in Sources */, + 7DE9212629CA70F4004483EB /* TreeSet+Sendable.swift in Sources */, + 7DE9209C29CA70F4004483EB /* Rope+Find.swift in Sources */, + 7DE920E829CA70F4004483EB /* BitArray+BitwiseOperations.swift in Sources */, + 7DE9207829CA70F4004483EB /* BigString+Append.swift in Sources */, + 7DE9217F29CA70F4004483EB /* _HeapNode.swift in Sources */, + 7DE9202929CA70F3004483EB /* OrderedSet+Codable.swift in Sources */, + 7DE9204829CA70F3004483EB /* _HashTable+CustomStringConvertible.swift in Sources */, + 7DE9213029CA70F4004483EB /* TreeSet+SetAlgebra isSuperset.swift in Sources */, + 7DE9217529CA70F4004483EB /* TreeDictionary+MapValues.swift in Sources */, + 7DE9206C29CA70F4004483EB /* BigString+Chunk.swift in Sources */, + 7DE920F329CA70F4004483EB /* BitArray+Copy.swift in Sources */, + 7DE9214029CA70F4004483EB /* _Hash.swift in Sources */, + 7DE920F729CA70F4004483EB /* BitArray+Random.swift in Sources */, + 7DE9205629CA70F3004483EB /* Deque+Testing.swift in Sources */, + 7DEBDB0829CBEE5300ADC226 /* UInt+reversed.swift in Sources */, + 7DE9209329CA70F4004483EB /* Rope+Invariants.swift in Sources */, + 7DE920EE29CA70F4004483EB /* BitArray+ExpressibleByArrayLiteral.swift in Sources */, + 7DEBDB0A29CBEE5300ADC226 /* UInt+first and last set bit.swift in Sources */, + 7DE9214C29CA70F4004483EB /* _HashNode+Primitive Insertions.swift in Sources */, + 7DE920BE29CA70F4004483EB /* BitSet+SetAlgebra formIntersection.swift in Sources */, + 7DE9217329CA70F4004483EB /* TreeDictionary+Merge.swift in Sources */, + 7DE9204E29CA70F3004483EB /* Deque+CustomReflectable.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7DE91B2A29CA6721004483EB /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7DEBDB7F29CCE44A00ADC226 /* CheckBidirectionalCollection.swift in Sources */, + 7DE9221829CA8576004483EB /* HashTableTests.swift in Sources */, + 7DE9220C29CA8576004483EB /* Availability.swift in Sources */, + 7DE9220029CA8576004483EB /* TreeDictionary Smoke Tests.swift in Sources */, + 7DEBDB9029CCE44A00ADC226 /* TestContext.swift in Sources */, + 7DE9221429CA8576004483EB /* OrderedSet Diffing Tests.swift in Sources */, + 7DEBDB1D29CBF6B200ADC226 /* RandomAccessCollection+Offsets.swift in Sources */, + 7DEBDB8529CCE44A00ADC226 /* AllOnesRandomNumberGenerator.swift in Sources */, + 7DEBDB1429CBF68D00ADC226 /* UnsafeMutableBufferPointer+SE-0370.swift in Sources */, + 7DE921FD29CA8576004483EB /* CombinatoricsChecks.swift in Sources */, + 7DEBDB8B29CCE44A00ADC226 /* _CollectionState.swift in Sources */, + 7DE9220229CA8576004483EB /* TreeDictionary Tests.swift in Sources */, + 7DEBDB8429CCE44A00ADC226 /* CheckSequence.swift in Sources */, + 7DEBDB8029CCE44A00ADC226 /* MinimalRandomAccessCollection.swift in Sources */, + 7DEBDB0F29CBF68900ADC226 /* UInt+reversed.swift in Sources */, + 7DEBDB1E29CBF6B200ADC226 /* UnsafeMutableBufferPointer+Extras.swift in Sources */, + 7DE9221C29CA8576004483EB /* RangeReplaceableCollectionTests.swift in Sources */, + 7DE9220429CA8576004483EB /* TreeHashedCollections Fixtures.swift in Sources */, + 7DEBDB7A29CCE44A00ADC226 /* SetAPIChecker.swift in Sources */, + 7DE9221B29CA8576004483EB /* DequeInternals.swift in Sources */, + 7DEBDB6E29CCE44A00ADC226 /* SortedCollectionAPIChecker.swift in Sources */, + 7DE9220929CA8576004483EB /* BitArrayTests.swift in Sources */, + 7DEBDB1C29CBF6B200ADC226 /* Debugging.swift in Sources */, + 7DE9221629CA8576004483EB /* OrderedSet.UnorderedView Tests.swift in Sources */, + 7DEBDB7529CCE44A00ADC226 /* MinimalCollection.swift in Sources */, + 7DEBDB1029CBF68900ADC226 /* UInt+first and last set bit.swift in Sources */, + 7DEBDB8C29CCE44A00ADC226 /* MinimalIterator.swift in Sources */, + 7DEBDB8829CCE44A00ADC226 /* MinimalSequence.swift in Sources */, + 7DEBDB1129CBF68900ADC226 /* FixedWidthInteger+roundUpToPowerOfTwo.swift in Sources */, + 7DE921FE29CA8576004483EB /* Hash.swift in Sources */, + 7DEBDB8929CCE44A00ADC226 /* Combinatorics.swift in Sources */, + 7DE9221A29CA8576004483EB /* HeapNodeTests.swift in Sources */, + 7DEBDB7029CCE44A00ADC226 /* ResettableValue.swift in Sources */, + 7DE9221129CA8576004483EB /* OrderedDictionary+Values Tests.swift in Sources */, + 7DEBDB7D29CCE44A00ADC226 /* MinimalRangeReplaceableRandomAccessCollection.swift in Sources */, + 7DEBDB8E29CCE44A00ADC226 /* Integer Square Root.swift in Sources */, + 7DE9221E29CA8576004483EB /* MutableCollectionTests.swift in Sources */, + 7DEBDB1229CBF68D00ADC226 /* UnsafeMutablePointer+SE-0370.swift in Sources */, + 7DE9221529CA8576004483EB /* RandomAccessCollection+Extras.swift in Sources */, + 7DEBDB7929CCE44A00ADC226 /* LifetimeTracked.swift in Sources */, + 7DE921FC29CA8576004483EB /* IndexRangeCollectionTests.swift in Sources */, + 7DE9221229CA8576004483EB /* OrderedDictionary+Elements Tests.swift in Sources */, + 7DEBDB7629CCE44A00ADC226 /* MinimalIndex.swift in Sources */, + 7DE9221329CA8576004483EB /* OrderedSetInternals.swift in Sources */, + 7DE9220329CA8576004483EB /* Colliders.swift in Sources */, + 7DE9221729CA8576004483EB /* OrderedSetTests.swift in Sources */, + 7DE9221D29CA8576004483EB /* DequeTests.swift in Sources */, + 7DEBDB1A29CBF6B200ADC226 /* Descriptions.swift in Sources */, + 7DE921FA29CA8576004483EB /* UtilitiesTests.swift in Sources */, + 7DE9220A29CA8576004483EB /* TestRope.swift in Sources */, + 7DE9220529CA8576004483EB /* TreeDictionary.Values Tests.swift in Sources */, + 7DEBDB8D29CCE44A00ADC226 /* RandomStableSample.swift in Sources */, + 7DEBDB7429CCE44A00ADC226 /* DictionaryAPIChecker.swift in Sources */, + 7DEBDB8A29CCE44A00ADC226 /* Box.swift in Sources */, + 7DEBDB8629CCE44A00ADC226 /* LifetimeTracker.swift in Sources */, + 7DEBDB8229CCE44A00ADC226 /* RepeatableRandomNumberGenerator.swift in Sources */, + 7DEBDB7129CCE44A00ADC226 /* MinimalEncoder.swift in Sources */, + 7DE921FB29CA8576004483EB /* MinimalTypeConformances.swift in Sources */, + 7DEBDB8129CCE44A00ADC226 /* CheckCollection.swift in Sources */, + 7DEBDB7229CCE44A00ADC226 /* MinimalBidirectionalCollection.swift in Sources */, + 7DEBDB1B29CBF6B200ADC226 /* UnsafeBufferPointer+Extras.swift in Sources */, + 7DEBDB8729CCE44A00ADC226 /* MinimalMutableRandomAccessCollection.swift in Sources */, + 7DEBDB7829CCE44A00ADC226 /* Assertions.swift in Sources */, + 7DE9220D29CA8576004483EB /* TestBigString.swift in Sources */, + 7DEBDB8329CCE44A00ADC226 /* CheckHashable.swift in Sources */, + 7DE921FF29CA8576004483EB /* Utilities.swift in Sources */, + 7DEBDB8F29CCE44A00ADC226 /* CheckEquatable.swift in Sources */, + 7DEBDB7729CCE44A00ADC226 /* HashableBox.swift in Sources */, + 7DE9220E29CA8576004483EB /* SampleStrings.swift in Sources */, + 7DEBDB9129CCE44A00ADC226 /* CollectionTestCase.swift in Sources */, + 7DEBDB1829CBF69F00ADC226 /* _UnsafeBitSet+_Word.swift in Sources */, + 7DE921B929CA81DC004483EB /* _SortedCollection.swift in Sources */, + 7DEBDB1629CBF69F00ADC226 /* _UnsafeBitSet+Index.swift in Sources */, + 7DEBDB1529CBF68D00ADC226 /* UnsafeRawPointer extensions.swift in Sources */, + 7DEBDB7B29CCE44A00ADC226 /* IndexRangeCollection.swift in Sources */, + 7DE9221929CA8576004483EB /* HeapTests.swift in Sources */, + 7DEBDB1729CBF69F00ADC226 /* _UnsafeBitSet.swift in Sources */, + 7DEBDB7E29CCE44A00ADC226 /* CheckComparable.swift in Sources */, + 7DEBDB7C29CCE44A00ADC226 /* MinimalDecoder.swift in Sources */, + 7DE9220829CA8576004483EB /* BitSetTests.swift in Sources */, + 7DEBDB7329CCE44A00ADC226 /* _MinimalCollectionCore.swift in Sources */, + 7DEBDB1329CBF68D00ADC226 /* Array+WithContiguousStorage Compatibility.swift in Sources */, + 7DE921C829CA81DC004483EB /* _UniqueCollection.swift in Sources */, + 7DE9220629CA8576004483EB /* TreeSet Tests.swift in Sources */, + 7DEBDB9229CCE44A00ADC226 /* StringConvertibleValue.swift in Sources */, + 7DEBDB6F29CCE44A00ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift in Sources */, + 7DE9220129CA8576004483EB /* TreeDictionary.Keys Tests.swift in Sources */, + 7DEBDB0E29CBF68900ADC226 /* Integer rank.swift in Sources */, + 7DE9220729CA8576004483EB /* BitSet.Counted Tests.swift in Sources */, + 7DE9220F29CA8576004483EB /* OrderedDictionary Tests.swift in Sources */, + 7DE9221029CA8576004483EB /* OrderedDictionary Utils.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 7DE91B3129CA6721004483EB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 7DE91B2529CA6721004483EB /* Collections */; + targetProxy = 7DE91B3029CA6721004483EB /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 7DE91B3629CA6721004483EB /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7DEBDB9829CCE4A600ADC226 /* Shared.xcconfig */; + buildSettings = { + CURRENT_PROJECT_VERSION = 1; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 7DE91B3729CA6721004483EB /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7DEBDB9829CCE4A600ADC226 /* Shared.xcconfig */; + buildSettings = { + CURRENT_PROJECT_VERSION = 1; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 7DE91B3929CA6721004483EB /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++"; + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++20"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SKIP_INSTALL = YES; + }; + name = Debug; + }; + 7DE91B3A29CA6721004483EB /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++"; + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++20"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SKIP_INSTALL = YES; + }; + name = Release; + }; + 7DE91B3C29CA6721004483EB /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7DEBDB9729CCE4A600ADC226 /* CollectionsTests.xcconfig */; + buildSettings = { + CURRENT_PROJECT_VERSION = 1; + MARKETING_VERSION = 1.0; + }; + name = Debug; + }; + 7DE91B3D29CA6721004483EB /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7DEBDB9729CCE4A600ADC226 /* CollectionsTests.xcconfig */; + buildSettings = { + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + MARKETING_VERSION = 1.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 7DE91B2029CA6721004483EB /* Build configuration list for PBXProject "Collections" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7DE91B3629CA6721004483EB /* Debug */, + 7DE91B3729CA6721004483EB /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7DE91B3829CA6721004483EB /* Build configuration list for PBXNativeTarget "Collections" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7DE91B3929CA6721004483EB /* Debug */, + 7DE91B3A29CA6721004483EB /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7DE91B3B29CA6721004483EB /* Build configuration list for PBXNativeTarget "CollectionsTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7DE91B3C29CA6721004483EB /* Debug */, + 7DE91B3D29CA6721004483EB /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 7DE91B1D29CA6721004483EB /* Project object */; +} diff --git a/Xcode/Collections.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Xcode/Collections.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/Xcode/Collections.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Xcode/Collections.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Xcode/Collections.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/Xcode/Collections.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Xcode/CollectionsTests.xcconfig b/Xcode/CollectionsTests.xcconfig new file mode 100644 index 00000000..1317925c --- /dev/null +++ b/Xcode/CollectionsTests.xcconfig @@ -0,0 +1,22 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +PRODUCT_NAME = CollectionsTests +PRODUCT_BUNDLE_IDENTIFIER = org.swift.CollectionsTests + +SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator watchos watchsimulator appletvos appletvsimulator +ARCHS = $(ARCHS_STANDARD) + +GENERATE_INFOPLIST_FILE = YES +CODE_SIGN_STYLE = Automatic + +ENABLE_TESTABILITY = NO + diff --git a/Xcode/Shared.xcconfig b/Xcode/Shared.xcconfig new file mode 100644 index 00000000..e54ee440 --- /dev/null +++ b/Xcode/Shared.xcconfig @@ -0,0 +1,79 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +SDKROOT = macosx + +SWIFT_VERSION = 5.5 +ONLY_ACTIVE_ARCH[config=Debug] = YES + +SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) COLLECTIONS_SINGLE_MODULE +SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Debug] = $(inherited) COLLECTIONS_INTERNAL_CHECKS + +SWIFT_COMPILATION_MODE[config=Release] = wholemodule +SWIFT_COMPILATION_MODE[config=Debug] = singlefile + +SWIFT_OPTIMIZATION_LEVEL[config=Release] = -O +SWIFT_OPTIMIZATION_LEVEL[config=Debug] = -Onone + +SWIFT_EMIT_LOC_STRINGS = NO +SWIFT_INSTALL_OBJC_HEADER = NO + +COPY_PHASE_STRIP = NO + +DEBUG_INFORMATION_FORMAT[config=Release] = dwarf-with-dsym +DEBUG_INFORMATION_FORMAT[config=Debug] = dwarf + +ALWAYS_SEARCH_USER_PATHS = NO + +GCC_DYNAMIC_NO_PIC = NO +GCC_NO_COMMON_BLOCKS = YES +GCC_OPTIMIZATION_LEVEL[config=Debug] = 0 + +GCC_C_LANGUAGE_STANDARD = gnu11 +CLANG_CXX_LANGUAGE_STANDARD = gnu++20 +CLANG_ENABLE_MODULES = YES +CLANG_ENABLE_OBJC_ARC = YES +CLANG_ENABLE_OBJC_WEAK = YES +ENABLE_NS_ASSERTIONS[config=Release] = NO +ENABLE_STRICT_OBJC_MSGSEND = YES +GCC_PREPROCESSOR_DEFINITIONS[config=Release] = DEBUG=1 $(inherited) + +CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES +CLANG_WARN_BOOL_CONVERSION = YES +CLANG_WARN_COMMA = YES +CLANG_WARN_CONSTANT_CONVERSION = YES +CLANG_WARN_DOCUMENTATION_COMMENTS = YES +CLANG_WARN_EMPTY_BODY = YES +CLANG_WARN_ENUM_CONVERSION = YES +CLANG_WARN_INFINITE_RECURSION = YES +CLANG_WARN_INT_CONVERSION = YES +CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN_UNREACHABLE_CODE = YES + +GCC_WARN_64_TO_32_BIT_CONVERSION = YES +GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR +GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE +GCC_WARN_UNUSED_FUNCTION = YES +GCC_WARN_UNUSED_VARIABLE = YES +CLANG_WARN_RANGE_LOOP_ANALYSIS = YES +CLANG_WARN_SUSPICIOUS_MOVE = YES +CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES +CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR +CLANG_WARN_OBJC_LITERAL_CONVERSION = YES +CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +CLANG_ANALYZER_NONNULL = YES +CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE From 1666222de2200b2a614a0d5184751b8b6f7309b0 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 23 Mar 2023 13:43:01 -0700 Subject: [PATCH 092/113] Add READMEs calling out the fact that the contents of Tests/, Utils/ & Xcode/ are unstable --- Tests/README.md | 3 +++ Utils/README.md | 17 +++++++++++++++++ Xcode/README.md | 5 +++++ 3 files changed, 25 insertions(+) create mode 100644 Tests/README.md create mode 100644 Utils/README.md create mode 100644 Xcode/README.md diff --git a/Tests/README.md b/Tests/README.md new file mode 100644 index 00000000..701eda8a --- /dev/null +++ b/Tests/README.md @@ -0,0 +1,3 @@ +# Unit tests + +Beware! The contents of this directory are not source stable. They are provided as is, with no compatibility promises across package releases. Future versions of this package can arbitrarily change these files or remove them, without any advance notice. (This can include patch releases.) diff --git a/Utils/README.md b/Utils/README.md new file mode 100644 index 00000000..58bce3bd --- /dev/null +++ b/Utils/README.md @@ -0,0 +1,17 @@ +# Maintenance Scripts + +This directory contains scripts that are used to maintain this package. + +Beware! The contents of this directory are not source stable. They are provided as is, with no compatibility promises across package releases. Future versions of this package can arbitrarily change these files or remove them, without any advance notice. (This can include patch releases.) + +- `generate-docs.sh`: A shell scripts that automates the generation of API documentation. + +- `generate-sources.sh`: A shell script that invokes `gyb` to regenerate the contents of autogenerated/ directories. This needs to be run whenever a file with a `.swift.gyb` extension is updated. + +- `gyb`, `gyb.py`: Generate Your Boilerplate. A rudimentary source code generation utility. + +- `gyb_utils.py`: A Python module containing code generation utility definitions that are shared across multiple `.swift.gyb` files in this repository. + +- `run-full-tests.sh`: A shell script that exercises many common configurations of this package in a semi-automated way. This is used before tagging a release to avoid accidentally shipping a package version that breaks some setups. + +- `shuffle-sources.sh`: A legacy utility that randomly reorders Swift source files in a given directory. This is used to avoid reoccurrances of issue #7. (This is hopefully only relevant with compilers that the package no longer supports.) diff --git a/Xcode/README.md b/Xcode/README.md new file mode 100644 index 00000000..0b8ae382 --- /dev/null +++ b/Xcode/README.md @@ -0,0 +1,5 @@ +# Xcode build files + +The project file here is used to build a variant of this package with Xcode. The project file is a regular Xcode project that builds the code base using the COLLECTIONS_SINGLE_MODULE configuration, producing a single framework bundle. Builds settings are entirely configured via the provided xcconfig files. + +Beware! The contents of this directory are not source stable. They are provided as is, with no compatibility promises across package releases. Future versions of this package can arbitrarily change these files or remove them, without any advance notice. (This can include patch releases.) From a0666cdcce8a3ee3054b38570765fb691411b199 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 23 Mar 2023 14:23:45 -0700 Subject: [PATCH 093/113] Resolve some leftover build issues --- Package.swift | 4 +++- .../OrderedSet/RandomAccessCollection+Extras.swift | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 49fb019e..db1c676f 100644 --- a/Package.swift +++ b/Package.swift @@ -163,7 +163,9 @@ extension Array where Element == CustomTarget { name: name, dependencies: dependencies, path: "Tests", - exclude: targets.flatMap { t in + exclude: [ + "README.md", + ] + targets.flatMap { t in t.exclude.map { "\(t.name)/\($0)" } }, sources: targets.map { "\($0.name)" }, diff --git a/Tests/OrderedCollectionsTests/OrderedSet/RandomAccessCollection+Extras.swift b/Tests/OrderedCollectionsTests/OrderedSet/RandomAccessCollection+Extras.swift index fd6bcb2b..8c6243d2 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/RandomAccessCollection+Extras.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/RandomAccessCollection+Extras.swift @@ -14,6 +14,7 @@ import _CollectionsUtilities #endif extension RandomAccessCollection { + #if SWIFT_PACKAGE @inline(__always) internal func _index(at offset: Int) -> Index { index(startIndex, offsetBy: offset) @@ -28,6 +29,7 @@ extension RandomAccessCollection { internal subscript(_offset offset: Int) -> Element { self[_index(at: offset)] } + #endif @inline(__always) internal func _indexRange(at offsets: Range) -> Range { From c81f73f05a07e3aabfbb8d8d4802deb7ebf2cae8 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 23 Mar 2023 16:27:05 -0700 Subject: [PATCH 094/113] Move build settings from Xcode project into xcconfig files --- Xcode/Collections.xcconfig | 26 +++++++++- Xcode/Collections.xcodeproj/project.pbxproj | 55 +-------------------- Xcode/CollectionsTests.xcconfig | 8 +++ Xcode/Shared.xcconfig | 2 +- 4 files changed, 35 insertions(+), 56 deletions(-) diff --git a/Xcode/Collections.xcconfig b/Xcode/Collections.xcconfig index 9a892a6b..ff0af9bc 100644 --- a/Xcode/Collections.xcconfig +++ b/Xcode/Collections.xcconfig @@ -15,8 +15,32 @@ PRODUCT_BUNDLE_IDENTIFIER = org.swift.Collections SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator watchos watchsimulator appletvos appletvsimulator ARCHS = $(ARCHS_STANDARD) -DEFINES_MODULE = YES +MACOSX_DEPLOYMENT_TARGET = 12.0 +IPHONEOS_DEPLOYMENT_TARGET = 15.0 +WATCHOS_DEPLOYMENT_TARGET = 8.0 +TVOS_DEPLOYMENT_TARGET = 15.0 + +MARKETING_VERSION = 1.1 + +CURRENT_PROJECT_VERSION = 1 +VERSIONING_SYSTEM = apple-generic +VERSION_INFO_PREFIX = + +DYLIB_COMPATIBILITY_VERSION = $(CURRENT_PROJECT_VERSION) +DYLIB_CURRENT_VERSION = $(CURRENT_PROJECT_VERSION) + +INSTALL_PATH = $(LOCAL_LIBRARY_DIR)/Frameworks +SKIP_INSTALL = YES +DYLIB_INSTALL_NAME_BASE = @rpath +LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/../Frameworks @loader_path/Frameworks ENABLE_TESTABILITY = NO +ENABLE_TESTABILITY[config=Debug] = YES +GENERATE_INFOPLIST_FILE = YES +CODE_SIGN_STYLE = Automatic +DEFINES_MODULE = YES +ENABLE_MODULE_VERIFIER = YES +MODULE_VERIFIER_SUPPORTED_LANGUAGES = objective-c objective-c++ +MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = gnu11 gnu++20 diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index ec50093b..ecde4df9 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -1797,9 +1797,9 @@ 7DEBDB9329CCE4A600ADC226 /* Xcode */ = { isa = PBXGroup; children = ( - 7DEBDB9729CCE4A600ADC226 /* CollectionsTests.xcconfig */, 7DEBDB9829CCE4A600ADC226 /* Shared.xcconfig */, 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */, + 7DEBDB9729CCE4A600ADC226 /* CollectionsTests.xcconfig */, 7D5A64D229CCE8CC00CB2595 /* README.md */, ); name = Xcode; @@ -2350,9 +2350,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9829CCE4A600ADC226 /* Shared.xcconfig */; buildSettings = { - CURRENT_PROJECT_VERSION = 1; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; }; name = Debug; }; @@ -2360,9 +2357,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9829CCE4A600ADC226 /* Shared.xcconfig */; buildSettings = { - CURRENT_PROJECT_VERSION = 1; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; }; name = Release; }; @@ -2370,27 +2364,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */; buildSettings = { - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_MODULE_VERIFIER = YES; - GENERATE_INFOPLIST_FILE = YES; - INFOPLIST_KEY_NSHumanReadableCopyright = ""; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - "@loader_path/Frameworks", - ); - MARKETING_VERSION = 1.0; - MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++"; - MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++20"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SKIP_INSTALL = YES; }; name = Debug; }; @@ -2398,27 +2371,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */; buildSettings = { - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_MODULE_VERIFIER = YES; - GENERATE_INFOPLIST_FILE = YES; - INFOPLIST_KEY_NSHumanReadableCopyright = ""; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - "@loader_path/Frameworks", - ); - MARKETING_VERSION = 1.0; - MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++"; - MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++20"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SKIP_INSTALL = YES; }; name = Release; }; @@ -2426,8 +2378,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9729CCE4A600ADC226 /* CollectionsTests.xcconfig */; buildSettings = { - CURRENT_PROJECT_VERSION = 1; - MARKETING_VERSION = 1.0; }; name = Debug; }; @@ -2435,9 +2385,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7DEBDB9729CCE4A600ADC226 /* CollectionsTests.xcconfig */; buildSettings = { - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - MARKETING_VERSION = 1.0; }; name = Release; }; diff --git a/Xcode/CollectionsTests.xcconfig b/Xcode/CollectionsTests.xcconfig index 1317925c..c0fa92aa 100644 --- a/Xcode/CollectionsTests.xcconfig +++ b/Xcode/CollectionsTests.xcconfig @@ -15,6 +15,14 @@ PRODUCT_BUNDLE_IDENTIFIER = org.swift.CollectionsTests SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator watchos watchsimulator appletvos appletvsimulator ARCHS = $(ARCHS_STANDARD) +MACOSX_DEPLOYMENT_TARGET = 12.0 +IPHONEOS_DEPLOYMENT_TARGET = 15.0 +WATCHOS_DEPLOYMENT_TARGET = 8.0 +TVOS_DEPLOYMENT_TARGET = 15.0 + +CURRENT_PROJECT_VERSION = 1 +MARKETING_VERSION = 1.0 + GENERATE_INFOPLIST_FILE = YES CODE_SIGN_STYLE = Automatic diff --git a/Xcode/Shared.xcconfig b/Xcode/Shared.xcconfig index e54ee440..f3b041e0 100644 --- a/Xcode/Shared.xcconfig +++ b/Xcode/Shared.xcconfig @@ -15,7 +15,7 @@ SWIFT_VERSION = 5.5 ONLY_ACTIVE_ARCH[config=Debug] = YES SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) COLLECTIONS_SINGLE_MODULE -SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Debug] = $(inherited) COLLECTIONS_INTERNAL_CHECKS +SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Debug] = $(inherited) COLLECTIONS_INTERNAL_CHECKS DEBUG SWIFT_COMPILATION_MODE[config=Release] = wholemodule SWIFT_COMPILATION_MODE[config=Debug] = singlefile From 26de4aa094c87a9efd793f3ec37ec7facea24184 Mon Sep 17 00:00:00 2001 From: Felix Herrmann Date: Wed, 29 Mar 2023 19:05:43 +0200 Subject: [PATCH 095/113] Fix deprecated UnsafeMutablePointer.assign(repeating:count) method --- .../HashTable/_HashTable+UnsafeHandle.swift | 4 ++++ Sources/OrderedCollections/Utilities/_UnsafeBitset.swift | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift b/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift index ba8efcb4..d2cb1957 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift @@ -484,7 +484,11 @@ extension _UnsafeHashTable { @usableFromInline internal func clear() { assertMutable() + #if swift(>=5.8) + _buckets.update(repeating: 0, count: wordCount) + #else _buckets.assign(repeating: 0, count: wordCount) + #endif } } diff --git a/Sources/OrderedCollections/Utilities/_UnsafeBitset.swift b/Sources/OrderedCollections/Utilities/_UnsafeBitset.swift index aa10c684..571436dd 100644 --- a/Sources/OrderedCollections/Utilities/_UnsafeBitset.swift +++ b/Sources/OrderedCollections/Utilities/_UnsafeBitset.swift @@ -184,7 +184,11 @@ extension _UnsafeBitset { @_effects(releasenone) internal mutating func clear() { guard _words.count > 0 else { return } + #if swift(>=5.8) + _words.baseAddress!.update(repeating: .empty, count: _words.count) + #else _words.baseAddress!.assign(repeating: .empty, count: _words.count) + #endif _count = 0 } From 73936bba69bd49e025aa8113fa81caa7f76ed571 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 7 Apr 2023 19:21:44 -0700 Subject: [PATCH 096/113] Expose a handful of BigString.Index methods These help implementing conversions between String.Index and BigString.Index. --- .../RopeModule/BigString/Basics/BigString+Index.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Sources/RopeModule/BigString/Basics/BigString+Index.swift b/Sources/RopeModule/BigString/Basics/BigString+Index.swift index d8291b9d..b1602bef 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Index.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Index.swift @@ -119,7 +119,7 @@ extension BigString.Index { _flags = 0 } - internal var _isUTF16TrailingSurrogate: Bool { + public var _isUTF16TrailingSurrogate: Bool { _orderingValue & 1 != 0 } @@ -135,20 +135,20 @@ extension BigString.Index { return copy } - internal var _isKnownScalarAligned: Bool { + public var _isKnownScalarAligned: Bool { _rawBits & Self._scalarAlignmentBit != 0 } - internal var _isKnownCharacterAligned: Bool { + public var _isKnownCharacterAligned: Bool { _rawBits & Self._characterAlignmentBit != 0 } - internal init(_utf8Offset: Int) { + public init(_utf8Offset: Int) { _rawBits = Self._bitsForUTF8Offset(_utf8Offset) _rope = nil } - internal init(_utf8Offset: Int, utf16TrailingSurrogate: Bool) { + public init(_utf8Offset: Int, utf16TrailingSurrogate: Bool) { _rawBits = Self._bitsForUTF8Offset(_utf8Offset) if utf16TrailingSurrogate { _rawBits |= Self._utf16TrailingSurrogateBits From 9c3328e235e5f17c06328f021a5d11e7221690f5 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 10 Apr 2023 16:45:28 -0700 Subject: [PATCH 097/113] Rope: Fix Sendable conformance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Rope._Node` wasn’t declared `Sendable`, which triggered valid warnings. --- Sources/RopeModule/Rope/Basics/Rope+_Node.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift index c2748e25..3b099e40 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift @@ -46,6 +46,10 @@ extension Rope { } } +extension Rope._Node: @unchecked Sendable where Element: Sendable { + // @unchecked because `object` is stored as an `AnyObject` above. +} + extension Rope._Node { var _headerPtr: UnsafePointer<_RopeStorageHeader> { let p = _getUnsafePointerToStoredProperties(object) From 96d71628887275fc3010a0979cdebef15edde911 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 10 Apr 2023 16:49:29 -0700 Subject: [PATCH 098/113] BigString: Fix String.Index._knownScalarAligned MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This member isn’t currently used, but unlike its counterpart in the stdlib, this one accidentally sets the character-alignment bit. --- Sources/RopeModule/Utilities/String.Index+ABI.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/RopeModule/Utilities/String.Index+ABI.swift b/Sources/RopeModule/Utilities/String.Index+ABI.swift index 193db89d..5c241da8 100644 --- a/Sources/RopeModule/Utilities/String.Index+ABI.swift +++ b/Sources/RopeModule/Utilities/String.Index+ABI.swift @@ -64,7 +64,7 @@ extension String.Index { } var _knownScalarAligned: String.Index { - let r = _abi_rawBits | Self._abi_characterAlignmentBit | Self._abi_scalarAlignmentBit + let r = _abi_rawBits | Self._abi_scalarAlignmentBit return unsafeBitCast(r, to: String.Index.self) } } From 454c84b5e4253e462dac5472b853ee222ca93368 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 10 Apr 2023 16:41:17 -0700 Subject: [PATCH 099/113] Make most of Rope inlinable --- .../HashNode/_HashNode+Builder.swift | 2 +- .../RopeModule/Rope/Basics/Rope+Builder.swift | 37 ++- .../Rope/Basics/Rope+Debugging.swift | 11 +- .../Rope/Basics/Rope+Invariants.swift | 11 +- .../RopeModule/Rope/Basics/Rope+_Node.swift | 279 +++++++++++------- .../Rope/Basics/Rope+_Storage.swift | 32 +- .../Rope/Basics/Rope+_UnmanagedLeaf.swift | 18 +- .../Rope/Basics/Rope+_UnsafeHandle.swift | 110 ++++--- Sources/RopeModule/Rope/Basics/Rope.swift | 26 +- .../RopeModule/Rope/Basics/RopeMetric.swift | 2 +- .../RopeModule/Rope/Basics/_RopeItem.swift | 42 ++- .../RopeModule/Rope/Basics/_RopePath.swift | 40 ++- .../RopeModule/Rope/Basics/_RopeVersion.swift | 19 +- .../Rope/Conformances/Rope+Collection.swift | 70 ++++- .../Rope/Conformances/Rope+Index.swift | 39 ++- .../Rope/Conformances/Rope+Sequence.swift | 34 ++- .../Rope/Operations/Rope+Append.swift | 4 +- .../Rope/Operations/Rope+Extract.swift | 4 +- .../Rope/Operations/Rope+Find.swift | 7 +- .../Rope/Operations/Rope+ForEachWhile.swift | 8 +- .../Rope/Operations/Rope+Insert.swift | 43 ++- .../Rope/Operations/Rope+Join.swift | 21 +- .../Operations/Rope+MutatingForEach.swift | 12 +- .../Rope/Operations/Rope+Remove.swift | 11 +- .../Rope/Operations/Rope+RemoveSubrange.swift | 24 +- .../Rope/Operations/Rope+Split.swift | 11 +- .../Utilities/Optional Utilities.swift | 1 + ...peModule.xcscheme => _RopeModule.xcscheme} | 19 +- 28 files changed, 625 insertions(+), 312 deletions(-) rename Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/{RopeModule.xcscheme => _RopeModule.xcscheme} (87%) diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift index d8f8131a..13a0a334 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift @@ -13,7 +13,7 @@ extension _HashNode { @usableFromInline @frozen internal struct Builder { - @usableFromInline typealias Element = _HashNode.Element + @usableFromInline internal typealias Element = _HashNode.Element @usableFromInline @frozen diff --git a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift index 244adb35..e5abec10 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift @@ -25,6 +25,7 @@ extension Rope { } extension Rope { + @frozen // Not really! This module isn't ABI stable. public struct Builder { // ║ ║ // ║ ║ ║ ║ @@ -34,26 +35,31 @@ extension Rope { // →prefixTrees→ ↑ ↑ ←suffixTrees← // prefix suffix - private var _prefixTrees: [Rope] = [] - private var _prefixLeaf: Rope._Node? - var _prefix: Rope._Item? - - var _suffix: Rope._Item? - var _suffixTrees: [Rope] = [] + @usableFromInline internal var _prefixTrees: [Rope] = [] + @usableFromInline internal var _prefixLeaf: Rope._Node? + @usableFromInline internal var _prefix: Rope._Item? + + @usableFromInline internal var _suffix: Rope._Item? + @usableFromInline internal var _suffixTrees: [Rope] = [] + + @inlinable public init() {} + @inlinable public var isPrefixEmpty: Bool { if _prefix != nil { return false } if let leaf = self._prefixLeaf, !leaf.isEmpty { return false } return _prefixTrees.isEmpty } + @inlinable public var isSuffixEmpty: Bool { if _suffix != nil { return false } return _suffixTrees.isEmpty } + @inlinable public var prefixSummary: Summary { var sum = Summary.zero for sapling in _prefixTrees { @@ -64,6 +70,7 @@ extension Rope { return sum } + @inlinable public var suffixSummary: Summary { var sum = Summary.zero if let item = _suffix { sum.add(item.summary) } @@ -73,6 +80,7 @@ extension Rope { return sum } + @inlinable var _lastPrefixItem: Rope._Item { get { assert(!isPrefixEmpty) @@ -92,6 +100,7 @@ extension Rope { } } + @inlinable var _firstSuffixItem: Rope._Item { get { assert(!isSuffixEmpty) @@ -108,6 +117,7 @@ extension Rope { } } + @inlinable public func forEachElementInPrefix( from position: Int, in metric: some RopeMetric, @@ -155,6 +165,7 @@ extension Rope { return true } + @inlinable public mutating func mutatingForEachSuffix( _ body: (inout Element) -> R? ) -> R? { @@ -170,10 +181,12 @@ extension Rope { return nil } + @inlinable public mutating func insertBeforeTip(_ item: __owned Element) { _insertBeforeTip(Rope._Item(item)) } + @inlinable mutating func _insertBeforeTip(_ item: __owned Rope._Item) { guard !item.isEmpty else { return } guard var prefix = self._prefix._take() else { @@ -189,6 +202,7 @@ extension Rope { self._prefix = item } + @inlinable mutating func _appendNow(_ item: __owned Rope._Item) { assert(self._prefix == nil) assert(!item.isUndersized) @@ -202,11 +216,13 @@ extension Rope { _invariantCheck() } + @inlinable public mutating func insertBeforeTip(_ rope: __owned Rope) { guard rope._root != nil else { return } _insertBeforeTip(rope.root) } + @inlinable mutating func _insertBeforeTip(_ node: __owned Rope._Node) { defer { _invariantCheck() } var node = node @@ -249,6 +265,7 @@ extension Rope { _appendNow(node) } + @inlinable mutating func _appendNow(_ rope: __owned Rope._Node) { assert(self._prefix == nil && self._prefixLeaf == nil) var new = rope @@ -287,10 +304,12 @@ extension Rope { _prefixTrees.append(Rope(root: new)) } + @inlinable public mutating func insertAfterTip(_ item: __owned Element) { _insertAfterTip(_Item(item)) } + @inlinable mutating func _insertAfterTip(_ item: __owned _Item) { guard !item.isEmpty else { return } if var suffixItem = self._suffix._take() { @@ -306,16 +325,19 @@ extension Rope { self._suffix = item } + @inlinable public mutating func insertAfterTip(_ rope: __owned Rope) { assert(_suffix == nil) assert(_suffixTrees.isEmpty || rope._height <= _suffixTrees.last!._height) _suffixTrees.append(rope) } + @inlinable mutating func _insertAfterTip(_ rope: __owned Rope._Node) { insertAfterTip(Rope(root: rope)) } + @inlinable mutating func _insertBeforeTip(slots: Range, in node: __owned Rope._Node) { assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) let c = slots.count @@ -334,6 +356,7 @@ extension Rope { _insertBeforeTip(copy) } + @inlinable mutating func _insertAfterTip(slots: Range, in node: __owned Rope._Node) { assert(slots.lowerBound >= 0 && slots.upperBound <= node.childCount) let c = slots.count @@ -352,6 +375,7 @@ extension Rope { _insertAfterTip(copy) } + @inlinable public mutating func finalize() -> Rope { // Integrate prefix & suffix chunks. if let suffixItem = self._suffix._take() { @@ -390,6 +414,7 @@ extension Rope { return rope } + @inlinable public func _invariantCheck() { #if COLLECTIONS_INTERNAL_CHECKS var h = UInt8.max diff --git a/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift b/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift index 7149f66e..58c39615 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift @@ -14,19 +14,22 @@ import _CollectionsUtilities #endif extension Rope._UnmanagedLeaf: CustomStringConvertible { - var description: String { + @usableFromInline + internal var description: String { _addressString(for: _ref.toOpaque()) } } extension Rope { + @inlinable public var _nodeCount: Int { _root?.nodeCount ?? 0 } } extension Rope._Node { - var nodeCount: Int { + @inlinable + internal var nodeCount: Int { guard !isLeaf else { return 1 } return readInner { $0.children.reduce(into: 1) { $0 += $1.nodeCount } } } @@ -47,7 +50,8 @@ extension Rope { } extension Rope._Node: CustomStringConvertible { - var description: String { + @usableFromInline + internal var description: String { """ \(height > 0 ? "Inner@\(height)" : "Leaf")(\ at: \(_addressString(for: object)), \ @@ -58,6 +62,7 @@ extension Rope._Node: CustomStringConvertible { } extension Rope._Node { + @usableFromInline internal func dump( heightLimit: Int = .max, firstPrefix: String = "", diff --git a/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift b/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift index 3cb7b645..2424ecd7 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Invariants.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable @inline(__always) public func _invariantCheck() { #if COLLECTIONS_INTERNAL_CHECKS _root?.invariantCheck(depth: 0, height: root.height, recursive: true) @@ -18,8 +19,9 @@ extension Rope { } extension Rope._Node { - func invariantCheck(depth: UInt8, height: UInt8, recursive: Bool = true) { #if COLLECTIONS_INTERNAL_CHECKS + @usableFromInline + internal func invariantCheck(depth: UInt8, height: UInt8, recursive: Bool = true) { precondition(height == self.height, "Mismatching rope height") if isLeaf { precondition(self.childCount <= Summary.maxNodeSize, "Oversized leaf") @@ -58,6 +60,11 @@ extension Rope._Node { child.invariantCheck(depth: depth + 1, height: height - 1, recursive: true) } } -#endif } +#else + @inlinable @inline(__always) + internal func invariantCheck(depth: UInt8, height: UInt8, recursive: Bool = true) { + // Do nothing. + } +#endif } diff --git a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift index c2748e25..4f73ebd8 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift @@ -14,28 +14,34 @@ import _CollectionsUtilities // for 5.8 polyfills #endif extension Rope { - struct _Node: _RopeItem { - typealias Element = Rope.Element - typealias Summary = Rope.Summary - typealias Index = Rope.Index - typealias _Item = Rope._Item - typealias _Storage = Rope._Storage - typealias _UnsafeHandle = Rope._UnsafeHandle - typealias _Path = Rope._Path - typealias _UnmanagedLeaf = Rope._UnmanagedLeaf + @usableFromInline + internal struct _Node: _RopeItem { + @usableFromInline internal typealias Element = Rope.Element + @usableFromInline internal typealias Summary = Rope.Summary + @usableFromInline internal typealias Index = Rope.Index + @usableFromInline internal typealias _Item = Rope._Item + @usableFromInline internal typealias _Storage = Rope._Storage + @usableFromInline internal typealias _UnsafeHandle = Rope._UnsafeHandle + @usableFromInline internal typealias _Path = Rope._Path + @usableFromInline internal typealias _UnmanagedLeaf = Rope._UnmanagedLeaf - var object: AnyObject - var summary: Summary - - init(leaf: _Storage<_Item>, summary: Summary? = nil) { + @usableFromInline + internal var object: AnyObject + + @usableFromInline + internal var summary: Summary + + @inlinable + internal init(leaf: _Storage<_Item>, summary: Summary? = nil) { self.object = leaf self.summary = .zero self.summary = readLeaf { handle in handle.children.reduce(into: .zero) { $0.add($1.summary) } } } - - init(inner: _Storage<_Node>, summary: Summary? = nil) { + + @inlinable + internal init(inner: _Storage<_Node>, summary: Summary? = nil) { assert(inner.header.height > 0) self.object = inner self.summary = .zero @@ -47,59 +53,74 @@ extension Rope { } extension Rope._Node { - var _headerPtr: UnsafePointer<_RopeStorageHeader> { + @inlinable + internal var _headerPtr: UnsafePointer<_RopeStorageHeader> { let p = _getUnsafePointerToStoredProperties(object) .assumingMemoryBound(to: _RopeStorageHeader.self) return .init(p) } - - var header: _RopeStorageHeader { + + @inlinable + internal var header: _RopeStorageHeader { _headerPtr.pointee } + + @inlinable @inline(__always) + internal var height: UInt8 { header.height } - @inline(__always) - var height: UInt8 { header.height } + @inlinable @inline(__always) + internal var isLeaf: Bool { height == 0 } - @inline(__always) - var isLeaf: Bool { height == 0 } - - @inline(__always) - var asLeaf: _Storage<_Item> { + @inlinable @inline(__always) + internal var asLeaf: _Storage<_Item> { assert(height == 0) return unsafeDowncast(object, to: _Storage<_Item>.self) } - @inline(__always) - var asInner: _Storage { + @inlinable @inline(__always) + internal var asInner: _Storage { assert(height > 0) return unsafeDowncast(object, to: _Storage.self) } - @inline(__always) - var childCount: Int { header.childCount } + @inlinable @inline(__always) + internal var childCount: Int { header.childCount } - var isEmpty: Bool { childCount == 0 } - var isSingleton: Bool { isLeaf && childCount == 1 } - var isUndersized: Bool { childCount < Summary.minNodeSize } - var isFull: Bool { childCount == Summary.maxNodeSize } + @inlinable + internal var isEmpty: Bool { childCount == 0 } + + @inlinable + internal var isSingleton: Bool { isLeaf && childCount == 1 } + + @inlinable + internal var isUndersized: Bool { childCount < Summary.minNodeSize } + + @inlinable + internal var isFull: Bool { childCount == Summary.maxNodeSize } } extension Rope._Node { - static func createLeaf() -> Self { + @inlinable + internal static func createLeaf() -> Self { Self(leaf: .create(height: 0), summary: Summary.zero) } - - static func createLeaf(_ item: __owned _Item) -> Self { + + @inlinable + internal static func createLeaf(_ item: __owned _Item) -> Self { var leaf = createLeaf() leaf._appendItem(item) return leaf } - - static func createInner(height: UInt8) -> Self { + + @inlinable + internal static func createInner(height: UInt8) -> Self { Self(inner: .create(height: height), summary: .zero) } - - static func createInner(children left: __owned Self, _ right: __owned Self) -> Self { + + @inlinable + internal static func createInner( + children left: __owned Self, _ right: __owned Self + ) -> Self { assert(left.height == right.height) var new = createInner(height: left.height + 1) new.summary = left.summary @@ -113,26 +134,27 @@ extension Rope._Node { } extension Rope._Node { - @inline(__always) - mutating func isUnique() -> Bool { + @inlinable @inline(__always) + internal mutating func isUnique() -> Bool { isKnownUniquelyReferenced(&object) } - - mutating func ensureUnique() { + + @inlinable + internal mutating func ensureUnique() { guard !isKnownUniquelyReferenced(&object) else { return } self = copy() } - @inline(never) - func copy() -> Self { + @inlinable @inline(never) + internal func copy() -> Self { if isLeaf { return Self(leaf: readLeaf { $0.copy() }, summary: self.summary) } return Self(inner: readInner { $0.copy() }, summary: self.summary) } - @inline(never) - func copy(slots: Range) -> Self { + @inlinable @inline(never) + internal func copy(slots: Range) -> Self { if isLeaf { let (object, summary) = readLeaf { $0.copy(slots: slots) } return Self(leaf: object, summary: summary) @@ -141,8 +163,8 @@ extension Rope._Node { return Self(inner: object, summary: summary) } - @inline(__always) - func readLeaf( + @inlinable @inline(__always) + internal func readLeaf( _ body: (_UnsafeHandle<_Item>) -> R ) -> R { asLeaf.withUnsafeMutablePointers { h, p in @@ -151,8 +173,8 @@ extension Rope._Node { } } - @inline(__always) - mutating func updateLeaf( + @inlinable @inline(__always) + internal mutating func updateLeaf( _ body: (_UnsafeHandle<_Item>) -> R ) -> R { asLeaf.withUnsafeMutablePointers { h, p in @@ -161,8 +183,8 @@ extension Rope._Node { } } - @inline(__always) - func readInner( + @inlinable @inline(__always) + internal func readInner( _ body: (_UnsafeHandle) -> R ) -> R { asInner.withUnsafeMutablePointers { h, p in @@ -171,8 +193,8 @@ extension Rope._Node { } } - @inline(__always) - mutating func updateInner( + @inlinable @inline(__always) + internal mutating func updateInner( _ body: (_UnsafeHandle) -> R ) -> R { asInner.withUnsafeMutablePointers { h, p in @@ -183,14 +205,16 @@ extension Rope._Node { } extension Rope._Node { - mutating func _insertItem(_ item: __owned _Item, at slot: Int) { + @inlinable + internal mutating func _insertItem(_ item: __owned _Item, at slot: Int) { assert(isLeaf) ensureUnique() self.summary.add(item.summary) updateLeaf { $0._insertChild(item, at: slot) } } - - mutating func _insertNode(_ node: __owned Self, at slot: Int) { + + @inlinable + internal mutating func _insertNode(_ node: __owned Self, at slot: Int) { assert(!isLeaf) assert(self.height == node.height + 1) ensureUnique() @@ -200,14 +224,16 @@ extension Rope._Node { } extension Rope._Node { - mutating func _appendItem(_ item: __owned _Item) { + @inlinable + internal mutating func _appendItem(_ item: __owned _Item) { assert(isLeaf) ensureUnique() self.summary.add(item.summary) updateLeaf { $0._appendChild(item) } } - - mutating func _appendNode(_ node: __owned Self) { + + @inlinable + internal mutating func _appendNode(_ node: __owned Self) { assert(!isLeaf) ensureUnique() self.summary.add(node.summary) @@ -216,7 +242,10 @@ extension Rope._Node { } extension Rope._Node { - mutating func _removeItem(at slot: Int) -> (removed: _Item, delta: Summary) { + @inlinable + internal mutating func _removeItem( + at slot: Int + ) -> (removed: _Item, delta: Summary) { assert(isLeaf) ensureUnique() let item = updateLeaf { $0._removeChild(at: slot) } @@ -224,8 +253,9 @@ extension Rope._Node { self.summary.subtract(delta) return (item, delta) } - - mutating func _removeNode(at slot: Int) -> Self { + + @inlinable + internal mutating func _removeNode(at slot: Int) -> Self { assert(!isLeaf) ensureUnique() let result = updateInner { $0._removeChild(at: slot) } @@ -235,7 +265,8 @@ extension Rope._Node { } extension Rope._Node { - mutating func split(keeping desiredCount: Int) -> Self { + @inlinable + internal mutating func split(keeping desiredCount: Int) -> Self { assert(desiredCount >= 0 && desiredCount <= childCount) var new = isLeaf ? Self.createLeaf() : Self.createInner(height: height) guard desiredCount < childCount else { return new } @@ -251,7 +282,8 @@ extension Rope._Node { } extension Rope._Node { - mutating func rebalance(nextNeighbor right: inout Rope._Node) -> Bool { + @inlinable + internal mutating func rebalance(nextNeighbor right: inout Rope._Node) -> Bool { assert(self.height == right.height) if self.isEmpty { swap(&self, &right) @@ -267,8 +299,9 @@ extension Rope._Node { Self.redistributeChildren(&self, &right, to: desired) return right.isEmpty } - - mutating func rebalance(prevNeighbor left: inout Self) -> Bool { + + @inlinable + internal mutating func rebalance(prevNeighbor left: inout Self) -> Bool { guard left.rebalance(nextNeighbor: &self) else { return false } swap(&self, &left) return true @@ -276,6 +309,7 @@ extension Rope._Node { /// Shift children between `left` and `right` such that the number of children in `left` /// becomes `target`. + @inlinable internal static func redistributeChildren( _ left: inout Self, _ right: inout Self, @@ -298,8 +332,11 @@ extension Rope._Node { right.prependChildren(movingFromSuffixOf: &left, count: -d) } } - - mutating func appendChildren(movingFromPrefixOf other: inout Self, count: Int) { + + @inlinable + internal mutating func appendChildren( + movingFromPrefixOf other: inout Self, count: Int + ) { assert(self.height == other.height) let delta: Summary if isLeaf { @@ -318,8 +355,11 @@ extension Rope._Node { self.summary.add(delta) other.summary.subtract(delta) } - - mutating func prependChildren(movingFromSuffixOf other: inout Self, count: Int) { + + @inlinable + internal mutating func prependChildren( + movingFromSuffixOf other: inout Self, count: Int + ) { assert(self.height == other.height) let delta: Summary if isLeaf { @@ -341,26 +381,31 @@ extension Rope._Node { } extension Rope._Node { - var _startPath: _Path { + @inlinable + internal var _startPath: _Path { _Path(height: self.height) } - - var lastPath: _Path { + + @inlinable + internal var lastPath: _Path { var path = _Path(height: self.height) _ = descendToLastItem(under: &path) return path } - - func isAtEnd(_ path: _Path) -> Bool { + + @inlinable + internal func isAtEnd(_ path: _Path) -> Bool { path[self.height] == childCount } - - func descendToFirstItem(under path: inout _Path) -> _UnmanagedLeaf { + + @inlinable + internal func descendToFirstItem(under path: inout _Path) -> _UnmanagedLeaf { path.clear(below: self.height + 1) return unmanagedLeaf(at: path) } - - func descendToLastItem(under path: inout _Path) -> _UnmanagedLeaf { + + @inlinable + internal func descendToLastItem(under path: inout _Path) -> _UnmanagedLeaf { let h = self.height let slot = self.childCount - 1 path[h] = slot @@ -372,7 +417,8 @@ extension Rope._Node { } extension Rope { - func _unmanagedLeaf(at path: _Path) -> _UnmanagedLeaf? { + @inlinable + internal func _unmanagedLeaf(at path: _Path) -> _UnmanagedLeaf? { assert(path.height == self._height) guard path < _endPath else { return nil } return root.unmanagedLeaf(at: path) @@ -380,12 +426,14 @@ extension Rope { } extension Rope._Node { - var asUnmanagedLeaf: _UnmanagedLeaf { + @inlinable + internal var asUnmanagedLeaf: _UnmanagedLeaf { assert(height == 0) return _UnmanagedLeaf(unsafeDowncast(self.object, to: _Storage<_Item>.self)) } - - func unmanagedLeaf(at path: _Path) -> _UnmanagedLeaf { + + @inlinable + internal func unmanagedLeaf(at path: _Path) -> _UnmanagedLeaf { if height == 0 { return asUnmanagedLeaf } @@ -395,7 +443,8 @@ extension Rope._Node { } extension Rope._Node { - func formSuccessor(of i: inout Index) -> Bool { + @inlinable + internal func formSuccessor(of i: inout Index) -> Bool { let h = self.height var slot = i._path[h] if h == 0 { @@ -421,8 +470,9 @@ extension Rope._Node { return true } } - - func formPredecessor(of i: inout Index) -> Bool { + + @inlinable + internal func formPredecessor(of i: inout Index) -> Bool { let h = self.height var slot = i._path[h] if h == 0 { @@ -450,7 +500,8 @@ extension Rope._Node { } extension Rope._Node { - var lastItem: _Item { + @inlinable + internal var lastItem: _Item { get { self[lastPath] } @@ -463,8 +514,9 @@ extension Rope._Node { yield &state.item } } - - var firstItem: _Item { + + @inlinable + internal var firstItem: _Item { get { self[_startPath] } @@ -472,8 +524,9 @@ extension Rope._Node { yield &self[_startPath] } } - - subscript(path: _Path) -> _Item { + + @inlinable + internal subscript(path: _Path) -> _Item { get { let h = height let slot = path[h] @@ -492,14 +545,23 @@ extension Rope._Node { yield &state.item } } - - struct _ModifyState { - var path: _Path - var item: _Item - var summary: Summary + + @usableFromInline + internal struct _ModifyState { + @usableFromInline internal var path: _Path + @usableFromInline internal var item: _Item + @usableFromInline internal var summary: Summary + + @inlinable + internal init(path: _Path, item: _Item, summary: Summary) { + self.path = path + self.item = item + self.summary = summary + } } - - mutating func _prepareModify(at path: _Path) -> _ModifyState { + + @inlinable + internal mutating func _prepareModify(at path: _Path) -> _ModifyState { ensureUnique() let h = height let slot = path[h] @@ -510,13 +572,15 @@ extension Rope._Node { let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) } return _ModifyState(path: path, item: item, summary: item.summary) } - - mutating func _prepareModifyLast() -> _ModifyState { + + @inlinable + internal mutating func _prepareModifyLast() -> _ModifyState { var path = _Path(height: height) return _prepareModifyLast(&path) } - - mutating func _prepareModifyLast(_ path: inout _Path) -> _ModifyState { + + @inlinable + internal mutating func _prepareModifyLast(_ path: inout _Path) -> _ModifyState { ensureUnique() let h = height let slot = self.childCount - 1 @@ -527,8 +591,9 @@ extension Rope._Node { let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) } return _ModifyState(path: path, item: item, summary: item.summary) } - - mutating func _finalizeModify( + + @inlinable + internal mutating func _finalizeModify( _ state: inout _ModifyState ) -> (delta: Summary, leaf: _UnmanagedLeaf) { assert(isUnique()) diff --git a/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift b/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift index c5642ebb..c5599922 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift @@ -9,16 +9,19 @@ // //===----------------------------------------------------------------------===// +@usableFromInline internal struct _RopeStorageHeader { - var _childCount: UInt16 - let height: UInt8 - - init(height: UInt8) { + @usableFromInline var _childCount: UInt16 + @usableFromInline let height: UInt8 + + @inlinable + internal init(height: UInt8) { self._childCount = 0 self.height = height } - - var childCount: Int { + + @inlinable + internal var childCount: Int { get { numericCast(_childCount) } @@ -29,15 +32,20 @@ internal struct _RopeStorageHeader { } extension Rope { - final class _Storage>: ManagedBuffer<_RopeStorageHeader, Child> { - typealias Summary = Element.Summary - typealias _UnsafeHandle = Rope._UnsafeHandle - - static func create(height: UInt8) -> _Storage { + @usableFromInline + internal final class _Storage>: + ManagedBuffer<_RopeStorageHeader, Child> + { + @usableFromInline internal typealias Summary = Element.Summary + @usableFromInline internal typealias _UnsafeHandle = Rope._UnsafeHandle + + @inlinable + internal static func create(height: UInt8) -> _Storage { let object = create(minimumCapacity: Summary.maxNodeSize) { _ in .init(height: height) } return unsafeDowncast(object, to: _Storage.self) } - + + @inlinable deinit { withUnsafeMutablePointers { h, p in p.deinitialize(count: h.pointee.childCount) diff --git a/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift b/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift index ec393fa2..1c53c19a 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift @@ -10,27 +10,31 @@ //===----------------------------------------------------------------------===// extension Rope { + @usableFromInline internal struct _UnmanagedLeaf { - typealias _Item = Rope._Item - typealias _Leaf = _Storage<_Item> - typealias _UnsafeHandle = Rope._UnsafeHandle + @usableFromInline internal typealias _Item = Rope._Item + @usableFromInline internal typealias _Leaf = _Storage<_Item> + @usableFromInline internal typealias _UnsafeHandle = Rope._UnsafeHandle - var _ref: Unmanaged<_Leaf> + @usableFromInline var _ref: Unmanaged<_Leaf> - init(_ leaf: __shared _Leaf) { + @inlinable + internal init(_ leaf: __shared _Leaf) { _ref = .passUnretained(leaf) } } } extension Rope._UnmanagedLeaf: Equatable { - static func ==(left: Self, right: Self) -> Bool { + @inlinable + internal static func ==(left: Self, right: Self) -> Bool { left._ref.toOpaque() == right._ref.toOpaque() } } extension Rope._UnmanagedLeaf { - func read( + @inlinable + internal func read( body: (_UnsafeHandle<_Item>) -> R ) -> R { _ref._withUnsafeGuaranteedRef { leaf in diff --git a/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift b/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift index 0d6c7293..a7dcec47 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift @@ -10,17 +10,23 @@ //===----------------------------------------------------------------------===// extension Rope { + @usableFromInline internal struct _UnsafeHandle> { - typealias Summary = Rope.Summary - typealias Element = Rope.Element + @usableFromInline internal typealias Summary = Rope.Summary + @usableFromInline internal typealias Element = Rope.Element - let _header: UnsafeMutablePointer<_RopeStorageHeader> - let _start: UnsafeMutablePointer + @usableFromInline + internal let _header: UnsafeMutablePointer<_RopeStorageHeader> + + @usableFromInline + internal let _start: UnsafeMutablePointer #if DEBUG - let _isMutable: Bool + @usableFromInline + internal let _isMutable: Bool #endif - - init( + + @inlinable + internal init( isMutable: Bool, header: UnsafeMutablePointer<_RopeStorageHeader>, start: UnsafeMutablePointer @@ -32,8 +38,8 @@ extension Rope { #endif } - @inline(__always) - func assertMutable() { + @inlinable @inline(__always) + internal func assertMutable() { #if DEBUG assert(_isMutable) #endif @@ -42,47 +48,54 @@ extension Rope { } extension Rope._UnsafeHandle { - @inline(__always) - var capacity: Int { Summary.maxNodeSize } + @inlinable @inline(__always) + internal var capacity: Int { Summary.maxNodeSize } - @inline(__always) - var height: UInt8 { _header.pointee.height } - - var childCount: Int { + @inlinable @inline(__always) + internal var height: UInt8 { _header.pointee.height } + + @inlinable + internal var childCount: Int { get { _header.pointee.childCount } nonmutating set { assertMutable() _header.pointee.childCount = newValue } } - - var children: UnsafeBufferPointer { + + @inlinable + internal var children: UnsafeBufferPointer { UnsafeBufferPointer(start: _start, count: childCount) } - - func child(at slot: Int) -> Child? { + + @inlinable + internal func child(at slot: Int) -> Child? { assert(slot >= 0) guard slot < childCount else { return nil } return (_start + slot).pointee } - - var mutableChildren: UnsafeMutableBufferPointer { + + @inlinable + internal var mutableChildren: UnsafeMutableBufferPointer { assertMutable() return UnsafeMutableBufferPointer(start: _start, count: childCount) } - - func mutableChildPtr(at slot: Int) -> UnsafeMutablePointer { + + @inlinable + internal func mutableChildPtr(at slot: Int) -> UnsafeMutablePointer { assertMutable() assert(slot >= 0 && slot < childCount) return _start + slot } - - var mutableBuffer: UnsafeMutableBufferPointer { + + @inlinable + internal var mutableBuffer: UnsafeMutableBufferPointer { assertMutable() return UnsafeMutableBufferPointer(start: _start, count: capacity) } - - func copy() -> Rope._Storage { + + @inlinable + internal func copy() -> Rope._Storage { let new = Rope._Storage.create(height: self.height) let c = self.childCount new.header.childCount = c @@ -92,7 +105,10 @@ extension Rope._UnsafeHandle { return new } - func copy(slots: Range) -> (object: Rope._Storage, summary: Summary) { + @inlinable + internal func copy( + slots: Range + ) -> (object: Rope._Storage, summary: Summary) { assert(slots.lowerBound >= 0 && slots.upperBound <= childCount) let object = Rope._Storage.create(height: self.height) let c = slots.count @@ -104,7 +120,8 @@ extension Rope._UnsafeHandle { return (object, summary) } - func _insertChild(_ child: __owned Child, at slot: Int) { + @inlinable + internal func _insertChild(_ child: __owned Child, at slot: Int) { assertMutable() assert(childCount < capacity) assert(slot >= 0 && slot <= childCount) @@ -112,15 +129,17 @@ extension Rope._UnsafeHandle { (_start + slot).initialize(to: child) childCount += 1 } - - func _appendChild(_ child: __owned Child) { + + @inlinable + internal func _appendChild(_ child: __owned Child) { assertMutable() assert(childCount < capacity) (_start + childCount).initialize(to: child) childCount += 1 } - - func _removeChild(at slot: Int) -> Child { + + @inlinable + internal func _removeChild(at slot: Int) -> Child { assertMutable() assert(slot >= 0 && slot < childCount) let result = (_start + slot).move() @@ -129,7 +148,8 @@ extension Rope._UnsafeHandle { return result } - func _removePrefix(_ n: Int) -> Summary { + @inlinable + internal func _removePrefix(_ n: Int) -> Summary { assertMutable() assert(n <= childCount) var delta = Summary.zero @@ -143,7 +163,8 @@ extension Rope._UnsafeHandle { return delta } - func _removeSuffix(_ n: Int) -> Summary { + @inlinable + internal func _removeSuffix(_ n: Int) -> Summary { assertMutable() assert(n <= childCount) var delta = Summary.zero @@ -155,8 +176,11 @@ extension Rope._UnsafeHandle { childCount -= n return delta } - - func _appendChildren(movingFromPrefixOf src: Self, count: Int) -> Summary { + + @inlinable + internal func _appendChildren( + movingFromPrefixOf src: Self, count: Int + ) -> Summary { assertMutable() src.assertMutable() assert(self.height == src.height) @@ -170,8 +194,11 @@ extension Rope._UnsafeHandle { src.childCount -= count return children.suffix(count)._sum() } - - func _prependChildren(movingFromSuffixOf src: Self, count: Int) -> Summary { + + @inlinable + internal func _prependChildren( + movingFromSuffixOf src: Self, count: Int + ) -> Summary { assertMutable() src.assertMutable() assert(self.height == src.height) @@ -186,7 +213,10 @@ extension Rope._UnsafeHandle { return children.prefix(count)._sum() } - func distance(from start: Int, to end: Int, in metric: some RopeMetric) -> Int { + @inlinable + internal func distance( + from start: Int, to end: Int, in metric: some RopeMetric + ) -> Int { if start <= end { return children[start ..< end].reduce(into: 0) { $0 += metric._nonnegativeSize(of: $1.summary) diff --git a/Sources/RopeModule/Rope/Basics/Rope.swift b/Sources/RopeModule/Rope/Basics/Rope.swift index 43d631e3..5411fb2a 100644 --- a/Sources/RopeModule/Rope/Basics/Rope.swift +++ b/Sources/RopeModule/Rope/Basics/Rope.swift @@ -13,24 +13,31 @@ /// The rope is augmented by the commutative group specified by `Element.Summary`, enabling /// quick lookup operations. public struct Rope { - var _root: _Node? - var _version: _RopeVersion + @usableFromInline + internal var _root: _Node? + @usableFromInline + internal var _version: _RopeVersion + + @inlinable public init() { self._root = nil self._version = _RopeVersion() } - - init(root: _Node?) { + + @inlinable + internal init(root: _Node?) { self._root = root self._version = _RopeVersion() } - var root: _Node { - get { _root.unsafelyUnwrapped } + @inlinable + internal var root: _Node { + @inline(__always) get { _root.unsafelyUnwrapped } @inline(__always) _modify { yield &_root! } } - + + @inlinable public init(_ value: Element) { self._root = .createLeaf(_Item(value)) self._version = _RopeVersion() @@ -40,13 +47,15 @@ public struct Rope { extension Rope: Sendable where Element: Sendable {} extension Rope { - mutating func _ensureUnique() { + @inlinable + internal mutating func _ensureUnique() { guard _root != nil else { return } root.ensureUnique() } } extension Rope { + @inlinable public var isSingleton: Bool { guard _root != nil else { return false } return root.isSingleton @@ -54,6 +63,7 @@ extension Rope { } extension Rope { + @inlinable public func isIdentical(to other: Self) -> Bool { self._root?.object === other._root?.object } diff --git a/Sources/RopeModule/Rope/Basics/RopeMetric.swift b/Sources/RopeModule/Rope/Basics/RopeMetric.swift index ad6d4f63..37711b64 100644 --- a/Sources/RopeModule/Rope/Basics/RopeMetric.swift +++ b/Sources/RopeModule/Rope/Basics/RopeMetric.swift @@ -17,7 +17,7 @@ public protocol RopeMetric: Sendable { } extension RopeMetric { - @inline(__always) + @inlinable @inline(__always) internal func _nonnegativeSize(of summary: Element.Summary) -> Int { let r = size(of: summary) assert(r >= 0) diff --git a/Sources/RopeModule/Rope/Basics/_RopeItem.swift b/Sources/RopeModule/Rope/Basics/_RopeItem.swift index 61724d8a..db24ab04 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeItem.swift +++ b/Sources/RopeModule/Rope/Basics/_RopeItem.swift @@ -14,6 +14,7 @@ /// Used as an implementation detail to increase code reuse across internal nodes and leaf nodes. /// (Ideally `Rope._Node` would just conform to the full `RopeElement` protocol on its own, but /// while that's an obvious refactoring idea, it hasn't happened yet.) +@usableFromInline internal protocol _RopeItem { associatedtype Summary: RopeSummary @@ -21,7 +22,8 @@ internal protocol _RopeItem { } extension Sequence where Element: _RopeItem { - func _sum() -> Element.Summary { + @inlinable + internal func _sum() -> Element.Summary { self.reduce(into: .zero) { $0.add($1.summary) } } } @@ -29,6 +31,7 @@ extension Sequence where Element: _RopeItem { extension Rope: _RopeItem { public typealias Summary = Element.Summary + @inlinable public var summary: Summary { guard _root != nil else { return .zero } return root.summary @@ -38,35 +41,50 @@ extension Rope: _RopeItem { extension Rope { /// A trivial wrapper around a rope's Element type, giving it `_RopeItem` conformance without /// having to make the protocol public. + @usableFromInline internal struct _Item { - var value: Element - init(_ value: Element) { self.value = value } + @usableFromInline internal var value: Element + + @inlinable + internal init(_ value: Element) { self.value = value } } } extension Rope._Item: _RopeItem { - typealias Summary = Rope.Summary - var summary: Summary { value.summary } + @usableFromInline internal typealias Summary = Rope.Summary + + @inlinable + internal var summary: Summary { value.summary } } extension Rope._Item: CustomStringConvertible { - var description: String { + @usableFromInline + internal var description: String { "\(value)" } } extension Rope._Item { - var isEmpty: Bool { value.isEmpty } - var isUndersized: Bool { value.isUndersized } - mutating func rebalance(nextNeighbor right: inout Self) -> Bool { + @inlinable + internal var isEmpty: Bool { value.isEmpty } + + @inlinable + internal var isUndersized: Bool { value.isUndersized } + + @inlinable + internal mutating func rebalance(nextNeighbor right: inout Self) -> Bool { value.rebalance(nextNeighbor: &right.value) } - mutating func rebalance(prevNeighbor left: inout Self) -> Bool { + + @inlinable + internal mutating func rebalance(prevNeighbor left: inout Self) -> Bool { value.rebalance(prevNeighbor: &left.value) } - typealias Index = Element.Index - mutating func split(at index: Index) -> Self { + @usableFromInline internal typealias Index = Element.Index + + @inlinable + internal mutating func split(at index: Index) -> Self { Self(self.value.split(at: index)) } } diff --git a/Sources/RopeModule/Rope/Basics/_RopePath.swift b/Sources/RopeModule/Rope/Basics/_RopePath.swift index c7278eea..fc0fe552 100644 --- a/Sources/RopeModule/Rope/Basics/_RopePath.swift +++ b/Sources/RopeModule/Rope/Basics/_RopePath.swift @@ -9,50 +9,58 @@ // //===----------------------------------------------------------------------===// +@usableFromInline +@frozen // Not really! This module isn't ABI stable internal struct _RopePath { // ┌──────────────────────────────────┬────────┐ // │ b63:b8 │ b7:b0 │ // ├──────────────────────────────────┼────────┤ // │ path │ height │ // └──────────────────────────────────┴────────┘ - var _value: UInt64 + @usableFromInline internal var _value: UInt64 - @inline(__always) - static var _pathBitWidth: Int { 56 } + @inlinable @inline(__always) + internal static var _pathBitWidth: Int { 56 } - init(_value: UInt64) { + @inlinable + internal init(_value: UInt64) { self._value = _value } - init(height: UInt8) { + @inlinable + internal init(height: UInt8) { self._value = UInt64(truncatingIfNeeded: height) assert((Int(height) + 1) * Summary.nodeSizeBitWidth <= Self._pathBitWidth) } } extension Rope { - typealias _Path = _RopePath + @usableFromInline internal typealias _Path = _RopePath } extension _RopePath: Equatable { - static func ==(left: Self, right: Self) -> Bool { + @inlinable + internal static func ==(left: Self, right: Self) -> Bool { left._value == right._value } } extension _RopePath: Hashable { - func hash(into hasher: inout Hasher) { + @inlinable + internal func hash(into hasher: inout Hasher) { hasher.combine(_value) } } extension _RopePath: Comparable { - static func <(left: Self, right: Self) -> Bool { + @inlinable + internal static func <(left: Self, right: Self) -> Bool { left._value < right._value } } extension _RopePath: CustomStringConvertible { - var description: String { + @usableFromInline + internal var description: String { var r = "<" for h in stride(from: height, through: 0, by: -1) { r += "\(self[h])" @@ -64,11 +72,13 @@ extension _RopePath: CustomStringConvertible { } extension _RopePath { - var height: UInt8 { + @inlinable + internal var height: UInt8 { UInt8(truncatingIfNeeded: _value) } - subscript(height: UInt8) -> Int { + @inlinable + internal subscript(height: UInt8) -> Int { get { assert(height <= self.height) let shift = 8 + Int(height) * Summary.nodeSizeBitWidth @@ -85,14 +95,16 @@ extension _RopePath { } } - func isEmpty(below height: UInt8) -> Bool { + @inlinable + internal func isEmpty(below height: UInt8) -> Bool { let shift = Int(height) * Summary.nodeSizeBitWidth assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth) let mask: UInt64 = ((1 &<< shift) - 1) &<< 8 return (_value & mask) == 0 } - mutating func clear(below height: UInt8) { + @inlinable + internal mutating func clear(below height: UInt8) { let shift = Int(height) * Summary.nodeSizeBitWidth assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth) let mask: UInt64 = ((1 &<< shift) - 1) &<< 8 diff --git a/Sources/RopeModule/Rope/Basics/_RopeVersion.swift b/Sources/RopeModule/Rope/Basics/_RopeVersion.swift index f85d2e40..26e7098b 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeVersion.swift +++ b/Sources/RopeModule/Rope/Basics/_RopeVersion.swift @@ -9,32 +9,39 @@ // //===----------------------------------------------------------------------===// +@usableFromInline +@frozen // Not really! This module isn't ABI stable. internal struct _RopeVersion { // FIXME: Replace this probabilistic mess with atomics when Swift gets its act together. - var _value: UInt + @usableFromInline internal var _value: UInt - init() { + @inlinable + internal init() { var rng = SystemRandomNumberGenerator() _value = rng.next() } - init(_ value: UInt) { + @inlinable + internal init(_ value: UInt) { self._value = value } } extension _RopeVersion: Equatable { - static func ==(left: Self, right: Self) -> Bool { + @inlinable + internal static func ==(left: Self, right: Self) -> Bool { left._value == right._value } } extension _RopeVersion { - mutating func bump() { + @inlinable + internal mutating func bump() { _value &+= 1 } - mutating func reset() { + @inlinable + internal mutating func reset() { var rng = SystemRandomNumberGenerator() _value = rng.next() } diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift index ebf22f34..8fe4aeb7 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift @@ -10,20 +10,24 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public func isValid(_ index: Index) -> Bool { index._version == _version } + @inlinable public func validate(_ index: Index) { precondition(isValid(index), "Invalid index") } - mutating func _invalidateIndices() { + @inlinable + internal mutating func _invalidateIndices() { _version.bump() } /// Validate `index` and fill out all cached information in it, /// to speed up subsequent lookups. + @inlinable public func grease(_ index: inout Index) { validate(index) guard index._leaf == nil else { return } @@ -32,15 +36,18 @@ extension Rope { } extension Rope { + @inlinable public var _height: UInt8 { _root?.height ?? 0 } - var _startPath: _Path { + @inlinable + internal var _startPath: _Path { _Path(height: _height) } - var _endPath: _Path { + @inlinable + internal var _endPath: _Path { guard let root = _root else { return _startPath } var path = _Path(height: _height) path[_height] = root.childCount @@ -49,32 +56,38 @@ extension Rope { } extension Rope: BidirectionalCollection { + @inlinable public var isEmpty: Bool { guard _root != nil else { return true } return root.childCount == 0 } + @inlinable public var startIndex: Index { // Note: `leaf` is intentionally not set here, to speed up accessing this property. return Index(version: _version, path: _startPath, leaf: nil) } + @inlinable public var endIndex: Index { Index(version: _version, path: _endPath, leaf: nil) } - + + @inlinable public func index(after i: Index) -> Index { var i = i formIndex(after: &i) return i } - + + @inlinable public func index(before i: Index) -> Index { var i = i formIndex(before: &i) return i } - + + @inlinable public func formIndex(after i: inout Index) { validate(i) precondition(i < endIndex, "Can't move after endIndex") @@ -91,7 +104,8 @@ extension Rope: BidirectionalCollection { i = endIndex } } - + + @inlinable public func formIndex(before i: inout Index) { validate(i) precondition(i > startIndex, "Can't move before startIndex") @@ -107,7 +121,8 @@ extension Rope: BidirectionalCollection { let success = root.formPredecessor(of: &i) precondition(success, "Invalid index") } - + + @inlinable public subscript(i: Index) -> Element { get { validate(i) @@ -129,6 +144,7 @@ extension Rope: BidirectionalCollection { extension Rope { /// Update the element at the given index, while keeping the index valid. + @inlinable public mutating func update( at index: inout Index, by body: (inout Element) -> R @@ -143,6 +159,7 @@ extension Rope { } extension Rope { + @inlinable @inline(__always) public static var _maxHeight: Int { _Path._pathBitWidth / Summary.nodeSizeBitWidth } @@ -153,6 +170,7 @@ extension Rope { /// representation used in the `Index` type.) /// /// This is one less than the minimum possible size for a rope whose size exceeds the maximum. + @inlinable public static var _minimumCapacity: Int { var c = 2 for _ in 0 ..< _maxHeight { @@ -167,6 +185,7 @@ extension Rope { /// the tree consists of maximum-sized nodes. (The data structure itself has no inherent limit, /// but this implementation of it is limited by the fixed 56-bit path representation used in /// the `Index` type.) + @inlinable public static var _maximumCapacity: Int { var c = 1 for _ in 0 ... _maxHeight { @@ -179,6 +198,7 @@ extension Rope { } extension Rope { + @inlinable public func count(in metric: some RopeMetric) -> Int { guard _root != nil else { return 0 } return root.count(in: metric) @@ -186,12 +206,14 @@ extension Rope { } extension Rope._Node { + @inlinable public func count(in metric: some RopeMetric) -> Int { metric._nonnegativeSize(of: self.summary) } } extension Rope { + @inlinable public func distance(from start: Index, to end: Index, in metric: some RopeMetric) -> Int { validate(start) validate(end) @@ -212,7 +234,8 @@ extension Rope { return -root.distance(from: end, to: start, in: metric) } - func offset(of index: Index, in metric: some RopeMetric) -> Int { + @inlinable + public func offset(of index: Index, in metric: some RopeMetric) -> Int { validate(index) if _root == nil { return 0 } return root.distanceFromStart(to: index, in: metric) @@ -220,7 +243,10 @@ extension Rope { } extension Rope._Node { - func distanceFromStart(to index: Index, in metric: some RopeMetric) -> Int { + @inlinable + internal func distanceFromStart( + to index: Index, in metric: some RopeMetric + ) -> Int { let slot = index._path[height] precondition(slot <= childCount, "Invalid index") if slot == childCount { @@ -236,14 +262,20 @@ extension Rope._Node { return distance } } - - func distanceToEnd(from index: Index, in metric: some RopeMetric) -> Int { + + @inlinable + internal func distanceToEnd( + from index: Index, in metric: some RopeMetric + ) -> Int { let d = metric._nonnegativeSize(of: self.summary) - self.distanceFromStart(to: index, in: metric) assert(d >= 0) return d } - - func distance(from start: Index, to end: Index, in metric: some RopeMetric) -> Int { + + @inlinable + internal func distance( + from start: Index, to end: Index, in metric: some RopeMetric + ) -> Int { assert(start < end) let a = start._path[height] let b = end._path[height] @@ -272,6 +304,7 @@ extension Rope._Node { } extension Rope { + @inlinable public func formIndex( _ i: inout Index, offsetBy distance: inout Int, @@ -303,7 +336,8 @@ extension Rope { precondition(distance == 0, "Position out of bounds") i = endIndex } - + + @inlinable public func index( _ i: Index, offsetBy distance: Int, @@ -318,6 +352,7 @@ extension Rope { } extension Rope._UnsafeHandle { + @inlinable func _seekForwardInLeaf( from path: inout Rope._Path, by distance: inout Int, @@ -340,6 +375,7 @@ extension Rope._UnsafeHandle { return false } + @inlinable func _seekBackwardInLeaf( from path: inout Rope._Path, by distance: inout Int, @@ -365,6 +401,7 @@ extension Rope._UnsafeHandle { } extension Rope._Node { + @inlinable func seekForward( from i: inout Index, by distance: inout Int, @@ -407,7 +444,8 @@ extension Rope._Node { return false } } - + + @inlinable func seekBackward( from i: inout Index, by distance: inout Int, diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Index.swift b/Sources/RopeModule/Rope/Conformances/Rope+Index.swift index e90f3e36..1e686688 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Index.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Index.swift @@ -10,18 +10,27 @@ //===----------------------------------------------------------------------===// extension Rope { + @frozen // Not really! This module isn't ABI stable. public struct Index: @unchecked Sendable { - typealias Summary = Rope.Summary - typealias _Path = Rope._Path + @usableFromInline internal typealias Summary = Rope.Summary + @usableFromInline internal typealias _Path = Rope._Path + + @usableFromInline + internal var _version: _RopeVersion + + @usableFromInline + internal var _path: _Path - var _version: _RopeVersion - var _path: _Path /// A direct reference to the leaf node addressed by this index. /// This must only be dereferenced while we own a tree with a matching /// version. - var _leaf: _UnmanagedLeaf? + @usableFromInline + internal var _leaf: _UnmanagedLeaf? - init(version: _RopeVersion, path: _Path, leaf: __shared _UnmanagedLeaf?) { + @inlinable + internal init( + version: _RopeVersion, path: _Path, leaf: __shared _UnmanagedLeaf? + ) { self._version = version self._path = path self._leaf = leaf @@ -30,27 +39,32 @@ extension Rope { } extension Rope.Index { - static var _invalid: Self { + @inlinable + internal static var _invalid: Self { Self(version: _RopeVersion(0), path: _RopePath(_value: .max), leaf: nil) } - var _isValid: Bool { + @inlinable + internal var _isValid: Bool { _path._value != .max } } extension Rope.Index: Equatable { + @inlinable public static func ==(left: Self, right: Self) -> Bool { left._path == right._path } } extension Rope.Index: Hashable { + @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(_path) } } extension Rope.Index: Comparable { + @inlinable public static func <(left: Self, right: Self) -> Bool { left._path < right._path } @@ -63,15 +77,18 @@ extension Rope.Index: CustomStringConvertible { } extension Rope.Index { - var _height: UInt8 { + @inlinable + internal var _height: UInt8 { _path.height } - func _isEmpty(below height: UInt8) -> Bool { + @inlinable + internal func _isEmpty(below height: UInt8) -> Bool { _path.isEmpty(below: height) } - mutating func _clear(below height: UInt8) { + @inlinable + internal mutating func _clear(below height: UInt8) { _path.clear(below: height) } } diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift index 8c9a90b9..471064b4 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift @@ -10,29 +10,37 @@ //===----------------------------------------------------------------------===// extension Rope: Sequence { + @inlinable public func makeIterator() -> Iterator { Iterator(self, from: self.startIndex) } - + + @inlinable public func makeIterator(from start: Index) -> Iterator { Iterator(self, from: start) } - - public struct Iterator: IteratorProtocol { - let rope: Rope - private(set) var index: Index - init(_ rope: Rope, from start: Index) { + @frozen // Not really! This module isn't ABI stable. + public struct Iterator: IteratorProtocol { + @usableFromInline + internal let _rope: Rope + + @usableFromInline + internal var _index: Index + + @inlinable + internal init(_ rope: Rope, from start: Index) { rope.validate(start) - self.rope = rope - self.index = start - self.rope.grease(&index) + self._rope = rope + self._index = start + self._rope.grease(&_index) } - + + @inlinable public mutating func next() -> Element? { - guard let leaf = index._leaf else { return nil } - let item = leaf.read { $0.children[index._path[0]].value } - rope.formIndex(after: &index) + guard let leaf = _index._leaf else { return nil } + let item = leaf.read { $0.children[_index._path[0]].value } + _rope.formIndex(after: &_index) return item } } diff --git a/Sources/RopeModule/Rope/Operations/Rope+Append.swift b/Sources/RopeModule/Rope/Operations/Rope+Append.swift index dc31c9ca..ddc45524 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Append.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Append.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public mutating func append(_ item: __owned Element) { _invalidateIndices() if _root == nil { @@ -23,7 +24,8 @@ extension Rope { } extension Rope._Node { - mutating func append(_ item: __owned _Item) -> Self? { + @inlinable + internal mutating func append(_ item: __owned _Item) -> Self? { var item = item if item.isUndersized, !self.isEmpty, self.lastItem.rebalance(nextNeighbor: &item) { return nil diff --git a/Sources/RopeModule/Rope/Operations/Rope+Extract.swift b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift index 5ffd2bc7..2883af2f 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Extract.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public func extract(from start: Int, to end: Int, in metric: some RopeMetric) -> Self { if _root == nil { precondition(start == 0 && end == 0, "Invalid range") @@ -22,7 +23,8 @@ extension Rope { } extension Rope._Node { - func extract( + @inlinable + internal func extract( from start: Int, to end: Int, in metric: some RopeMetric, diff --git a/Sources/RopeModule/Rope/Operations/Rope+Find.swift b/Sources/RopeModule/Rope/Operations/Rope+Find.swift index 6f97709e..a6d4ff44 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Find.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Find.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public func find( at position: Int, in metric: some RopeMetric, @@ -39,7 +40,8 @@ extension Rope { } extension Rope._UnsafeHandle { - func findSlot( + @inlinable + internal func findSlot( at position: Int, in metric: some RopeMetric, preferEnd: Bool = true @@ -59,7 +61,8 @@ extension Rope._UnsafeHandle { return preferEnd ? (childCount - 1, remaining + size) : (childCount, 0) } - func findSlot( + @inlinable + internal func findSlot( from p: (slot: Int, remaining: Int), offsetBy distance: Int, in metric: some RopeMetric, diff --git a/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift b/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift index 69d2611e..b6cf0473 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public func forEachWhile( _ body: (Element) -> Bool ) -> Bool { @@ -17,6 +18,7 @@ extension Rope { return root.forEachWhile(body) } + @inlinable public func forEachWhile( from position: Int, in metric: some RopeMetric, @@ -31,7 +33,8 @@ extension Rope { } extension Rope._Node { - func forEachWhile( + @inlinable + internal func forEachWhile( _ body: (Element) -> Bool ) -> Bool { if isLeaf { @@ -52,7 +55,8 @@ extension Rope._Node { } } - func forEachWhile( + @inlinable + internal func forEachWhile( from position: Int, in metric: some RopeMetric, _ body: (Element, Element.Index?) -> Bool diff --git a/Sources/RopeModule/Rope/Operations/Rope+Insert.swift b/Sources/RopeModule/Rope/Operations/Rope+Insert.swift index 873b9e71..e1c06daa 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Insert.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Insert.swift @@ -10,11 +10,13 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public mutating func prepend(_ item: __owned Element) { _invalidateIndices() insert(item, at: startIndex) } - + + @inlinable public mutating func insert( _ item: __owned Element, at index: Index @@ -23,6 +25,7 @@ extension Rope { insert(item, at: index._path) } + @inlinable mutating func insert( _ item: __owned Element, at path: _Path @@ -36,7 +39,8 @@ extension Rope { } _invalidateIndices() } - + + @inlinable public mutating func insert( _ item: __owned Element, at position: Int, @@ -54,11 +58,13 @@ extension Rope { } extension Rope._Node { - mutating func prepend(_ item: __owned _Item) -> Self? { + @inlinable + internal mutating func prepend(_ item: __owned _Item) -> Self? { insert(item, at: _startPath) } - - mutating func insert( + + @inlinable + internal mutating func insert( _ item: __owned _Item, at path: _Path ) -> Self? { @@ -72,8 +78,9 @@ extension Rope._Node { precondition(slot <= childCount, "Index out of bounds") return _leafInsert(item, at: slot) } - - mutating func insert( + + @inlinable + internal mutating func insert( _ item: __owned _Item, at position: Int, in metric: some RopeMetric @@ -94,7 +101,8 @@ extension Rope._Node { } extension Rope._Node { - mutating func _innerInsert( + @inlinable + internal mutating func _innerInsert( at slot: Int, with body: (inout Self) -> Self? ) -> Self? { @@ -111,8 +119,11 @@ extension Rope._Node { guard let spawn = spawn else { return nil } return _applySpawn(spawn, of: slot) } - - mutating func _applySpawn(_ spawn: __owned Self, of slot: Int) -> Self? { + + @inlinable + internal mutating func _applySpawn( + _ spawn: __owned Self, of slot: Int + ) -> Self? { var spawn = spawn var nextSlot = slot + 1 #if true // Compress existing nodes if possible. @@ -161,7 +172,10 @@ extension Rope._Node { } extension Rope._Node { - mutating func _leafInsert(_ item: __owned _Item, at slot: Int) -> Self? { + @inlinable + internal mutating func _leafInsert( + _ item: __owned _Item, at slot: Int + ) -> Self? { assert(slot <= childCount) var item = item if item.isUndersized, childCount > 0, _rebalanceBeforeInsert(&item, at: slot) { @@ -181,8 +195,11 @@ extension Rope._Node { spawn._insertItem(item, at: slot - childCount) return spawn } - - mutating func _rebalanceBeforeInsert(_ item: inout _Item, at slot: Int) -> Bool { + + @inlinable + internal mutating func _rebalanceBeforeInsert( + _ item: inout _Item, at slot: Int + ) -> Bool { assert(item.isUndersized) let r = updateLeaf { (h) -> (merged: Bool, delta: Summary) in if slot > 0 { diff --git a/Sources/RopeModule/Rope/Operations/Rope+Join.swift b/Sources/RopeModule/Rope/Operations/Rope+Join.swift index c73a2cbf..4fcea99d 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Join.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Join.swift @@ -10,23 +10,28 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public mutating func append(_ other: __owned Self) { self = Rope.join(self, other) } + @inlinable public mutating func prepend(_ other: __owned Self) { self = Rope.join(other, self) } - mutating func _append(_ other: __owned _Node) { + @inlinable + internal mutating func _append(_ other: __owned _Node) { append(Self(root: other)) } - mutating func _prepend(_ other: __owned _Node) { + @inlinable + internal mutating func _prepend(_ other: __owned _Node) { prepend(Self(root: other)) } /// Concatenate `left` and `right` by linking up the two trees. + @inlinable public static func join(_ left: __owned Self, _ right: __owned Self) -> Self { guard !right.isEmpty else { return left } guard !left.isEmpty else { return right } @@ -54,7 +59,10 @@ extension Rope { } extension Rope._Node { - mutating func _graftFront(_ scion: inout Self) -> (remainder: Self?, delta: Summary) { + @inlinable + internal mutating func _graftFront( + _ scion: inout Self + ) -> (remainder: Self?, delta: Summary) { assert(self.height >= scion.height) guard self.height > scion.height else { assert(self.height == scion.height) @@ -85,8 +93,11 @@ extension Rope._Node { splinter._insertNode(remainder, at: 0) return (splinter, delta) } - - mutating func _graftBack(_ scion: inout Self) -> (remainder: Self?, delta: Summary) { + + @inlinable + internal mutating func _graftBack( + _ scion: inout Self + ) -> (remainder: Self?, delta: Summary) { assert(self.height >= scion.height) guard self.height > scion.height else { assert(self.height == scion.height) diff --git a/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift b/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift index bd1e5740..06a3723f 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { - @inline(__always) + @inlinable @inline(__always) @discardableResult public mutating func mutatingForEach( _ body: (inout Element) -> R? @@ -19,7 +19,7 @@ extension Rope { return mutatingForEach(from: &i, body) } - @inline(__always) + @inlinable @inline(__always) @discardableResult public mutating func mutatingForEach( from index: inout Index, @@ -33,8 +33,9 @@ extension Rope { assert(completed == (r == nil)) return r } - - mutating func _mutatingForEach( + + @inlinable + internal mutating func _mutatingForEach( from index: inout Index, _ body: (inout Element) -> Bool ) -> Bool { @@ -50,7 +51,8 @@ extension Rope { } extension Rope._Node { - mutating func mutatingForEach( + @inlinable + internal mutating func mutatingForEach( from index: inout Index, body: (inout Element) -> Bool ) -> (continue: Bool, delta: Summary) { diff --git a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift index 7a19183a..8f4d07e8 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public mutating func remove(at index: Index) -> Element { validate(index) let old = root.remove(at: index._path).removed @@ -24,7 +25,8 @@ extension Rope { } extension Rope._Node { - mutating func remove( + @inlinable + internal mutating func remove( at path: _Path ) -> (removed: _Item, delta: Summary, needsFixing: Bool) { ensureUnique() @@ -44,6 +46,7 @@ extension Rope._Node { } extension Rope { + @inlinable public mutating func remove( at position: Int, in metric: some RopeMetric @@ -60,7 +63,8 @@ extension Rope { } extension Rope._Node { - mutating func remove( + @inlinable + internal mutating func remove( at position: Int, in metric: some RopeMetric ) -> (removed: _Item, delta: Summary, needsFixing: Bool) { @@ -86,7 +90,8 @@ extension Rope._Node { } extension Rope._Node { - mutating func fixDeficiency(at slot: Int) { + @inlinable + internal mutating func fixDeficiency(at slot: Int) { assert(isUnique()) updateInner { let c = $0.mutableChildren diff --git a/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift index 2ade38a1..163edef4 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public mutating func removeSubrange( _ bounds: Range, in metric: some RopeMetric @@ -24,6 +25,7 @@ extension Rope { self = builder.finalize() } + @inlinable public mutating func replaceSubrange( _ bounds: Range, in metric: some RopeMetric, @@ -40,6 +42,7 @@ extension Rope { self = builder.finalize() } + @inlinable public mutating func builder( removing bounds: Range, in metric: some RopeMetric @@ -96,7 +99,8 @@ extension Rope { } extension Rope._Node { - __consuming func _removeSubrange( + @inlinable + internal __consuming func _removeSubrange( from start: (slot: Int, remaining: Int), to end: (slot: Int, remaining: Int), in metric: some RopeMetric, @@ -130,7 +134,8 @@ extension Rope._Node { builder._insertAfterTip(upper.split(at: i2)) } - __consuming func removeSuffix( + @inlinable + internal __consuming func removeSuffix( from position: Int, in metric: some RopeMetric, into builder: inout Rope.Builder @@ -158,7 +163,8 @@ extension Rope._Node { builder._insertBeforeTip(item) } - __consuming func removePrefix( + @inlinable + internal __consuming func removePrefix( upTo position: Int, in metric: some RopeMetric, into builder: inout Rope.Builder @@ -184,7 +190,8 @@ extension Rope._Node { builder._insertAfterTip(item.split(at: i)) } - mutating func _innerRemoveSuffix( + @inlinable + internal mutating func _innerRemoveSuffix( descending slot: Int, into builder: inout Rope.Builder ) { @@ -216,7 +223,8 @@ extension Rope._Node { builder._insertBeforeTip(n) } - __consuming func _leafRemoveSuffix( + @inlinable + internal __consuming func _leafRemoveSuffix( returning slot: Int, into builder: inout Rope.Builder ) -> _Item { @@ -246,7 +254,8 @@ extension Rope._Node { return item } - mutating func _innerRemovePrefix( + @inlinable + internal mutating func _innerRemovePrefix( descending slot: Int, into builder: inout Rope.Builder ) { @@ -279,7 +288,8 @@ extension Rope._Node { builder._insertAfterTip(n) } - __consuming func _leafRemovePrefix( + @inlinable + internal __consuming func _leafRemovePrefix( returning slot: Int, into builder: inout Rope.Builder ) -> _Item { diff --git a/Sources/RopeModule/Rope/Operations/Rope+Split.swift b/Sources/RopeModule/Rope/Operations/Rope+Split.swift index bae6da0a..dab68354 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Split.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Split.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable public mutating func builder( splittingAt position: Int, in metric: some RopeMetric @@ -35,6 +36,7 @@ extension Rope { return builder } + @inlinable public mutating func split(at index: Index) -> (builder: Builder, item: Element) { validate(index) precondition(index < endIndex) @@ -55,6 +57,7 @@ extension Rope { return (builder, item.value) } + @inlinable public mutating func split(at ropeIndex: Index, _ itemIndex: Element.Index) -> Builder { var (builder, item) = self.split(at: ropeIndex) let suffix = item.split(at: itemIndex) @@ -69,7 +72,8 @@ extension Rope { } extension Rope._Node { - mutating func _innerSplit( + @inlinable + internal mutating func _innerSplit( at slot: Int, into builder: inout Rope.Builder ) { @@ -102,8 +106,9 @@ extension Rope._Node { builder._insertBeforeTip(n) builder._insertAfterTip(suffix) } - - __consuming func _leafSplit( + + @inlinable + internal __consuming func _leafSplit( at slot: Int, into builder: inout Rope.Builder ) -> _Item { diff --git a/Sources/RopeModule/Utilities/Optional Utilities.swift b/Sources/RopeModule/Utilities/Optional Utilities.swift index 16e8ed35..c5f54f28 100644 --- a/Sources/RopeModule/Utilities/Optional Utilities.swift +++ b/Sources/RopeModule/Utilities/Optional Utilities.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Optional { + @inlinable internal mutating func _take() -> Self { let r = self self = nil diff --git a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/_RopeModule.xcscheme similarity index 87% rename from Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme rename to Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/_RopeModule.xcscheme index c487bb69..eecd34c5 100644 --- a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/RopeModule.xcscheme +++ b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/_RopeModule.xcscheme @@ -1,6 +1,6 @@ @@ -75,9 +75,9 @@ @@ -89,7 +89,4 @@ buildConfiguration = "Release" revealArchiveInOrganizer = "YES"> - - From 4b6978bf8b220c9c7d03d1f8124d537fbbddc32a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 10 Apr 2023 17:06:33 -0700 Subject: [PATCH 100/113] Require Swift 5.6 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Swift 5.8 is out now, so let’s bump the minimum required toolchain to Swift 5.6. (The package wants to support three major language releases, and now that 5.8 is out, supporting 5.5 would bump that to four.) --- Package.swift | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index db1c676f..9148ad31 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.5 +// swift-tools-version:5.6 //===----------------------------------------------------------------------===// // // This source file is part of the Swift Collections open source project diff --git a/README.md b/README.md index 8c6d6b87..af72ddff 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ The following table maps existing package releases to their minimum required Swi | Package version | Swift version | Xcode release | | ----------------------- | ------------- | ------------- | | swift-collections 1.0.x | >= Swift 5.3 | >= Xcode 12 | -| swift-collections 1.1.x | >= Swift 5.5 | >= Xcode 13 | +| swift-collections 1.1.x | >= Swift 5.6 | >= Xcode 13.3 | (Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.) From 7f63914a7161923e9af6889ed0f954de1ed4c7f0 Mon Sep 17 00:00:00 2001 From: Ryan McLeod <220240+warpling@users.noreply.github.com> Date: Mon, 19 Dec 2022 14:23:40 +0100 Subject: [PATCH 101/113] [OrderedDictionary] Explicitly mention in documentation that keys/values are ordered (cherry picked from commit fef38395004569688a967b88c70d8774c63f5fc5) --- .../OrderedDictionary/OrderedDictionary.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index 3863521c..c3dc81f8 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -159,7 +159,7 @@ /// original dictionary value.) /// /// The ``values-swift.property`` collection is a mutable random-access -/// collection of the values in the dictionary: +/// ordered collection of the values in the dictionary: /// /// d.values // "two", "one", "zero" /// d.values[2] = "nada" @@ -219,7 +219,7 @@ public struct OrderedDictionary { } extension OrderedDictionary { - /// A read-only collection view for the keys contained in this dictionary, as + /// A read-only ordered collection view for the keys contained in this dictionary, as /// an `OrderedSet`. /// /// - Complexity: O(1) @@ -227,7 +227,7 @@ extension OrderedDictionary { @inline(__always) public var keys: OrderedSet { _keys } - /// A mutable collection view containing the values in this dictionary. + /// A mutable collection view containing the ordered values in this dictionary. /// /// - Complexity: O(1) @inlinable From ac0c075ccc0fe2754a41dd777bb39507e73efe5b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 10 Apr 2023 18:24:33 -0700 Subject: [PATCH 102/113] =?UTF-8?q?[HashCollections]=20Ensure=20`self`=20d?= =?UTF-8?q?oesn=E2=80=99t=20get=20destroyed=20before=20we=E2=80=99re=20don?= =?UTF-8?q?e=20working=20with=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The HashCollections module includes several mutating methods that dereference unmanaged references to internal nodes after the last usage of `self`. Prevent the compiler from destroying `self` before we’re done working within descendants of its tree. --- .../HashTreeCollections/TreeDictionary/TreeDictionary.swift | 3 +++ Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift | 1 + .../TreeSet/TreeSet+SetAlgebra basics.swift | 2 ++ 3 files changed, 6 insertions(+) diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift index 75b16e03..fba483b3 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift @@ -345,6 +345,7 @@ extension TreeDictionary { public mutating func updateValue( _ value: __owned Value, forKey key: Key ) -> Value? { + defer { _fixLifetime(self) } let hash = _Hash(key) let r = _root.updateValue(.top, forKey: key, hash) { $0.initialize(to: (key, value)) @@ -364,6 +365,7 @@ extension TreeDictionary { internal mutating func _updateValue( _ value: __owned Value, forKey key: Key ) -> Bool { + defer { _fixLifetime(self) } let hash = _Hash(key) let r = _root.updateValue(.top, forKey: key, hash) { $0.initialize(to: (key, value)) @@ -470,6 +472,7 @@ extension TreeDictionary { default defaultValue: @autoclosure () -> Value, with body: (inout Value) throws -> R ) rethrows -> R { + defer { _fixLifetime(self) } let hash = _Hash(key) let r = _root.updateValue(.top, forKey: key, hash) { $0.initialize(to: (key, defaultValue())) diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift index 70ac8c69..2450a22a 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift @@ -54,6 +54,7 @@ extension TreeSet { /// - Complexity: O(log(`count`)) if set storage might be shared; O(1) /// otherwise. public mutating func update(_ member: Element, at index: Index) -> Element { + defer { _fixLifetime(self) } precondition(_isValid(index), "Invalid index") precondition(index._path.isOnItem, "Can't get element at endIndex") _invalidateIndices() diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift index e6e58204..78b9a4bc 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift @@ -51,6 +51,7 @@ extension TreeSet: SetAlgebra { public mutating func insert( _ newMember: __owned Element ) -> (inserted: Bool, memberAfterInsert: Element) { + defer { _fixLifetime(self) } let hash = _Hash(newMember) let r = _root.insert(.top, (newMember, ()), hash) if r.inserted { @@ -117,6 +118,7 @@ extension TreeSet: SetAlgebra { @discardableResult @inlinable public mutating func update(with newMember: __owned Element) -> Element? { + defer { _fixLifetime(self) } let hash = _Hash(newMember) let r = _root.updateValue(.top, forKey: newMember, hash) { $0.initialize(to: (newMember, ())) From a8dad62bc9c76f1f455a372c91759e7bb1e92e63 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 10 Apr 2023 18:33:52 -0700 Subject: [PATCH 103/113] Remove obsolete swift(>=5.5)/swift(>=5.6) checks --- Sources/BitCollections/BitArray/BitArray.swift | 4 +--- .../BitSet/BitSet+BidirectionalCollection.swift | 4 +--- Sources/BitCollections/BitSet/BitSet.Counted.swift | 4 +--- Sources/BitCollections/BitSet/BitSet.Index.swift | 4 +--- Sources/BitCollections/BitSet/BitSet.swift | 4 +--- Sources/DequeModule/Deque+Collection.swift | 4 +--- Sources/DequeModule/Deque+Sendable.swift | 4 +--- .../TreeDictionary/TreeDictionary+Codable.swift | 6 +----- .../TreeDictionary/TreeDictionary+Collection.swift | 4 +--- .../TreeDictionary/TreeDictionary+Keys.swift | 6 +----- .../TreeDictionary/TreeDictionary+Sendable.swift | 4 +--- .../TreeDictionary/TreeDictionary+Sequence.swift | 4 +--- .../TreeDictionary/TreeDictionary+Values.swift | 6 +----- .../TreeSet/TreeSet+Collection.swift | 4 +--- .../HashTreeCollections/TreeSet/TreeSet+Sendable.swift | 4 +--- .../HashTreeCollections/TreeSet/TreeSet+Sequence.swift | 4 +--- Sources/HeapModule/Heap.swift | 4 +--- .../OrderedDictionary+Elements.SubSequence.swift | 6 +----- .../OrderedDictionary/OrderedDictionary+Elements.swift | 4 +--- .../OrderedDictionary/OrderedDictionary+Sendable.swift | 4 +--- .../OrderedDictionary/OrderedDictionary+Sequence.swift | 4 +--- .../OrderedDictionary/OrderedDictionary+Values.swift | 4 +--- .../OrderedSet/OrderedSet+SubSequence.swift | 4 +--- .../OrderedSet/OrderedSet+UnorderedView.swift | 4 +--- .../OrderedSet/OrderedSet+UnstableInternals.swift | 4 +--- .../TreeDictionary Tests.swift | 10 +--------- 26 files changed, 26 insertions(+), 92 deletions(-) diff --git a/Sources/BitCollections/BitArray/BitArray.swift b/Sources/BitCollections/BitArray/BitArray.swift index 2c042359..99e26141 100644 --- a/Sources/BitCollections/BitArray/BitArray.swift +++ b/Sources/BitCollections/BitArray/BitArray.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -48,9 +48,7 @@ public struct BitArray { } } -#if swift(>=5.5) extension BitArray: Sendable {} -#endif extension BitArray { @inline(__always) diff --git a/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift b/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift index f910e28d..fdd13a87 100644 --- a/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift +++ b/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -88,9 +88,7 @@ extension BitSet: Sequence { } } -#if swift(>=5.5) extension BitSet.Iterator: Sendable {} -#endif extension BitSet: Collection, BidirectionalCollection { /// A Boolean value indicating whether the collection is empty. diff --git a/Sources/BitCollections/BitSet/BitSet.Counted.swift b/Sources/BitCollections/BitSet/BitSet.Counted.swift index 9acfc731..bcbbf476 100644 --- a/Sources/BitCollections/BitSet/BitSet.Counted.swift +++ b/Sources/BitCollections/BitSet/BitSet.Counted.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 @@ -28,9 +28,7 @@ extension BitSet { } } -#if swift(>=5.5) extension BitSet.Counted: Sendable {} -#endif extension BitSet.Counted { #if COLLECTIONS_INTERNAL_CHECKS diff --git a/Sources/BitCollections/BitSet/BitSet.Index.swift b/Sources/BitCollections/BitSet/BitSet.Index.swift index a0518d30..433dd37d 100644 --- a/Sources/BitCollections/BitSet/BitSet.Index.swift +++ b/Sources/BitCollections/BitSet/BitSet.Index.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -43,9 +43,7 @@ extension BitSet { } } -#if swift(>=5.5) extension BitSet.Index: Sendable {} -#endif extension BitSet.Index: CustomStringConvertible { // A textual representation of this instance. diff --git a/Sources/BitCollections/BitSet/BitSet.swift b/Sources/BitCollections/BitSet/BitSet.swift index 26cf01b0..dfb09742 100644 --- a/Sources/BitCollections/BitSet/BitSet.swift +++ b/Sources/BitCollections/BitSet/BitSet.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -33,9 +33,7 @@ public struct BitSet { } } -#if swift(>=5.5) extension BitSet: Sendable {} -#endif extension BitSet { @inline(__always) diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index 8212a293..6dcdc28e 100644 --- a/Sources/DequeModule/Deque+Collection.swift +++ b/Sources/DequeModule/Deque+Collection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -164,9 +164,7 @@ extension Deque: Sequence { } } -#if swift(>=5.5) extension Deque.Iterator: Sendable where Element: Sendable {} -#endif extension Deque: RandomAccessCollection { public typealias Index = Int diff --git a/Sources/DequeModule/Deque+Sendable.swift b/Sources/DequeModule/Deque+Sendable.swift index 0ebf4bb0..df3fdd54 100644 --- a/Sources/DequeModule/Deque+Sendable.swift +++ b/Sources/DequeModule/Deque+Sendable.swift @@ -2,13 +2,11 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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.5) extension Deque: @unchecked Sendable where Element: Sendable {} -#endif diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Codable.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Codable.swift index 7a9d4246..c929e01a 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Codable.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Codable.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 @@ -60,7 +60,6 @@ where Key: Encodable, Value: Encodable } return } -#if swift(>=5.6) if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *), Key.self is CodingKeyRepresentable.Type { // Since the keys are CodingKeyRepresentable, we can use the `codingKey` @@ -73,7 +72,6 @@ where Key: Encodable, Value: Encodable } return } -#endif // Keys are Encodable but not Strings or Ints, so we cannot arbitrarily // convert to keys. We can encode as an array of alternating key-value // pairs, though. @@ -133,7 +131,6 @@ where Key: Decodable, Value: Decodable return } -#if swift(>=5.6) if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *), let keyType = Key.self as? CodingKeyRepresentable.Type { // The keys are CodingKeyRepresentable, so we should be able to expect @@ -152,7 +149,6 @@ where Key: Decodable, Value: Decodable } return } -#endif // We should have encoded as an array of alternating key-value pairs. var container = try decoder.unkeyedContainer() diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift index 86089e61..a1df0ed0 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 @@ -38,10 +38,8 @@ extension TreeDictionary { } } -#if swift(>=5.5) extension TreeDictionary.Index: @unchecked Sendable where Key: Sendable, Value: Sendable {} -#endif extension TreeDictionary.Index: Equatable { /// Returns a Boolean value indicating whether two index values are equal. diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift index 84fb7001..da2d3a54 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 @@ -38,10 +38,8 @@ extension TreeDictionary { } } -#if swift(>=5.5) extension TreeDictionary.Keys: Sendable where Key: Sendable, Value: Sendable {} -#endif extension TreeDictionary.Keys: _UniqueCollection {} @@ -114,10 +112,8 @@ extension TreeDictionary.Keys: Sequence { } } -#if swift(>=5.5) extension TreeDictionary.Keys.Iterator: Sendable where Key: Sendable, Value: Sendable {} -#endif extension TreeDictionary.Keys: Collection { public typealias Index = TreeDictionary.Index diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sendable.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sendable.swift index 01bdf115..f347d3c6 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sendable.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sendable.swift @@ -2,14 +2,12 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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.5) extension TreeDictionary: @unchecked Sendable where Key: Sendable, Value: Sendable {} -#endif diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift index f504404c..3c86dd01 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2019 - 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2019 - 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 @@ -51,10 +51,8 @@ extension TreeDictionary: Sequence { } } -#if swift(>=5.5) extension TreeDictionary.Iterator: @unchecked Sendable where Key: Sendable, Value: Sendable {} -#endif extension TreeDictionary.Iterator: IteratorProtocol { /// The element type of a dictionary: a tuple containing an individual diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift index 7384ed79..40d4d4a1 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 @@ -43,10 +43,8 @@ extension TreeDictionary { } } -#if swift(>=5.5) extension TreeDictionary.Values: Sendable where Key: Sendable, Value: Sendable {} -#endif extension TreeDictionary.Values: CustomStringConvertible { // A textual representation of this instance. @@ -92,10 +90,8 @@ extension TreeDictionary.Values: Sequence { } } -#if swift(>=5.5) extension TreeDictionary.Values.Iterator: Sendable where Key: Sendable, Value: Sendable {} -#endif // Note: This cannot be a MutableCollection because its subscript setter // needs to invalidate indices. diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift index ad45426a..dde99c0c 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 @@ -38,10 +38,8 @@ extension TreeSet { } } -#if swift(>=5.5) extension TreeSet.Index: @unchecked Sendable where Element: Sendable {} -#endif extension TreeSet.Index: Equatable { /// Returns a Boolean value indicating whether two index values are equal. diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Sendable.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Sendable.swift index b5b758e2..e19e0a1b 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Sendable.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Sendable.swift @@ -2,13 +2,11 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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.5) extension TreeSet: @unchecked Sendable where Element: Sendable {} -#endif diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift index 00e8fe66..43d3ac4a 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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 @@ -49,7 +49,5 @@ extension TreeSet: Sequence { } } -#if swift(>=5.5) extension TreeSet.Iterator: @unchecked Sendable where Element: Sendable {} -#endif diff --git a/Sources/HeapModule/Heap.swift b/Sources/HeapModule/Heap.swift index d63017e1..4e7e60e9 100644 --- a/Sources/HeapModule/Heap.swift +++ b/Sources/HeapModule/Heap.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -35,9 +35,7 @@ public struct Heap { } } -#if swift(>=5.5) extension Heap: Sendable where Element: Sendable {} -#endif extension Heap { /// A Boolean value indicating whether or not the heap is empty. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift index 5f3b7b71..b6c9f16f 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -34,10 +34,8 @@ extension OrderedDictionary.Elements { } } -#if swift(>=5.5) extension OrderedDictionary.Elements.SubSequence: Sendable where Key: Sendable, Value: Sendable {} -#endif extension OrderedDictionary.Elements.SubSequence: CustomStringConvertible { // A textual representation of this instance. @@ -149,10 +147,8 @@ extension OrderedDictionary.Elements.SubSequence: Sequence { } } -#if swift(>=5.5) extension OrderedDictionary.Elements.SubSequence.Iterator: Sendable where Key: Sendable, Value: Sendable {} -#endif extension OrderedDictionary.Elements.SubSequence: RandomAccessCollection { /// The index type for an ordered dictionary: `Int`. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index 403d01b2..66cd9926 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -29,10 +29,8 @@ extension OrderedDictionary { } } -#if swift(>=5.5) extension OrderedDictionary.Elements: Sendable where Key: Sendable, Value: Sendable {} -#endif extension OrderedDictionary { /// A view of the contents of this dictionary as a random-access collection. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Sendable.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Sendable.swift index 539a4fe1..b8ce4670 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Sendable.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Sendable.swift @@ -2,14 +2,12 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2022 - 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.5) extension OrderedDictionary: @unchecked Sendable where Key: Sendable, Value: Sendable {} -#endif diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Sequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Sequence.swift index 21967d9e..4d516ed5 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Sequence.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Sequence.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -62,7 +62,5 @@ extension OrderedDictionary: Sequence { } } -#if swift(>=5.5) extension OrderedDictionary.Iterator: Sendable where Key: Sendable, Value: Sendable {} -#endif diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift index 1bafecee..6796917f 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -28,10 +28,8 @@ extension OrderedDictionary { } } -#if swift(>=5.5) extension OrderedDictionary.Values: Sendable where Key: Sendable, Value: Sendable {} -#endif extension OrderedDictionary.Values: CustomStringConvertible { // A textual representation of this instance. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift index 51079bfb..017a0d22 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -37,9 +37,7 @@ extension OrderedSet { } } -#if swift(>=5.5) extension OrderedSet.SubSequence: Sendable where Element: Sendable {} -#endif extension OrderedSet.SubSequence { @inlinable diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift index 783840f3..8efa76d0 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -66,9 +66,7 @@ extension OrderedSet { } } -#if swift(>=5.5) extension OrderedSet.UnorderedView: Sendable where Element: Sendable {} -#endif extension OrderedSet.UnorderedView: CustomStringConvertible { /// A textual representation of this instance. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnstableInternals.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnstableInternals.swift index 3c94ed43..effc6ec0 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnstableInternals.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnstableInternals.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -47,7 +47,5 @@ extension OrderedSet { } } -#if swift(>=5.5) extension OrderedSet._UnstableInternals: Sendable where Element: Sendable {} -#endif diff --git a/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift b/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift index aae5e315..c38fcfc7 100644 --- a/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift +++ b/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 - 2022 Apple Inc. and the Swift project authors +// Copyright (c) 2021 - 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 @@ -274,7 +274,6 @@ class TreeDictionaryTests: CollectionTestCase { d, expectedContents: ref, by: ==) } -#if swift(>=5.6) @available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) struct FancyDictionaryKey: CodingKeyRepresentable, Hashable, Codable { var value: Int @@ -290,7 +289,6 @@ class TreeDictionaryTests: CollectionTestCase { self.init(value) } } -#endif struct BoringDictionaryKey: Hashable, Codable { var value: Int @@ -316,7 +314,6 @@ class TreeDictionaryTests: CollectionTestCase { ]) expectEqual(try MinimalEncoder.encode(d2), v2) -#if swift(>=5.6) if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) { let d3: TreeDictionary = [ FancyDictionaryKey(1): 10, FancyDictionaryKey(2): 20 @@ -326,7 +323,6 @@ class TreeDictionaryTests: CollectionTestCase { ]) expectEqual(try MinimalEncoder.encode(d3), v3) } -#endif let d4: TreeDictionary = [ // Note: we only have a single element to prevent ordering @@ -362,7 +358,6 @@ class TreeDictionaryTests: CollectionTestCase { try MinimalDecoder.decode(v2, as: PD.self), d2) -#if swift(>=5.6) if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) { let d3: TreeDictionary = [ FancyDictionaryKey(1): 10, FancyDictionaryKey(2): 20 @@ -374,7 +369,6 @@ class TreeDictionaryTests: CollectionTestCase { try MinimalDecoder.decode(v3, as: PD.self), d3) } -#endif let d4: TreeDictionary = [ // Note: we only have a single element to prevent ordering @@ -396,7 +390,6 @@ class TreeDictionaryTests: CollectionTestCase { expectTrue($0 is DecodingError) } -#if swift(>=5.6) if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) { let v6: MinimalEncoder.Value = .dictionary([ "This is not a number": .string("bus"), @@ -419,7 +412,6 @@ class TreeDictionaryTests: CollectionTestCase { try MinimalDecoder.decode(v7, as: PD.self), d7) } -#endif let v8: MinimalEncoder.Value = .array([ .int32(1), .string("bike"), .int32(2), From 99adbe97af48017fb51d884936f6bb87c27166c2 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 10 Apr 2023 19:12:03 -0700 Subject: [PATCH 104/113] [Xcode] Update Xcode project MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Update to Xcode 14.3 - Update source filelists - Remove DEFINES_MODULE and related settings — this package does not define a clang module. --- Xcode/Collections.xcconfig | 5 -- Xcode/Collections.xcodeproj/project.pbxproj | 34 +++++--- .../xcschemes/Collections.xcscheme | 84 +++++++++++++++++++ Xcode/Collections.xctestplan | 25 ++++++ 4 files changed, 131 insertions(+), 17 deletions(-) create mode 100644 Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme create mode 100644 Xcode/Collections.xctestplan diff --git a/Xcode/Collections.xcconfig b/Xcode/Collections.xcconfig index ff0af9bc..13193a67 100644 --- a/Xcode/Collections.xcconfig +++ b/Xcode/Collections.xcconfig @@ -39,8 +39,3 @@ ENABLE_TESTABILITY[config=Debug] = YES GENERATE_INFOPLIST_FILE = YES CODE_SIGN_STYLE = Automatic - -DEFINES_MODULE = YES -ENABLE_MODULE_VERIFIER = YES -MODULE_VERIFIER_SUPPORTED_LANGUAGES = objective-c objective-c++ -MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = gnu11 gnu++20 diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index ecde4df9..adec5dde 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -7,6 +7,11 @@ objects = { /* Begin PBXBuildFile section */ + 7D9B859729E4F74400B291CD /* BitArray+Shifts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */; }; + 7D9B859829E4F74400B291CD /* BitArray+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859229E4F74400B291CD /* BitArray+Descriptions.swift */; }; + 7D9B859929E4F74400B291CD /* BitArray+LosslessStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */; }; + 7D9B859A29E4F74400B291CD /* BitArray+RandomBits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859429E4F74400B291CD /* BitArray+RandomBits.swift */; }; + 7D9B859B29E4F74400B291CD /* BitArray+ExpressibleByStringLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859529E4F74400B291CD /* BitArray+ExpressibleByStringLiteral.swift */; }; 7DE91B2F29CA6721004483EB /* Collections.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7DE91B2629CA6721004483EB /* Collections.framework */; }; 7DE9200D29CA70F3004483EB /* OrderedDictionary+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7529CA70F3004483EB /* OrderedDictionary+Equatable.swift */; }; 7DE9200E29CA70F3004483EB /* OrderedDictionary+ExpressibleByDictionaryLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7629CA70F3004483EB /* OrderedDictionary+ExpressibleByDictionaryLiteral.swift */; }; @@ -201,7 +206,6 @@ 7DE920E029CA70F4004483EB /* Range+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F5F29CA70F3004483EB /* Range+Utilities.swift */; }; 7DE920E129CA70F4004483EB /* UInt+Tricks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6029CA70F3004483EB /* UInt+Tricks.swift */; }; 7DE920E229CA70F4004483EB /* _Word.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6129CA70F3004483EB /* _Word.swift */; }; - 7DE920E529CA70F4004483EB /* BitArray+CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6529CA70F3004483EB /* BitArray+CustomStringConvertible.swift */; }; 7DE920E629CA70F4004483EB /* BitArray+ChunkedBitsIterators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6629CA70F3004483EB /* BitArray+ChunkedBitsIterators.swift */; }; 7DE920E729CA70F4004483EB /* BitArray+CustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6729CA70F3004483EB /* BitArray+CustomReflectable.swift */; }; 7DE920E829CA70F4004483EB /* BitArray+BitwiseOperations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F6829CA70F3004483EB /* BitArray+BitwiseOperations.swift */; }; @@ -217,9 +221,7 @@ 7DE920F229CA70F4004483EB /* BitArray._UnsafeHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7229CA70F3004483EB /* BitArray._UnsafeHandle.swift */; }; 7DE920F329CA70F4004483EB /* BitArray+Copy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7329CA70F3004483EB /* BitArray+Copy.swift */; }; 7DE920F429CA70F4004483EB /* BitArray+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7429CA70F3004483EB /* BitArray+Hashable.swift */; }; - 7DE920F529CA70F4004483EB /* BitArray+CustomDebugStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7529CA70F3004483EB /* BitArray+CustomDebugStringConvertible.swift */; }; 7DE920F629CA70F4004483EB /* BitArray+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7629CA70F3004483EB /* BitArray+Equatable.swift */; }; - 7DE920F729CA70F4004483EB /* BitArray+Random.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7729CA70F3004483EB /* BitArray+Random.swift */; }; 7DE920F829CA70F4004483EB /* BitArray+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91F7829CA70F3004483EB /* BitArray+Testing.swift */; }; 7DE9212329CA70F4004483EB /* TreeSet+SetAlgebra isEqualSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FAB29CA70F3004483EB /* TreeSet+SetAlgebra isEqualSet.swift */; }; 7DE9212429CA70F4004483EB /* TreeSet+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FAC29CA70F3004483EB /* TreeSet+Descriptions.swift */; }; @@ -440,6 +442,12 @@ 7D5A64D629CCEF1500CB2595 /* gyb */ = {isa = PBXFileReference; lastKnownFileType = text; path = gyb; sourceTree = ""; }; 7D5A64D729CCEF1500CB2595 /* gyb.py */ = {isa = PBXFileReference; lastKnownFileType = text.script.python; path = gyb.py; sourceTree = ""; }; 7D5A64D829CCF0FE00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; + 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Shifts.swift"; sourceTree = ""; }; + 7D9B859229E4F74400B291CD /* BitArray+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Descriptions.swift"; sourceTree = ""; }; + 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+LosslessStringConvertible.swift"; sourceTree = ""; }; + 7D9B859429E4F74400B291CD /* BitArray+RandomBits.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+RandomBits.swift"; sourceTree = ""; }; + 7D9B859529E4F74400B291CD /* BitArray+ExpressibleByStringLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+ExpressibleByStringLiteral.swift"; sourceTree = ""; }; + 7D9B859C29E4F77D00B291CD /* Collections.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = Collections.xctestplan; sourceTree = ""; }; 7DE91B2629CA6721004483EB /* Collections.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Collections.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 7DE91B2E29CA6721004483EB /* CollectionsTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CollectionsTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 7DE91E7229CA70F3004483EB /* OrderedCollections.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = OrderedCollections.docc; sourceTree = ""; }; @@ -643,7 +651,6 @@ 7DE91F6029CA70F3004483EB /* UInt+Tricks.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UInt+Tricks.swift"; sourceTree = ""; }; 7DE91F6129CA70F3004483EB /* _Word.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _Word.swift; sourceTree = ""; }; 7DE91F6229CA70F3004483EB /* BitCollections.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = BitCollections.docc; sourceTree = ""; }; - 7DE91F6529CA70F3004483EB /* BitArray+CustomStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+CustomStringConvertible.swift"; sourceTree = ""; }; 7DE91F6629CA70F3004483EB /* BitArray+ChunkedBitsIterators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+ChunkedBitsIterators.swift"; sourceTree = ""; }; 7DE91F6729CA70F3004483EB /* BitArray+CustomReflectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+CustomReflectable.swift"; sourceTree = ""; }; 7DE91F6829CA70F3004483EB /* BitArray+BitwiseOperations.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+BitwiseOperations.swift"; sourceTree = ""; }; @@ -659,9 +666,7 @@ 7DE91F7229CA70F3004483EB /* BitArray._UnsafeHandle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitArray._UnsafeHandle.swift; sourceTree = ""; }; 7DE91F7329CA70F3004483EB /* BitArray+Copy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Copy.swift"; sourceTree = ""; }; 7DE91F7429CA70F3004483EB /* BitArray+Hashable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Hashable.swift"; sourceTree = ""; }; - 7DE91F7529CA70F3004483EB /* BitArray+CustomDebugStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+CustomDebugStringConvertible.swift"; sourceTree = ""; }; 7DE91F7629CA70F3004483EB /* BitArray+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Equatable.swift"; sourceTree = ""; }; - 7DE91F7729CA70F3004483EB /* BitArray+Random.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Random.swift"; sourceTree = ""; }; 7DE91F7829CA70F3004483EB /* BitArray+Testing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Testing.swift"; sourceTree = ""; }; 7DE91F7A29CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; 7DE91F7B29CA70F3004483EB /* Collections.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Collections.swift; sourceTree = ""; }; @@ -1336,18 +1341,20 @@ 7DE91F6F29CA70F3004483EB /* BitArray+Codable.swift */, 7DE91F6C29CA70F3004483EB /* BitArray+Collection.swift */, 7DE91F7329CA70F3004483EB /* BitArray+Copy.swift */, - 7DE91F7529CA70F3004483EB /* BitArray+CustomDebugStringConvertible.swift */, 7DE91F6729CA70F3004483EB /* BitArray+CustomReflectable.swift */, - 7DE91F6529CA70F3004483EB /* BitArray+CustomStringConvertible.swift */, + 7D9B859229E4F74400B291CD /* BitArray+Descriptions.swift */, 7DE91F7629CA70F3004483EB /* BitArray+Equatable.swift */, 7DE91F6E29CA70F3004483EB /* BitArray+ExpressibleByArrayLiteral.swift */, + 7D9B859529E4F74400B291CD /* BitArray+ExpressibleByStringLiteral.swift */, 7DE91F6D29CA70F3004483EB /* BitArray+Extras.swift */, 7DE91F6B29CA70F3004483EB /* BitArray+Fill.swift */, 7DE91F7429CA70F3004483EB /* BitArray+Hashable.swift */, 7DE91F7129CA70F3004483EB /* BitArray+Initializers.swift */, 7DE91F6929CA70F3004483EB /* BitArray+Invariants.swift */, - 7DE91F7729CA70F3004483EB /* BitArray+Random.swift */, + 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */, + 7D9B859429E4F74400B291CD /* BitArray+RandomBits.swift */, 7DE91F7029CA70F3004483EB /* BitArray+RangeReplaceableCollection.swift */, + 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */, 7DE91F7829CA70F3004483EB /* BitArray+Testing.swift */, ); path = BitArray; @@ -1800,6 +1807,7 @@ 7DEBDB9829CCE4A600ADC226 /* Shared.xcconfig */, 7DEBDB9929CCE4A600ADC226 /* Collections.xcconfig */, 7DEBDB9729CCE4A600ADC226 /* CollectionsTests.xcconfig */, + 7D9B859C29E4F77D00B291CD /* Collections.xctestplan */, 7D5A64D229CCE8CC00CB2595 /* README.md */, ); name = Xcode; @@ -1962,6 +1970,7 @@ 7DE9201129CA70F3004483EB /* OrderedDictionary+Initializers.swift in Sources */, 7DE9212B29CA70F4004483EB /* TreeSet+SetAlgebra subtracting.swift in Sources */, 7DE920F629CA70F4004483EB /* BitArray+Equatable.swift in Sources */, + 7D9B859829E4F74400B291CD /* BitArray+Descriptions.swift in Sources */, 7DE9212329CA70F4004483EB /* TreeSet+SetAlgebra isEqualSet.swift in Sources */, 7DE9214629CA70F4004483EB /* _HashSlot.swift in Sources */, 7DEBDB0129CBEE5300ADC226 /* _UnsafeBitSet+Index.swift in Sources */, @@ -2030,7 +2039,6 @@ 7DE9207D29CA70F4004483EB /* BigSubstring+UTF16View.swift in Sources */, 7DEBDAF829CBEE5300ADC226 /* UnsafeMutableBufferPointer+Extras.swift in Sources */, 7DE9217229CA70F4004483EB /* TreeDictionary+Sendable.swift in Sources */, - 7DE920F529CA70F4004483EB /* BitArray+CustomDebugStringConvertible.swift in Sources */, 7DE9207729CA70F4004483EB /* Range+BigString.swift in Sources */, 7DE9204B29CA70F3004483EB /* _DequeBuffer.swift in Sources */, 7DE920DF29CA70F4004483EB /* Slice+Utilities.swift in Sources */, @@ -2042,6 +2050,7 @@ 7DE9201429CA70F3004483EB /* OrderedDictionary+Sequence.swift in Sources */, 7DE920DB29CA70F4004483EB /* BitSet+Hashable.swift in Sources */, 7DE9208C29CA70F4004483EB /* _RopeItem.swift in Sources */, + 7D9B859A29E4F74400B291CD /* BitArray+RandomBits.swift in Sources */, 7DEBDB0929CBEE5300ADC226 /* Integer rank.swift in Sources */, 7DE920EC29CA70F4004483EB /* BitArray+Collection.swift in Sources */, 7DE9201729CA70F3004483EB /* OrderedDictionary+Codable.swift in Sources */, @@ -2050,6 +2059,7 @@ 7DE9213329CA70F4004483EB /* TreeSet+Collection.swift in Sources */, 7DE9217929CA70F4004483EB /* Heap+UnsafeHandle.swift in Sources */, 7DE920BC29CA70F4004483EB /* _UniqueCollection.swift in Sources */, + 7D9B859B29E4F74400B291CD /* BitArray+ExpressibleByStringLiteral.swift in Sources */, 7DE9216529CA70F4004483EB /* _HashNode+Structural intersection.swift in Sources */, 7DEBDAF329CBEE5300ADC226 /* Array+WithContiguousStorage Compatibility.swift in Sources */, 7DE920A629CA70F4004483EB /* String Utilities.swift in Sources */, @@ -2145,13 +2155,14 @@ 7DE920A829CA70F4004483EB /* String.Index+ABI.swift in Sources */, 7DE9204F29CA70F3004483EB /* Deque.swift in Sources */, 7DE9214129CA70F4004483EB /* _HashNode+Initializers.swift in Sources */, + 7D9B859929E4F74400B291CD /* BitArray+LosslessStringConvertible.swift in Sources */, 7DE9202D29CA70F3004483EB /* OrderedSet.swift in Sources */, 7DEBDB0329CBEE5300ADC226 /* _UnsafeBitSet+_Word.swift in Sources */, 7DE9216329CA70F4004483EB /* _HashLevel.swift in Sources */, + 7D9B859729E4F74400B291CD /* BitArray+Shifts.swift in Sources */, 7DE9216C29CA70F4004483EB /* TreeDictionary+Descriptions.swift in Sources */, 7DE9205429CA70F3004483EB /* Deque+Sendable.swift in Sources */, 7DE920A229CA70F4004483EB /* Rope+RemoveSubrange.swift in Sources */, - 7DE920E529CA70F4004483EB /* BitArray+CustomStringConvertible.swift in Sources */, 7DE920C729CA70F4004483EB /* BitSet+ExpressibleByArrayLiteral.swift in Sources */, 7DE9214929CA70F4004483EB /* _HashNode+Structural isEqualSet.swift in Sources */, 7DE9206729CA70F4004483EB /* BigString+Builder.swift in Sources */, @@ -2224,7 +2235,6 @@ 7DE9206C29CA70F4004483EB /* BigString+Chunk.swift in Sources */, 7DE920F329CA70F4004483EB /* BitArray+Copy.swift in Sources */, 7DE9214029CA70F4004483EB /* _Hash.swift in Sources */, - 7DE920F729CA70F4004483EB /* BitArray+Random.swift in Sources */, 7DE9205629CA70F3004483EB /* Deque+Testing.swift in Sources */, 7DEBDB0829CBEE5300ADC226 /* UInt+reversed.swift in Sources */, 7DE9209329CA70F4004483EB /* Rope+Invariants.swift in Sources */, diff --git a/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme b/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme new file mode 100644 index 00000000..2c3287f6 --- /dev/null +++ b/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Xcode/Collections.xctestplan b/Xcode/Collections.xctestplan new file mode 100644 index 00000000..446f3f5d --- /dev/null +++ b/Xcode/Collections.xctestplan @@ -0,0 +1,25 @@ +{ + "configurations" : [ + { + "id" : "18C3508F-98DB-45BE-9CFC-5159D79BA600", + "name" : "Test Scheme Action", + "options" : { + + } + } + ], + "defaultOptions" : { + + }, + "testTargets" : [ + { + "parallelizable" : true, + "target" : { + "containerPath" : "container:Collections.xcodeproj", + "identifier" : "7DE91B2D29CA6721004483EB", + "name" : "CollectionsTests" + } + } + ], + "version" : 1 +} From 4afdfe4da269e1c57428c173e49c48228aeb382f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 12 Apr 2023 17:52:19 -0700 Subject: [PATCH 105/113] [Rope] Flesh out docs a little bit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rope remains woefully undocumented, and I suspect its abstraction level isn’t right for general use, but let’s see if writing up some documentation for it will make it a bit more accessible. --- .../RopeModule/Rope/Basics/RopeElement.swift | 39 ++++++++++++++++++- .../RopeModule/Rope/Basics/RopeMetric.swift | 9 +++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/Sources/RopeModule/Rope/Basics/RopeElement.swift b/Sources/RopeModule/Rope/Basics/RopeElement.swift index de4bf99a..1bfb0d84 100644 --- a/Sources/RopeModule/Rope/Basics/RopeElement.swift +++ b/Sources/RopeModule/Rope/Basics/RopeElement.swift @@ -9,10 +9,27 @@ // //===----------------------------------------------------------------------===// -/// The element type of an augmented tree. +/// The element type of a rope. Rope elements are expected to be container types +/// of their own, with logical positions within them addressed by an `Index` +/// type, similar to `Collection` indices. +/// +/// However, rope elements aren't required conform to `Collection`. In fact, +/// they often support multiple different ways to interpret/project their +/// contents, similar to `String`'s views. In some cases, they may just be +/// individual, undivisable items of varying sizes -- although it's usually +/// a better to use a simple fixed-size collection type instead. +/// +/// Each such projection may come with a different idea for how large a rope +/// element is -- this is modeled by the `RopeSummary` and `RopeMetric` +/// protocols. The `summary` property returns the size of the element as an +/// additive value, which can be projected to integer sizes using one of the +/// associated rope metrics. public protocol RopeElement { /// The commutative group that is used to augment the tree. associatedtype Summary: RopeSummary + + /// A type whose values address a particular pieces of content in this rope + /// element. associatedtype Index: Comparable /// Returns the summary of `self`. @@ -24,8 +41,28 @@ public protocol RopeElement { /// Check the consistency of `self`. func invariantCheck() + /// Rebalance contents between `self` and its next neighbor `right`, + /// eliminating an `isUndersized` condition on one of the inputs, if possible. + /// + /// On return, `self` is expected to be non-empty and well-sized. + /// + /// - Parameter right: The element immediately following `self` in some rope. + /// - Precondition: Either `self` or `right` must be undersized. + /// - Returns: A boolean value indicating whether `right` has become empty. mutating func rebalance(nextNeighbor right: inout Self) -> Bool + + /// Rebalance contents between `self` and its previous neighbor `left`, + /// eliminating an `isUndersized` condition on one of the inputs, if possible. + /// + /// On return, `self` is expected to be non-empty and well-sized. + /// + /// - Parameter left: The element immediately preceding `self` in some rope. + /// - Precondition: Either `left` or `self` must be undersized. + /// - Returns: A boolean value indicating whether `left` has become empty. mutating func rebalance(prevNeighbor left: inout Self) -> Bool + + /// Split `self` into two pieces at the specified index, keeping contents + /// up to `index` in `self`, and moving the rest of it into a new item. mutating func split(at index: Index) -> Self } diff --git a/Sources/RopeModule/Rope/Basics/RopeMetric.swift b/Sources/RopeModule/Rope/Basics/RopeMetric.swift index 37711b64..d6b05269 100644 --- a/Sources/RopeModule/Rope/Basics/RopeMetric.swift +++ b/Sources/RopeModule/Rope/Basics/RopeMetric.swift @@ -12,7 +12,16 @@ public protocol RopeMetric: Sendable { associatedtype Element: RopeElement + /// Returns the size of a summarized rope element in this metric. func size(of summary: Element.Summary) -> Int + + /// Returns an index addressing the content at the given offset from + /// the start of the specified rope element. + /// + /// - Parameter offset: An integer offset from the start of `element` in this + /// metric, not exceeding `size(of: element.summary)`. + /// - Parameter element: An arbitary rope element. + /// - Returns: The index addressing the desired position in the input element. func index(at offset: Int, in element: Element) -> Element.Index } From bc21b90ff19d1b3d2a6c3145d5c8156d43ff8ee9 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 12 Apr 2023 17:53:04 -0700 Subject: [PATCH 106/113] [Rope] Minor usability fixes and API additions --- Sources/RopeModule/Rope/Basics/RopeSummary.swift | 5 +++++ Sources/RopeModule/Rope/Conformances/Rope+Collection.swift | 2 ++ Sources/RopeModule/Rope/Operations/Rope+Extract.swift | 5 +++++ Sources/RopeModule/Rope/Operations/Rope+Remove.swift | 1 + 4 files changed, 13 insertions(+) diff --git a/Sources/RopeModule/Rope/Basics/RopeSummary.swift b/Sources/RopeModule/Rope/Basics/RopeSummary.swift index 8afabccb..bbad6fc5 100644 --- a/Sources/RopeModule/Rope/Basics/RopeSummary.swift +++ b/Sources/RopeModule/Rope/Basics/RopeSummary.swift @@ -36,6 +36,11 @@ public protocol RopeSummary: Equatable, Sendable { } extension RopeSummary { + @inlinable @inline(__always) + public static var nodeSizeBitWidth: Int { + Int.bitWidth - maxNodeSize.leadingZeroBitCount + } + @inlinable @inline(__always) public static var minNodeSize: Int { (maxNodeSize + 1) / 2 } } diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift index 8fe4aeb7..c9784f54 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift @@ -56,6 +56,8 @@ extension Rope { } extension Rope: BidirectionalCollection { + public typealias SubSequence = Slice + @inlinable public var isEmpty: Bool { guard _root != nil else { return true } diff --git a/Sources/RopeModule/Rope/Operations/Rope+Extract.swift b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift index 2883af2f..7749b3cf 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Extract.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift @@ -10,6 +10,11 @@ //===----------------------------------------------------------------------===// extension Rope { + @inlinable + public func extract(_ offsetRange: Range, in metric: some RopeMetric) -> Self { + extract(from: offsetRange.lowerBound, to: offsetRange.upperBound, in: metric) + } + @inlinable public func extract(from start: Int, to end: Int, in metric: some RopeMetric) -> Self { if _root == nil { diff --git a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift index 8f4d07e8..0e6caf0a 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift @@ -11,6 +11,7 @@ extension Rope { @inlinable + @discardableResult public mutating func remove(at index: Index) -> Element { validate(index) let old = root.remove(at: index._path).removed From cead2b3d647346672065b4f29ef440029f37b9a9 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 12 Apr 2023 17:54:13 -0700 Subject: [PATCH 107/113] [Rope] index(_:offsetBy:in:preferEnd:) fix result tuple labeling This renames `remainder` to `remaining`, restoring API consistency. --- Sources/RopeModule/Rope/Conformances/Rope+Collection.swift | 2 +- Tests/RopeModuleTests/TestRope.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift index c9784f54..0c73fa01 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift @@ -345,7 +345,7 @@ extension Rope { offsetBy distance: Int, in metric: some RopeMetric, preferEnd: Bool - ) -> (index: Index, remainder: Int) { + ) -> (index: Index, remaining: Int) { var i = i var distance = distance formIndex(&i, offsetBy: &distance, in: metric, preferEnd: preferEnd) diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index 471b2944..6e5203d8 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -253,7 +253,7 @@ class TestRope: XCTestCase { : ref[j.. Date: Wed, 12 Apr 2023 17:55:19 -0700 Subject: [PATCH 108/113] [Rope] update(at:by:): Invalidate indices MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Calling this function is supposed to invalidate all indices other than the input index — so let’s do that. --- Sources/RopeModule/Rope/Conformances/Rope+Collection.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift index 0c73fa01..44ab25ab 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift @@ -154,6 +154,8 @@ extension Rope { validate(index) var state = root._prepareModify(at: index._path) defer { + _invalidateIndices() + index._version = self._version index._leaf = root._finalizeModify(&state).leaf } return body(&state.item.value) From 3fa52c48de6955a9334e3ebb5b0f84827b228d20 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 13 Apr 2023 19:36:09 -0700 Subject: [PATCH 109/113] [Rope] Add remove(at:), remove(at:in:) variants that preserve the position --- .../RopeModule/Rope/Basics/_RopePath.swift | 9 + .../Rope/Operations/Rope+Remove.swift | 154 +++++++++++++----- Tests/RopeModuleTests/TestRope.swift | 35 +++- 3 files changed, 157 insertions(+), 41 deletions(-) diff --git a/Sources/RopeModule/Rope/Basics/_RopePath.swift b/Sources/RopeModule/Rope/Basics/_RopePath.swift index fc0fe552..492db787 100644 --- a/Sources/RopeModule/Rope/Basics/_RopePath.swift +++ b/Sources/RopeModule/Rope/Basics/_RopePath.swift @@ -77,6 +77,15 @@ extension _RopePath { UInt8(truncatingIfNeeded: _value) } + @inlinable + internal mutating func popRoot() { + let heightMask: UInt64 = 255 + let h = height + assert(h > 0 && self[h] == 0) + _value &= ~heightMask + _value |= UInt64(truncatingIfNeeded: h - 1) & heightMask + } + @inlinable internal subscript(height: UInt8) -> Int { get { diff --git a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift index 0e6caf0a..8b6f4453 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift @@ -13,120 +13,198 @@ extension Rope { @inlinable @discardableResult public mutating func remove(at index: Index) -> Element { + _remove(at: index).removed + } + + /// Remove the element at the specified index, and update `index` to address the subsequent + /// element in the new collection. (Or the `endIndex` if it originally addressed the last item.) + @inlinable + @discardableResult + public mutating func remove(at index: inout Index) -> Element { + let (old, path) = _remove(at: index) + index = Index(version: _version, path: path, leaf: _unmanagedLeaf(at: path)) + return old + } + + @inlinable + @discardableResult + internal mutating func _remove(at index: Index) -> (removed: Element, path: _Path) { validate(index) - let old = root.remove(at: index._path).removed + var path = index._path + let r = root.remove(at: &path) if root.isEmpty { _root = nil + assert(r.pathIsAtEnd) } else if root.childCount == 1, root.height > 0 { root = root.readInner { $0.children.first! } + path.popRoot() } _invalidateIndices() - return old.value + return (r.removed.value, r.pathIsAtEnd ? _endPath : path) } } extension Rope._Node { @inlinable internal mutating func remove( - at path: _Path - ) -> (removed: _Item, delta: Summary, needsFixing: Bool) { + at path: inout _Path + ) -> (removed: _Item, delta: Summary, needsFixing: Bool, pathIsAtEnd: Bool) { ensureUnique() - let slot = path[height] + let h = height + let slot = path[h] precondition(slot < childCount, "Invalid index") - guard height > 0 else { + guard h > 0 else { let r = _removeItem(at: slot) - return (r.removed, r.delta, self.isUndersized) + return (r.removed, r.delta, self.isUndersized, slot == childCount) } - let r = updateInner { $0.mutableChildren[slot].remove(at: path) } + let r = updateInner { $0.mutableChildren[slot].remove(at: &path) } self.summary.subtract(r.delta) + var isAtEnd = r.pathIsAtEnd if r.needsFixing { - fixDeficiency(at: slot) + let prepended = fixDeficiency(on: &path) + isAtEnd = isAtEnd && prepended } - return (r.removed, r.delta, self.isUndersized) + if isAtEnd { + path[h] += 1 + path.clear(below: h) + isAtEnd = path[h] == childCount + } + return (r.removed, r.delta, self.isUndersized, isAtEnd) } } extension Rope { @inlinable + @discardableResult public mutating func remove( at position: Int, in metric: some RopeMetric - ) -> Element { + ) -> (removed: Element, next: Index) { _invalidateIndices() - let old = root.remove(at: position, in: metric).removed + var path = _Path(height: self._height) + let r = root.remove(at: position, in: metric, initializing: &path) if root.isEmpty { _root = nil } else if root.childCount == 1, root.height > 0 { root = root.readInner { $0.children.first! } } - return old.value + if r.pathIsAtEnd { + return (r.removed.value, endIndex) + } + let i = Index(version: _version, path: path, leaf: nil) + return (r.removed.value, i) } } extension Rope._Node { + /// Note: `self` may be left undersized after calling this function, which + /// is expected to be resolved by the caller. This is indicated by the `needsFixing` component + /// in the return value. + /// + /// - Returns: A tuple `(removed, delta, needsFixing, pathIsAtEnd)`, where + /// `removed` is the element that got removed, + /// `delta` is its summary, + /// `needsFixing` indicates whether the node was left undersized, and + /// `pathIsAtEnd` indicates if `path` now addresses the end of the node's subtree. @inlinable internal mutating func remove( at position: Int, - in metric: some RopeMetric - ) -> (removed: _Item, delta: Summary, needsFixing: Bool) { + in metric: some RopeMetric, + initializing path: inout _Path + ) -> (removed: _Item, delta: Summary, needsFixing: Bool, pathIsAtEnd: Bool) { ensureUnique() - guard height > 0 else { + let h = height + guard h > 0 else { let (slot, remaining) = readLeaf { $0.findSlot(at: position, in: metric, preferEnd: false) } precondition(remaining == 0, "Element to be removed doesn't fall on an element boundary") + path[h] = slot let r = _removeItem(at: slot) - return (r.removed, r.delta, self.isUndersized) + return (r.removed, r.delta, self.isUndersized, slot == childCount) } - let (slot, r) = updateInner { + let r = updateInner { let (slot, remaining) = $0.findSlot(at: position, in: metric, preferEnd: false) - return (slot, $0.mutableChildren[slot].remove(at: remaining, in: metric)) + path[h] = slot + return $0.mutableChildren[slot].remove(at: remaining, in: metric, initializing: &path) } self.summary.subtract(r.delta) + var isAtEnd = r.pathIsAtEnd if r.needsFixing { - fixDeficiency(at: slot) + let prepended = fixDeficiency(on: &path) + isAtEnd = isAtEnd && prepended } - return (r.removed, r.delta, self.isUndersized) + if isAtEnd { + path[h] += 1 + path.clear(below: h) + isAtEnd = path[h] == childCount + } + return (r.removed, r.delta, self.isUndersized, isAtEnd) } } extension Rope._Node { + /// Returns: `true` if new items got prepended to the child addressed by `path`. + /// `false` if new items got appended. @inlinable - internal mutating func fixDeficiency(at slot: Int) { + @discardableResult + internal mutating func fixDeficiency(on path: inout _Path) -> Bool { assert(isUnique()) - updateInner { + return updateInner { let c = $0.mutableChildren + let h = $0.height + let slot = path[h] assert(c[slot].isUndersized) - guard c.count > 1 else { return } + guard c.count > 1 else { return true } let prev = slot - 1 - let prevSum = prev >= 0 ? c[prev].childCount + c[slot].childCount : 0 - if prev >= 0, prevSum <= Summary.maxNodeSize { - Self.redistributeChildren(&c[prev], &c[slot], to: prevSum) - assert(c[slot].isEmpty) - _ = $0._removeChild(at: slot) - return + let prevSum: Int + if prev >= 0 { + let prevCount = c[prev].childCount + prevSum = prevCount + c[slot].childCount + if prevSum <= Summary.maxNodeSize { + Self.redistributeChildren(&c[prev], &c[slot], to: prevSum) + assert(c[slot].isEmpty) + _ = $0._removeChild(at: slot) + path[h] = prev + path[h - 1] += prevCount + return true + } + } else { + prevSum = 0 } - + let next = slot + 1 - let nextSum = next < c.count ? c[slot].childCount + c[next].childCount : 0 - if next < c.count, nextSum <= Summary.maxNodeSize { - Self.redistributeChildren(&c[slot], &c[next], to: nextSum) - assert(c[next].isEmpty) - _ = $0._removeChild(at: next) - return + let nextSum: Int + if next < c.count { + let nextCount = c[next].childCount + nextSum = c[slot].childCount + nextCount + if nextSum <= Summary.maxNodeSize { + Self.redistributeChildren(&c[slot], &c[next], to: nextSum) + assert(c[next].isEmpty) + _ = $0._removeChild(at: next) + // `path` doesn't need updating. + return false + } + } else { + nextSum = 0 } + if prev >= 0 { assert(c[prev].childCount > Summary.minNodeSize) + let origCount = c[slot].childCount Self.redistributeChildren(&c[prev], &c[slot], to: prevSum / 2) + path[h - 1] += c[slot].childCount - origCount assert(!c[prev].isUndersized) assert(!c[slot].isUndersized) - return + return true } assert(next < c.count) assert(c[next].childCount > Summary.minNodeSize) Self.redistributeChildren(&c[slot], &c[next], to: nextSum / 2) + // `path` doesn't need updating. assert(!c[slot].isUndersized) assert(!c[next].isUndersized) + return false } } } diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index 6e5203d8..901bfe41 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -347,7 +347,35 @@ class TestRope: XCTestCase { XCTAssertTrue(rope.isEmpty) XCTAssertEqual(rope.summary, .zero) } - + + func test_remove_at_inout_index() { + let c = 1000 + let ref = (0 ..< c).map { + Chunk(length: ($0 % 4) + 1, value: $0) + } + + var rope = Rope(ref) + + var rng = RepeatableRandomNumberGenerator(seed: 0) + let input = ref.shuffled(using: &rng) + + for i in input.indices { + let chunk = input[i] + let (offset, position) = input[i...].reduce(into: (0, 0)) { + guard $1.value < chunk.value else { return } + $0.0 += 1 + $0.1 += $1.length + } + var index = rope.index(rope.startIndex, offsetBy: offset) + let removed = rope.remove(at: &index) + XCTAssertEqual(removed, chunk) + XCTAssertEqual(rope.offset(of: index, in: Chunk.Metric()), position, "\(i)") + rope._invariantCheck() + } + XCTAssertTrue(rope.isEmpty) + XCTAssertEqual(rope.summary, .zero) + } + func test_remove_at_position() { let c = 1000 let ref = (0 ..< c).map { @@ -364,8 +392,9 @@ class TestRope: XCTestCase { let position = input[i...].reduce(into: 0) { $0 += $1.value < chunk.value ? $1.length : 0 } - let removed = rope.remove(at: position, in: Chunk.Metric()) - XCTAssertEqual(removed, chunk) + let r = rope.remove(at: position, in: Chunk.Metric()) + XCTAssertEqual(r.removed, chunk) + XCTAssertEqual(rope.offset(of: r.next, in: Chunk.Metric()), position, "\(i)") rope._invariantCheck() } XCTAssertTrue(rope.isEmpty) From 8d7c630712109b02f7ab954f4defdb3366d86a72 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 13 Apr 2023 19:36:28 -0700 Subject: [PATCH 110/113] [Xcode] Enable randomized testing --- Xcode/CollectionsTests.xcconfig | 1 + 1 file changed, 1 insertion(+) diff --git a/Xcode/CollectionsTests.xcconfig b/Xcode/CollectionsTests.xcconfig index c0fa92aa..8c257edc 100644 --- a/Xcode/CollectionsTests.xcconfig +++ b/Xcode/CollectionsTests.xcconfig @@ -28,3 +28,4 @@ CODE_SIGN_STYLE = Automatic ENABLE_TESTABILITY = NO +SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) COLLECTIONS_RANDOMIZED_TESTING From b0fe7ca8bad02599faa6a308b561f71d4d5e3b4b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 14 Apr 2023 14:38:30 -0700 Subject: [PATCH 111/113] [Rope] replaceSubrange: take a sequence, not a collection --- .../RopeModule/Rope/Basics/Rope+Builder.swift | 16 ++++++++++++++-- .../Rope/Operations/Rope+RemoveSubrange.swift | 6 ++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift index e5abec10..5ccc5b37 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift @@ -194,7 +194,7 @@ extension Rope { return } var item = item - if prefix.rebalance(nextNeighbor: &item) { + if (prefix.isUndersized || item.isUndersized), prefix.rebalance(nextNeighbor: &item) { self._prefix = prefix return } @@ -221,7 +221,19 @@ extension Rope { guard rope._root != nil else { return } _insertBeforeTip(rope.root) } - + + @inlinable + public mutating func insertBeforeTip>(_ items: __owned S) { + if S.self == Rope.self { + let items = _identityCast(items, to: Rope.self) + self.insertBeforeTip(items) + } else { + for item in items { + self.insertBeforeTip(item) + } + } + } + @inlinable mutating func _insertBeforeTip(_ node: __owned Rope._Node) { defer { _invariantCheck() } diff --git a/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift index 163edef4..13b52b34 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift @@ -29,16 +29,14 @@ extension Rope { public mutating func replaceSubrange( _ bounds: Range, in metric: some RopeMetric, - with newElements: __owned some Collection + with newElements: __owned some Sequence ) { // FIXME: Implement insert(contentsOf:at:in:) and dispatch to it when bounds.isEmpty. // FIXME: Add fast path for replacing tiny ranges with tiny data. // FIXME: Add special cases if newElements is itself a _Rope etc. _invalidateIndices() var builder = builder(removing: bounds, in: metric) - for item in newElements { - builder.insertBeforeTip(item) - } + builder.insertBeforeTip(newElements) self = builder.finalize() } From dce7b156e7276d44c3641f05bf675d90fea16523 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 17 Apr 2023 17:20:07 -0700 Subject: [PATCH 112/113] [Rope] remove(at:): Fix assertion when removing the last item creates a deficiency --- Sources/RopeModule/Rope/Operations/Rope+Remove.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift index 8b6f4453..220bca4c 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift @@ -64,10 +64,10 @@ extension Rope._Node { let prepended = fixDeficiency(on: &path) isAtEnd = isAtEnd && prepended } - if isAtEnd { + if isAtEnd, path[h] < childCount - 1 { path[h] += 1 path.clear(below: h) - isAtEnd = path[h] == childCount + isAtEnd = false } return (r.removed, r.delta, self.isUndersized, isAtEnd) } @@ -134,10 +134,10 @@ extension Rope._Node { let prepended = fixDeficiency(on: &path) isAtEnd = isAtEnd && prepended } - if isAtEnd { + if isAtEnd, path[h] < childCount - 1 { path[h] += 1 path.clear(below: h) - isAtEnd = path[h] == childCount + isAtEnd = false } return (r.removed, r.delta, self.isUndersized, isAtEnd) } From 992e0f3446b4f608f5ead9dd6edc92f6bbc0b0a0 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 24 Apr 2023 13:47:32 -0700 Subject: [PATCH 113/113] Update configuration for the Swift Package Index --- .spi.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.spi.yml b/.spi.yml index adcda23e..2aecf061 100644 --- a/.spi.yml +++ b/.spi.yml @@ -1,4 +1,4 @@ version: 1 builder: configs: - - documentation_targets: [Collections, DequeModule, OrderedCollections] + - documentation_targets: [Collections, BitCollections, DequeModule, HashTreeCollections, HeapModule, OrderedCollections]