diff --git a/Benchmarks/Sources/CppBenchmarks/src/CustomHash.h b/Benchmarks/Sources/CppBenchmarks/src/CustomHash.h index c8ba3597..f99beb61 100644 --- a/Benchmarks/Sources/CppBenchmarks/src/CustomHash.h +++ b/Benchmarks/Sources/CppBenchmarks/src/CustomHash.h @@ -19,7 +19,7 @@ extern cpp_hash_fn custom_hash_fn; -struct custom_intptr_hash: public std::unary_function +struct custom_intptr_hash: public std::function { std::size_t operator()(intptr_t value) const diff --git a/Documentation/OrderedSet.md b/Documentation/OrderedSet.md index 9786a66e..9d1285d0 100644 --- a/Documentation/OrderedSet.md +++ b/Documentation/OrderedSet.md @@ -55,7 +55,7 @@ high-level set operations such as `union(_:)`, `intersection(_:)` or ```swift buildingMaterials.contains("glass") // false -buildingMaterials.intersection(["brick", "straw"]) // ["straw", "brick"] +buildingMaterials.intersection(["bricks", "straw"]) // ["straw", "bricks"] ``` Operations that return an ordered set usually preserve the ordering of @@ -111,7 +111,7 @@ elements to the end of the collection. ```swift buildingMaterials.unordered.insert("glass") // => inserted: true -// buildingMaterials is now ["straw", "sticks", "brick", "glass"] +// buildingMaterials is now ["straw", "sticks", "bricks", "glass"] ``` Accessing the unordered view is an efficient operation, with constant diff --git a/Sources/BitCollections/BitArray/BitArray+Descriptions.swift b/Sources/BitCollections/BitArray/BitArray+Descriptions.swift index be4f0421..ebc6cdff 100644 --- a/Sources/BitCollections/BitArray/BitArray+Descriptions.swift +++ b/Sources/BitCollections/BitArray/BitArray+Descriptions.swift @@ -33,8 +33,23 @@ extension BitArray: CustomStringConvertible { extension BitArray: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. + /// + /// 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" + /// + /// As a special case, the debug description of an empty bit array is an empty pair of brackets. + /// This makes this case read better in structured printouts, like when the `BitArray` is printed + /// as part of another collection value: + /// + /// let list: [BitArray] = [[false, true], [], [false]] + /// print(list) // "[10, [], 0]" + /// public var debugDescription: String { - "BitArray(\(_bitString))" + guard !isEmpty else { return "[]" } + return description } } diff --git a/Sources/BitCollections/BitSet/BitSet+CustomDebugStringConvertible.swift b/Sources/BitCollections/BitSet/BitSet+CustomDebugStringConvertible.swift index c1120198..43d2c821 100644 --- a/Sources/BitCollections/BitSet/BitSet+CustomDebugStringConvertible.swift +++ b/Sources/BitCollections/BitSet/BitSet+CustomDebugStringConvertible.swift @@ -12,11 +12,7 @@ extension BitSet: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _debugDescription(typeName: "BitSet") - } - - internal func _debugDescription(typeName: String) -> String { - var result = "\(typeName)([" + var result = "[" var first = true for item in self { if first { @@ -26,7 +22,7 @@ extension BitSet: CustomDebugStringConvertible { } debugPrint(item, terminator: "", to: &result) } - result += "])" + result += "]" return result } } diff --git a/Sources/BitCollections/BitSet/BitSet.Counted.swift b/Sources/BitCollections/BitSet/BitSet.Counted.swift index bcbbf476..6b2992db 100644 --- a/Sources/BitCollections/BitSet/BitSet.Counted.swift +++ b/Sources/BitCollections/BitSet/BitSet.Counted.swift @@ -197,7 +197,7 @@ extension BitSet.Counted: CustomStringConvertible { extension BitSet.Counted: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _bits._debugDescription(typeName: "BitSet.Counted") + description } } diff --git a/Sources/BitCollections/BitSet/BitSet.Index.swift b/Sources/BitCollections/BitSet/BitSet.Index.swift index 433dd37d..5735f33e 100644 --- a/Sources/BitCollections/BitSet/BitSet.Index.swift +++ b/Sources/BitCollections/BitSet/BitSet.Index.swift @@ -55,7 +55,7 @@ extension BitSet.Index: CustomStringConvertible { extension BitSet.Index: CustomDebugStringConvertible { // A textual representation of this instance, suitable for debugging. public var debugDescription: String { - "BitSet.Index(\(_value))" + description } } diff --git a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift index 06d48e0e..9abef257 100644 --- a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift +++ b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift @@ -223,8 +223,8 @@ extension _UnsafeBitSet { let r = range.clamped(to: 0 ..< UInt(capacity)) guard r == range else { return false } - let lower = Index(range.lowerBound) - let upper = Index(range.upperBound) + let lower = Index(range.lowerBound).split + let upper = Index(range.upperBound).endSplit guard upper.word == wordCount &- 1 else { return false } diff --git a/Sources/BitCollections/CMakeLists.txt b/Sources/BitCollections/CMakeLists.txt index 8cc52f44..b8990fdf 100644 --- a/Sources/BitCollections/CMakeLists.txt +++ b/Sources/BitCollections/CMakeLists.txt @@ -1,7 +1,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 @@ -14,6 +14,7 @@ add_library(BitCollections "BitArray/BitArray+Collection.swift" "BitArray/BitArray+Copy.swift" "BitArray/BitArray+CustomReflectable.swift" + "BitArray/BitArray+Descriptions.swift" "BitArray/BitArray+Equatable.swift" "BitArray/BitArray+ExpressibleByArrayLiteral.swift" "BitArray/BitArray+Extras.swift" @@ -21,6 +22,7 @@ add_library(BitCollections "BitArray/BitArray+Hashable.swift" "BitArray/BitArray+Initializers.swift" "BitArray/BitArray+Invariants.swift" + "BitArray/BitArray+RandomBits.swift" "BitArray/BitArray+RangeReplaceableCollection.swift" "BitArray/BitArray+Testing.swift" "BitArray/BitArray._UnsafeHandle.swift" diff --git a/Sources/CMakeLists.txt b/Sources/CMakeLists.txt index ad81e77d..0d24cb07 100644 --- a/Sources/CMakeLists.txt +++ b/Sources/CMakeLists.txt @@ -1,7 +1,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 @@ -10,7 +10,8 @@ See https://swift.org/LICENSE.txt for license information add_subdirectory(BitCollections) add_subdirectory(Collections) add_subdirectory(DequeModule) +add_subdirectory(HashTreeCollections) add_subdirectory(HeapModule) add_subdirectory(OrderedCollections) -add_subdirectory(HashTreeCollections) +add_subdirectory(RopeModule) add_subdirectory(_CollectionsUtilities) diff --git a/Sources/DequeModule/Deque+Descriptions.swift b/Sources/DequeModule/Deque+Descriptions.swift index 9e27a2f6..cc23c386 100644 --- a/Sources/DequeModule/Deque+Descriptions.swift +++ b/Sources/DequeModule/Deque+Descriptions.swift @@ -23,7 +23,6 @@ extension Deque: CustomStringConvertible { extension Deque: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _arrayDescription( - for: self, debug: true, typeName: "Deque<\(Element.self)>") + description } } diff --git a/Sources/HashTreeCollections/CMakeLists.txt b/Sources/HashTreeCollections/CMakeLists.txt index 6c105e8a..f28687f4 100644 --- a/Sources/HashTreeCollections/CMakeLists.txt +++ b/Sources/HashTreeCollections/CMakeLists.txt @@ -1,7 +1,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 @@ -12,8 +12,6 @@ add_library(HashTreeCollections "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" @@ -40,11 +38,13 @@ add_library(HashTreeCollections "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/_StorageHeader.swift" + "HashNode/_HashTreeIterator.swift" + "HashNode/_HashTreeStatistics.swift" + "HashNode/_RawHashNode+UnsafeHandle.swift" + "HashNode/_RawHashNode.swift" + "HashNode/_HashNodeHeader.swift" "HashNode/_UnmanagedHashNode.swift" "HashNode/_UnsafePath.swift" "TreeDictionary/TreeDictionary+Codable.swift" diff --git a/Sources/HashTreeCollections/HashNode/_StorageHeader.swift b/Sources/HashTreeCollections/HashNode/_HashNodeHeader.swift similarity index 100% rename from Sources/HashTreeCollections/HashNode/_StorageHeader.swift rename to Sources/HashTreeCollections/HashNode/_HashNodeHeader.swift diff --git a/Sources/HashTreeCollections/HashTreeCollections.docc/Extensions/TreeSet.md b/Sources/HashTreeCollections/HashTreeCollections.docc/Extensions/TreeSet.md index 86add030..3642fac7 100644 --- a/Sources/HashTreeCollections/HashTreeCollections.docc/Extensions/TreeSet.md +++ b/Sources/HashTreeCollections/HashTreeCollections.docc/Extensions/TreeSet.md @@ -32,7 +32,7 @@ two nodes: ``` The root node directly contains `Maximo`, because it is the only set member -whose hash value starts with `8`. However, the first digits of the hashes of +whose hash value starts with `2`. However, the first digits of the hashes of `Julia` and `Don Pablo` are both `A`, so these items reside in a separate node, one level below the root. diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift index a1df0ed0..e071bef9 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift @@ -94,7 +94,7 @@ extension TreeDictionary.Index: CustomStringConvertible { extension TreeDictionary.Index: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _path.description + description } } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Descriptions.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Descriptions.swift index d0e8f6aa..53ba75bf 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Descriptions.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Descriptions.swift @@ -23,11 +23,6 @@ extension TreeDictionary: CustomStringConvertible { extension TreeDictionary: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _dictionaryDescription( - for: self, debug: true, typeName: Self._debugTypeName()) - } - - internal static func _debugTypeName() -> String { - "TreeDictionary<\(Key.self), \(Value.self)>" + description } } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift index da2d3a54..a7e22ad1 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Keys.swift @@ -53,10 +53,7 @@ extension TreeDictionary.Keys: CustomStringConvertible { extension TreeDictionary.Keys: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _arrayDescription( - for: self, - debug: true, - typeName: "\(TreeDictionary._debugTypeName()).Keys") + description } } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift index 40d4d4a1..68814a2f 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Values.swift @@ -56,10 +56,7 @@ extension TreeDictionary.Values: CustomStringConvertible { extension TreeDictionary.Values: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _arrayDescription( - for: self, - debug: true, - typeName: "\(TreeDictionary._debugTypeName()).Values") + description } } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Descriptions.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Descriptions.swift index 13d7b419..8939c463 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Descriptions.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Descriptions.swift @@ -23,11 +23,6 @@ extension TreeSet: CustomStringConvertible { extension TreeSet: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _arrayDescription( - for: self, debug: true, typeName: _debugTypeName()) - } - - internal func _debugTypeName() -> String { - "TreeSet<\(Element.self)>" + description } } diff --git a/Sources/HeapModule/Heap.swift b/Sources/HeapModule/Heap.swift index 4e7e60e9..52651fd8 100644 --- a/Sources/HeapModule/Heap.swift +++ b/Sources/HeapModule/Heap.swift @@ -9,20 +9,54 @@ // //===----------------------------------------------------------------------===// -/// A [Min-Max Heap](https://en.wikipedia.org/wiki/Min-max_heap) data structure. + +/// A container type implementing a double-ended priority queue. +/// `Heap` is a container of `Comparable` elements that provides immediate +/// access to its minimal and maximal members, and supports removing these items +/// or inserting arbitrary new items in (amortized) logarithmic complexity. /// -/// In a min-max heap, each node at an even level in the tree is less than or -/// equal to all its descendants, while each node at an odd level in the tree is -/// greater than or equal to all of its descendants. +/// var queue: Heap = [3, 4, 1, 2] +/// queue.insert(0) +/// print(queue.min()) // 0 +/// print(queue.popMax()) // 4 +/// print(queue.max()) // 3 /// -/// The implementation is based on [Atkinson et al. 1986]: +/// `Heap` implements the min-max heap data structure, based on +/// [Atkinson et al. 1986]. /// /// [Atkinson et al. 1986]: https://doi.org/10.1145/6617.6621 /// -/// M.D. Atkinson, J.-R. Sack, N. Santoro, T. Strothotte. +/// > M.D. Atkinson, J.-R. Sack, N. Santoro, T. Strothotte. /// "Min-Max Heaps and Generalized Priority Queues." /// *Communications of the ACM*, vol. 29, no. 10, Oct. 1986., pp. 996-1000, /// doi:[10.1145/6617.6621](https://doi.org/10.1145/6617.6621) +/// +/// To efficiently implement these operations, a min-max heap arranges its items +/// into a complete binary tree, maintaining a specific invariant across levels, +/// called the "min-max heap property": each node at an even level in the tree +/// must be less than or equal to all its descendants, while each node at an odd +/// level in the tree must be greater than or equal to all of its descendants. +/// To achieve a compact representation, this tree is stored in breadth-first +/// order inside a single contiguous array value. +/// +/// Unlike most container types, `Heap` doesn't provide a direct way to iterate +/// over the elements it contains -- it isn't a `Sequence` (nor a `Collection`). +/// This is because the order of items in a heap is unspecified and unstable: +/// it may vary between heaps that contain the same set of items, and it may +/// sometimes change in between versions of this library. In particular, the +/// items are (almost) never expected to be in sorted order. +/// +/// For cases where you do need to access the contents of a heap directly and +/// you don't care about their (lack of) order, you can do so by invoking the +/// `unordered` view. This read-only view gives you direct access to the +/// underlying array value: +/// +/// for item in queue.unordered { +/// ... +/// } +/// +/// The name `unordered` highlights the lack of ordering guarantees on the +/// contents, and it helps avoid relying on any particular order. @frozen public struct Heap { @usableFromInline @@ -253,18 +287,49 @@ extension Heap { /// /// - Parameter newElements: The new elements to insert into the heap. /// - /// - Complexity: O(*n* * log(`count`)), where *n* is the length of `newElements`. + /// - Complexity: O(`count` + *k*), where *k* is the length of `newElements`. @inlinable public mutating func insert( contentsOf newElements: S ) where S.Element == Element { - if count == 0 { + let origCount = self.count + if origCount == 0 { self = Self(newElements) return } - _storage.reserveCapacity(count + newElements.underestimatedCount) - for element in newElements { - insert(element) + defer { _checkInvariants() } + _storage.append(contentsOf: newElements) + let newCount = self.count + + guard newCount > origCount, newCount > 1 else { + // If we didn't append, or the result is too small to violate heapness, + // then we have nothing else to dp. + return + } + + // Otherwise we can either insert items one by one, or we can run Floyd's + // algorithm to re-heapify our entire storage from scratch. + // + // If n is the original count, and k is the number of items we need to + // append, then Floyd's costs O(n + k) comparisons/swaps, while + // the naive loop costs k * log(n + k) -- so we expect that Floyd will + // be cheaper whenever k is "large enough" relative to n. + // + // Floyd's algorithm has a worst-case upper complexity bound of 2 * (n + k), + // so one simple heuristic is to use it whenever k * log(n + k) exceeds + // that. + // + // FIXME: Write a benchmark to verify this heuristic. + let heuristicLimit = 2 * newCount / newCount._binaryLogarithm() + let useFloyd = (newCount - origCount) < heuristicLimit + _update { handle in + if useFloyd { + handle.heapify() + } else { + for offset in origCount ..< handle.count { + handle.bubbleUp(_HeapNode(offset: offset)) + } + } } } } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift index 9188f615..f0569a5a 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift @@ -23,11 +23,6 @@ extension OrderedDictionary: CustomStringConvertible { extension OrderedDictionary: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _dictionaryDescription( - for: self.elements, debug: true, typeName: Self._debugTypeName()) - } - - internal static func _debugTypeName() -> String { - "OrderedDictionary<\(Key.self), \(Value.self)>" + description } } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift index b6c9f16f..587c9df2 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.SubSequence.swift @@ -47,11 +47,7 @@ extension OrderedDictionary.Elements.SubSequence: CustomStringConvertible { extension OrderedDictionary.Elements.SubSequence: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _dictionaryDescription( - for: self, - debug: true, - typeName: "\(OrderedDictionary._debugTypeName()).Elements.SubSequence" - ) + description } } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index 66cd9926..d60779c7 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -342,10 +342,7 @@ extension OrderedDictionary.Elements: CustomStringConvertible { extension OrderedDictionary.Elements: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _dictionaryDescription( - for: self, - debug: true, - typeName: "OrderedDictionary<\(Key.self), \(Value.self)>.Elements") + description } } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift index 6796917f..29773637 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Values.swift @@ -41,10 +41,7 @@ extension OrderedDictionary.Values: CustomStringConvertible { extension OrderedDictionary.Values: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _arrayDescription( - for: self, - debug: true, - typeName: "OrderedDictionary<\(Key.self), \(Value.self)>.Keys") + description } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift index fa023ffc..f1cb7489 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift @@ -23,11 +23,6 @@ extension OrderedSet: CustomStringConvertible { extension OrderedSet: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _arrayDescription( - for: self, debug: true, typeName: Self._debugTypeName()) - } - - internal static func _debugTypeName() -> String { - "OrderedSet<\(Element.self)>" + description } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift index 017a0d22..a3f63954 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift @@ -63,11 +63,7 @@ extension OrderedSet.SubSequence: CustomStringConvertible { extension OrderedSet.SubSequence: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _arrayDescription( - for: self, - debug: true, - typeName: "\(OrderedSet._debugTypeName()).SubSequence" - ) + description } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift index 8efa76d0..2c52231c 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+UnorderedView.swift @@ -71,17 +71,14 @@ extension OrderedSet.UnorderedView: Sendable where Element: Sendable {} extension OrderedSet.UnorderedView: CustomStringConvertible { /// A textual representation of this instance. public var description: String { - _base.description + _arrayDescription(for: _base) } } extension OrderedSet.UnorderedView: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - _arrayDescription( - for: _base, - debug: true, - typeName: "\(OrderedSet._debugTypeName()).UnorderedView") + description } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index 0934047b..439369ee 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -53,7 +53,7 @@ import _CollectionsUtilities /// ``intersection(_:)-4o09a`` or ``isSubset(of:)-ptij``. /// /// buildingMaterials.contains("glass") // false -/// buildingMaterials.intersection(["brick", "straw"]) // ["straw", "brick"] +/// buildingMaterials.intersection(["bricks", "straw"]) // ["straw", "bricks"] /// /// Operations that return an ordered set usually preserve the ordering of /// elements in their input. For example, in the case of the `intersection` call @@ -103,7 +103,7 @@ import _CollectionsUtilities /// elements to the end of the collection. /// /// buildingMaterials.unordered.insert("glass") // => inserted: true -/// // buildingMaterials is now ["straw", "sticks", "brick", "glass"] +/// // buildingMaterials is now ["straw", "sticks", "bricks", "glass"] /// /// Accessing the unordered view is an efficient operation, with constant /// (minimal) overhead. Direct mutations of the unordered view (such as the diff --git a/Sources/RopeModule/CMakeLists.txt b/Sources/RopeModule/CMakeLists.txt new file mode 100644 index 00000000..936e16cc --- /dev/null +++ b/Sources/RopeModule/CMakeLists.txt @@ -0,0 +1,94 @@ +#[[ +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 +#]] + +add_library(RopeModule + "BigString/Basics/BigString+Metrics.swift" + "BigString/Basics/BigString+Index.swift" + "BigString/Basics/BigString+Summary.swift" + "BigString/Basics/BigString.swift" + "BigString/Basics/BigString+Iterators.swift" + "BigString/Basics/BigString+Contents.swift" + "BigString/Basics/BigString+Invariants.swift" + "BigString/Basics/BigString+Ingester.swift" + "BigString/Basics/BigString+Debugging.swift" + "BigString/Basics/BigString+Builder.swift" + "BigString/Chunk/BigString+Chunk+Append and Insert.swift" + "BigString/Chunk/BigString+Chunk+Indexing by UTF16.swift" + "BigString/Chunk/BigString+Chunk+Counts.swift" + "BigString/Chunk/BigString+Chunk+Indexing by Characters.swift" + "BigString/Chunk/BigString+Chunk.swift" + "BigString/Chunk/BigString+Chunk+Description.swift" + "BigString/Chunk/BigString+Chunk+Splitting.swift" + "BigString/Chunk/BigString+Chunk+Breaks.swift" + "BigString/Chunk/BigString+Chunk+RopeElement.swift" + "BigString/Operations/BigString+Split.swift" + "BigString/Operations/BigString+Managing Breaks.swift" + "BigString/Operations/BigString+RemoveSubrange.swift" + "BigString/Operations/BigString+ReplaceSubrange.swift" + "BigString/Operations/BigString+Insert.swift" + "BigString/Operations/BigString+Initializers.swift" + "BigString/Operations/Range+BigString.swift" + "BigString/Operations/BigString+Append.swift" + "BigString/Views/BigString+UnicodeScalarView.swift" + "BigString/Views/BigString+UTF8View.swift" + "BigString/Views/BigSubstring+UnicodeScalarView.swift" + "BigString/Views/BigSubstring.swift" + "BigString/Views/BigSubstring+UTF16View.swift" + "BigString/Views/BigString+UTF16View.swift" + "BigString/Views/BigSubstring+UTF8View.swift" + "BigString/Conformances/BigString+Hashing.swift" + "BigString/Conformances/BigString+CustomStringConvertible.swift" + "BigString/Conformances/BigString+BidirectionalCollection.swift" + "BigString/Conformances/BigString+CustomDebugStringConvertible.swift" + "BigString/Conformances/BigString+Equatable.swift" + "BigString/Conformances/BigString+TextOutputStream.swift" + "BigString/Conformances/BigString+LosslessStringConvertible.swift" + "BigString/Conformances/BigString+Sequence.swift" + "BigString/Conformances/BigString+ExpressibleByStringLiteral.swift" + "BigString/Conformances/BigString+RangeReplaceableCollection.swift" + "BigString/Conformances/BigString+Comparable.swift" + "Rope/Basics/RopeMetric.swift" + "Rope/Basics/_RopeItem.swift" + "Rope/Basics/Rope+Debugging.swift" + "Rope/Basics/_RopeVersion.swift" + "Rope/Basics/RopeElement.swift" + "Rope/Basics/Rope.swift" + "Rope/Basics/Rope+_UnsafeHandle.swift" + "Rope/Basics/Rope+_Storage.swift" + "Rope/Basics/Rope+Invariants.swift" + "Rope/Basics/Rope+_UnmanagedLeaf.swift" + "Rope/Basics/RopeSummary.swift" + "Rope/Basics/Rope+Builder.swift" + "Rope/Basics/_RopePath.swift" + "Rope/Basics/Rope+_Node.swift" + "Rope/Operations/Rope+Extract.swift" + "Rope/Operations/Rope+Append.swift" + "Rope/Operations/Rope+Split.swift" + "Rope/Operations/Rope+Find.swift" + "Rope/Operations/Rope+Insert.swift" + "Rope/Operations/Rope+ForEachWhile.swift" + "Rope/Operations/Rope+MutatingForEach.swift" + "Rope/Operations/Rope+Join.swift" + "Rope/Operations/Rope+Remove.swift" + "Rope/Operations/Rope+RemoveSubrange.swift" + "Rope/Conformances/Rope+Index.swift" + "Rope/Conformances/Rope+Sequence.swift" + "Rope/Conformances/Rope+Collection.swift" + "Utilities/String Utilities.swift" + "Utilities/_CharacterRecognizer.swift" + "Utilities/String.Index+ABI.swift" + "Utilities/Optional Utilities.swift" + ) +target_link_libraries(RopeModule PRIVATE + _CollectionsUtilities) +set_target_properties(RopeModule PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) + +_install_target(RopeModule) +set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS RopeModule) diff --git a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift index 4d84e168..f7848ce7 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift @@ -14,9 +14,9 @@ import _CollectionsUtilities // for 5.8 polyfills #endif extension Rope { + @frozen // Not really! This module isn't ABI stable. @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 @@ -550,6 +550,7 @@ extension Rope._Node { } } + @frozen // Not really! This module isn't ABI stable. @usableFromInline internal struct _ModifyState { @usableFromInline internal var path: _Path diff --git a/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift b/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift index c5599922..fa93b8f5 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// @usableFromInline +@frozen // Not really! This module isn't ABI stable. internal struct _RopeStorageHeader { @usableFromInline var _childCount: UInt16 @usableFromInline let height: UInt8 @@ -33,6 +34,7 @@ internal struct _RopeStorageHeader { extension Rope { @usableFromInline + @_fixed_layout // Not really! This module isn't ABI stable. internal final class _Storage>: ManagedBuffer<_RopeStorageHeader, Child> { diff --git a/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift b/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift index 1c53c19a..4e254aed 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension Rope { + @frozen // Not really! This module isn't ABI stable. @usableFromInline internal struct _UnmanagedLeaf { @usableFromInline internal typealias _Item = Rope._Item diff --git a/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift b/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift index a7dcec47..e67291d1 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift @@ -11,9 +11,9 @@ extension Rope { @usableFromInline + @frozen // Not really! This module isn't ABI stable. internal struct _UnsafeHandle> { @usableFromInline internal typealias Summary = Rope.Summary - @usableFromInline internal typealias Element = Rope.Element @usableFromInline internal let _header: UnsafeMutablePointer<_RopeStorageHeader> diff --git a/Sources/RopeModule/Rope/Basics/Rope.swift b/Sources/RopeModule/Rope/Basics/Rope.swift index 5411fb2a..aae8dd80 100644 --- a/Sources/RopeModule/Rope/Basics/Rope.swift +++ b/Sources/RopeModule/Rope/Basics/Rope.swift @@ -12,6 +12,7 @@ /// 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. +@frozen // Not really! This module isn't ABI stable. public struct Rope { @usableFromInline internal var _root: _Node? diff --git a/Sources/RopeModule/Rope/Basics/_RopeItem.swift b/Sources/RopeModule/Rope/Basics/_RopeItem.swift index db24ab04..186ba9fe 100644 --- a/Sources/RopeModule/Rope/Basics/_RopeItem.swift +++ b/Sources/RopeModule/Rope/Basics/_RopeItem.swift @@ -42,6 +42,7 @@ extension Rope { /// A trivial wrapper around a rope's Element type, giving it `_RopeItem` conformance without /// having to make the protocol public. @usableFromInline + @frozen // Not really! This module isn't ABI stable. internal struct _Item { @usableFromInline internal var value: Element diff --git a/Sources/RopeModule/Rope/Operations/Rope+Find.swift b/Sources/RopeModule/Rope/Operations/Rope+Find.swift index a6d4ff44..cbed76b7 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Find.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Find.swift @@ -19,7 +19,7 @@ extension Rope { let wholeSize = _root == nil ? 0 : metric.size(of: root.summary) precondition(position >= 0 && position <= wholeSize, "Position out of bounds") guard !isEmpty, preferEnd || position < wholeSize else { - return (endIndex, position) + return (endIndex, 0) } var position = position var node = root diff --git a/Sources/RopeModule/Rope/Operations/Rope+Split.swift b/Sources/RopeModule/Rope/Operations/Rope+Split.swift index dab68354..71bbaf10 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Split.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Split.swift @@ -18,6 +18,10 @@ extension Rope { _invalidateIndices() var builder = Builder() + if self.isEmpty { + precondition(position == 0, "Position out of bounds") + return builder + } var position = position var node = root _root = nil diff --git a/Sources/_CollectionsUtilities/CMakeLists.txt b/Sources/_CollectionsUtilities/CMakeLists.txt index e9c13b6b..3873f383 100644 --- a/Sources/_CollectionsUtilities/CMakeLists.txt +++ b/Sources/_CollectionsUtilities/CMakeLists.txt @@ -1,7 +1,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/_CollectionsUtilities/Descriptions.swift.gyb b/Sources/_CollectionsUtilities/Descriptions.swift.gyb index 73e10e11..4f79e161 100644 --- a/Sources/_CollectionsUtilities/Descriptions.swift.gyb +++ b/Sources/_CollectionsUtilities/Descriptions.swift.gyb @@ -35,15 +35,9 @@ ${modifier} func _addressString(for object: Unmanaged) -> Strin @inlinable ${modifier} func _arrayDescription( - for elements: C, - debug: Bool = false, - typeName: String? = nil + for elements: C ) -> String { - var result = "" - if let typeName = typeName { - result += "\(typeName)(" - } - result += "[" + var result = "[" var first = true for item in elements { if first { @@ -51,53 +45,30 @@ ${modifier} func _arrayDescription( } else { result += ", " } - if debug { - debugPrint(item, terminator: "", to: &result) - } else { - print(item, terminator: "", to: &result) - } + debugPrint(item, terminator: "", to: &result) } result += "]" - if typeName != nil { result += ")" } return result } @inlinable ${modifier} func _dictionaryDescription( - for elements: C, - debug: Bool = false, - typeName: String? = nil + for elements: C ) -> 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)" - } + guard !elements.isEmpty else { return "[:]" } + var result = "[" + var first = true + for (key, value) in elements { + if first { + first = false + } else { + result += ", " } - result += "]" - } - - if typeName != nil { - result += ")" + debugPrint(key, terminator: "", to: &result) + result += ": " + debugPrint(value, terminator: "", to: &result) } + result += "]" return result } % end diff --git a/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb b/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb index de75e1f7..59ad49ed 100644 --- a/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb +++ b/Sources/_CollectionsUtilities/IntegerTricks/Integer rank.swift.gyb @@ -41,13 +41,16 @@ extension UInt { var shift: Self = 0 var n = Self(truncatingIfNeeded: n) - if Self.bitWidth == 64 { + if MemoryLayout.size == 8 { let c32 = (self & 0xFFFFFFFF)._nonzeroBitCount if n >= c32 { shift &+= 32 n &-= c32 } + } else { + assert(MemoryLayout.size == 4, "Unknown platform") } + let c16 = ((self &>> shift) & 0xFFFF)._nonzeroBitCount if n >= c16 { shift &+= 16 diff --git a/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift index 02790d35..07ede453 100644 --- a/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift +++ b/Sources/_CollectionsUtilities/IntegerTricks/autogenerated/Integer rank.swift @@ -47,13 +47,16 @@ extension UInt { var shift: Self = 0 var n = Self(truncatingIfNeeded: n) - if Self.bitWidth == 64 { + if MemoryLayout.size == 8 { let c32 = (self & 0xFFFFFFFF)._nonzeroBitCount if n >= c32 { shift &+= 32 n &-= c32 } + } else { + assert(MemoryLayout.size == 4, "Unknown platform") } + let c16 = ((self &>> shift) & 0xFFFF)._nonzeroBitCount if n >= c16 { shift &+= 16 @@ -184,13 +187,16 @@ extension UInt { var shift: Self = 0 var n = Self(truncatingIfNeeded: n) - if Self.bitWidth == 64 { + if MemoryLayout.size == 8 { let c32 = (self & 0xFFFFFFFF)._nonzeroBitCount if n >= c32 { shift &+= 32 n &-= c32 } + } else { + assert(MemoryLayout.size == 4, "Unknown platform") } + let c16 = ((self &>> shift) & 0xFFFF)._nonzeroBitCount if n >= c16 { shift &+= 16 diff --git a/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift b/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift index 93bdbe93..3fc0f73f 100644 --- a/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift +++ b/Sources/_CollectionsUtilities/autogenerated/Descriptions.swift @@ -41,15 +41,9 @@ internal func _addressString(for object: Unmanaged) -> String { @inlinable internal func _arrayDescription( - for elements: C, - debug: Bool = false, - typeName: String? = nil + for elements: C ) -> String { - var result = "" - if let typeName = typeName { - result += "\(typeName)(" - } - result += "[" + var result = "[" var first = true for item in elements { if first { @@ -57,53 +51,30 @@ internal func _arrayDescription( } else { result += ", " } - if debug { - debugPrint(item, terminator: "", to: &result) - } else { - print(item, terminator: "", to: &result) - } + debugPrint(item, terminator: "", to: &result) } result += "]" - if typeName != nil { result += ")" } return result } @inlinable internal func _dictionaryDescription( - for elements: C, - debug: Bool = false, - typeName: String? = nil + for elements: C ) -> 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)" - } + guard !elements.isEmpty else { return "[:]" } + var result = "[" + var first = true + for (key, value) in elements { + if first { + first = false + } else { + result += ", " } - result += "]" - } - - if typeName != nil { - result += ")" + debugPrint(key, terminator: "", to: &result) + result += ": " + debugPrint(value, terminator: "", to: &result) } + result += "]" return result } #else // !COLLECTIONS_SINGLE_MODULE @@ -126,15 +97,9 @@ public func _addressString(for object: Unmanaged) -> String { @inlinable public func _arrayDescription( - for elements: C, - debug: Bool = false, - typeName: String? = nil + for elements: C ) -> String { - var result = "" - if let typeName = typeName { - result += "\(typeName)(" - } - result += "[" + var result = "[" var first = true for item in elements { if first { @@ -142,53 +107,30 @@ public func _arrayDescription( } else { result += ", " } - if debug { - debugPrint(item, terminator: "", to: &result) - } else { - print(item, terminator: "", to: &result) - } + debugPrint(item, terminator: "", to: &result) } result += "]" - if typeName != nil { result += ")" } return result } @inlinable public func _dictionaryDescription( - for elements: C, - debug: Bool = false, - typeName: String? = nil + for elements: C ) -> 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)" - } + guard !elements.isEmpty else { return "[:]" } + var result = "[" + var first = true + for (key, value) in elements { + if first { + first = false + } else { + result += ", " } - result += "]" - } - - if typeName != nil { - result += ")" + debugPrint(key, terminator: "", to: &result) + result += ": " + debugPrint(value, terminator: "", to: &result) } + result += "]" return result } #endif // COLLECTIONS_SINGLE_MODULE diff --git a/Tests/BitCollectionsTests/BitArrayTests.swift b/Tests/BitCollectionsTests/BitArrayTests.swift index 2368689f..c50e0f0c 100644 --- a/Tests/BitCollectionsTests/BitArrayTests.swift +++ b/Tests/BitCollectionsTests/BitArrayTests.swift @@ -934,13 +934,13 @@ final class BitArrayTests: CollectionTestCase { func test_debugDescription() { let a: BitArray = [] - expectEqual("\(String(reflecting: a))", "BitArray()") + expectEqual("\(String(reflecting: a))", "[]") let b: BitArray = [true, false, true, true, true] - expectEqual("\(String(reflecting: b))", "BitArray(11101)") + expectEqual("\(String(reflecting: b))", "11101") let c: BitArray = [false, false, false, false, true, true, true, false] - expectEqual("\(String(reflecting: c))", "BitArray(01110000)") + expectEqual("\(String(reflecting: c))", "01110000") } func test_mirror() { diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index 0851a368..e58f77c7 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -1109,6 +1109,14 @@ final class BitSetTest: CollectionTestCase { let c = BitSet(130 ..< 160) expectTrue(c.isEqualSet(to: 130 ..< 160)) + + withEvery("i", in: stride(from: 0, to: 200, by: 4)) { i in + withEvery("j", in: stride(from: i, to: 200, by: 4)) { j in + let c = BitSet(i ..< j) + expectTrue(c.isEqualSet(to: i ..< j)) + expectFalse(c.isEqualSet(to: i ..< (j + 1))) + } + } } func test_isEqual_to_counted_BitSet() { @@ -1505,13 +1513,13 @@ final class BitSetTest: CollectionTestCase { func test_debugDescription() { let a: BitSet = [] - expectEqual("\(String(reflecting: a))", "BitSet([])") + expectEqual("\(String(reflecting: a))", "[]") let b: BitSet = [1, 2, 3] - expectEqual("\(String(reflecting: b))", "BitSet([1, 2, 3])") + expectEqual("\(String(reflecting: b))", "[1, 2, 3]") let c: BitSet = [23, 652, 892, 19230] - expectEqual("\(String(reflecting: c))", "BitSet([23, 652, 892, 19230])") + expectEqual("\(String(reflecting: c))", "[23, 652, 892, 19230]") } func test_index_descriptions() { @@ -1519,7 +1527,7 @@ final class BitSetTest: CollectionTestCase { let i = a.startIndex expectEqual(i.description, "3") - expectEqual(i.debugDescription, "BitSet.Index(3)") + expectEqual(i.debugDescription, "3") } func test_mirror() { diff --git a/Tests/CollectionsTestSupportTests/UtilitiesTests.swift b/Tests/CollectionsTestSupportTests/UtilitiesTests.swift index b0038980..ae64f2b9 100644 --- a/Tests/CollectionsTestSupportTests/UtilitiesTests.swift +++ b/Tests/CollectionsTestSupportTests/UtilitiesTests.swift @@ -21,7 +21,10 @@ final class UtilitiesTests: CollectionTestCase { withSome("i", in: 0 ..< Int.max, maxSamples: 100_000) { i in let s = i._squareRoot() expectLessThanOrEqual(s * s, i) - expectGreaterThan((s + 1) * (s + 1), i) + let next = (s + 1).multipliedReportingOverflow(by: s + 1) + if !next.overflow { + expectGreaterThan(next.partialValue, i) + } } } } diff --git a/Tests/DequeTests/DequeTests.swift b/Tests/DequeTests/DequeTests.swift index 7c191e4d..ef9b0b0b 100644 --- a/Tests/DequeTests/DequeTests.swift +++ b/Tests/DequeTests/DequeTests.swift @@ -52,19 +52,18 @@ final class DequeTests: CollectionTestCase { expectEqual("\([1, 2, nil, 3] as Deque)", "[Optional(1), Optional(2), nil, Optional(3)]") let deque: Deque = [1, 2, 3] - expectEqual("\(deque)", "[description(1), description(2), description(3)]") + expectEqual("\(deque)", "[debugDescription(1), debugDescription(2), debugDescription(3)]") } func test_debugDescription() { - expectEqual(String(reflecting: [] as Deque), - "Deque([])") - expectEqual(String(reflecting: [1, 2, 3] as Deque), - "Deque([1, 2, 3])") - expectEqual(String(reflecting: [1, 2, nil, 3] as Deque), - "Deque>([Optional(1), Optional(2), nil, Optional(3)])") + expectEqual(String(reflecting: [] as Deque), "[]") + expectEqual(String(reflecting: [1, 2, 3] as Deque), "[1, 2, 3]") + expectEqual( + String(reflecting: [1, 2, nil, 3] as Deque), + "[Optional(1), Optional(2), nil, Optional(3)]") let deque: Deque = [1, 2, 3] - expectEqual(String(reflecting: deque), "Deque([debugDescription(1), debugDescription(2), debugDescription(3)])") + expectEqual(String(reflecting: deque), "[debugDescription(1), debugDescription(2), debugDescription(3)]") } func test_customMirror() { diff --git a/Tests/HashTreeCollectionsTests/Colliders.swift b/Tests/HashTreeCollectionsTests/Colliders.swift index 9b8b5f5d..e2c142ce 100644 --- a/Tests/HashTreeCollectionsTests/Colliders.swift +++ b/Tests/HashTreeCollectionsTests/Colliders.swift @@ -43,11 +43,11 @@ struct Collider: } var description: String { - "\(identity)" + "\(identity)(#\(hash))" } var debugDescription: String { - "\(identity)-#\(hash)" + description } } diff --git a/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift b/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift index c38fcfc7..c1308e93 100644 --- a/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift +++ b/Tests/HashTreeCollectionsTests/TreeDictionary Tests.swift @@ -471,20 +471,14 @@ class TreeDictionaryTests: CollectionTestCase { func test_CustomDebugStringConvertible() { let a: TreeDictionary = [:] - expectEqual( - a.debugDescription, - "TreeDictionary([:])") + expectEqual(a.debugDescription, "[:]") let b: TreeDictionary = [0: 1] - expectEqual( - b.debugDescription, - "TreeDictionary([0: 1])") + expectEqual(b.debugDescription, "[0: 1]") let c: TreeDictionary = [0: 1, 2: 3, 4: 5] let cd = c.map { "\($0.key): \($0.value)"}.joined(separator: ", ") - expectEqual( - c.debugDescription, - "TreeDictionary([\(cd)])") + expectEqual(c.debugDescription, "[\(cd)]") } diff --git a/Tests/HashTreeCollectionsTests/TreeDictionary.Keys Tests.swift b/Tests/HashTreeCollectionsTests/TreeDictionary.Keys Tests.swift index 9dc06a27..663cf8cd 100644 --- a/Tests/HashTreeCollectionsTests/TreeDictionary.Keys Tests.swift +++ b/Tests/HashTreeCollectionsTests/TreeDictionary.Keys Tests.swift @@ -37,15 +37,11 @@ class TreeDictionaryKeysTests: CollectionTestCase { ] if d.first!.key == "a" { - expectEqual(d.keys.description, "[a, b]") - expectEqual( - d.keys.debugDescription, - "TreeDictionary.Keys([\"a\", \"b\"])") + expectEqual(d.keys.description, #"["a", "b"]"#) + expectEqual(d.keys.debugDescription, #"["a", "b"]"#) } else { - expectEqual(d.keys.description, "[b, a]") - expectEqual( - d.keys.debugDescription, - "TreeDictionary.Keys([\"b\", \"a\"])") + expectEqual(d.keys.description, #"["b", "a"]"#) + expectEqual(d.keys.debugDescription, #"["b", "a"]"#) } } diff --git a/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift b/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift index 58333c84..ae8735f0 100644 --- a/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift +++ b/Tests/HashTreeCollectionsTests/TreeHashedCollections Fixtures.swift @@ -21,20 +21,34 @@ import HashTreeCollections /// /// Note: Try to keep this short. Every new item added here will quadruple /// testing costs. -let testItems = [ - RawCollider(1, "A"), - RawCollider(2, "B"), - RawCollider(3, "ACA"), - RawCollider(4, "ACB"), - RawCollider(5, "ACAD"), - RawCollider(6, "ACAD"), - RawCollider(7, "ACAEB"), - RawCollider(8, "ACAEB"), - RawCollider(9, "ACAEB"), - // RawCollider(10, "ACAEB"), - // RawCollider(11, "ADAD"), - // RawCollider(12, "ACC"), -] +let testItems: [RawCollider] = { + var testItems = [ + RawCollider(1, "A"), + RawCollider(2, "B"), + RawCollider(3, "ACA"), + RawCollider(4, "ACB"), + RawCollider(5, "ACAD"), + RawCollider(6, "ACAD"), + ] + if MemoryLayout.size == 8 { + // Cut testing workload down a bit on 32-bit systems. In practice a 32-bit Int + // usually means we're running on a watchOS device (arm64_32), and those are relatively slow + // to run these. + testItems += [ + RawCollider(7, "ACAEB"), + RawCollider(8, "ACAEB"), + RawCollider(9, "ACAEB"), + ] + } + #if false // Enable for even deeper testing + testItems += [ + RawCollider(10, "ACAEB"), + RawCollider(11, "ADAD"), + RawCollider(12, "ACC"), + ] + #endif + return testItems +}() extension LifetimeTracker { func shareableDictionary( @@ -106,12 +120,35 @@ extension LifetimeTracker { /// the same order as we expect a preorder walk would visit them in the /// resulting tree. The resulting ordering is then used to insert key/value /// pairs into the map, with sequentially increasing keys. -let _fixtures: KeyValuePairs = [ - "empty": [], - "single-item": [ - "A" - ], - "single-node": [ +let fixtures: [Fixture] = { + var fixtures: Array = [] + + enum FixtureFlavor { + case any + case small // 32-bit platforms + case large // 64-bit platforms + + func isAllowed() -> Bool { + let reject: FixtureFlavor +#if arch(i386) || arch(arm64_32) + reject = .large +#else + precondition(MemoryLayout.size == 8, "Unknown platform") + reject = .small +#endif + return self != reject + } + } + + func add(_ title: String, flavor: FixtureFlavor = .any, _ contents: [String]) { + // Ignore unsupported flavors + guard flavor.isAllowed() else { return } + fixtures.append(Fixture(title: title, contents: contents)) + } + + add("empty", []) + add("single-item", ["A"]) + add("single-node", [ "0", "1", "2", @@ -121,26 +158,28 @@ let _fixtures: KeyValuePairs = [ "B", "C", "D", - ], - "few-collisions": [ + ]) + add("few-collisions", [ "42*5" - ], - "many-collisions": [ + ]) + add("many-collisions", [ "42*40" - ], - "few-different-collisions": [ + ]) + + add("few-different-collisions", [ "1*3", "21*3", "22*3", "3*3", - ], - "everything-on-the-2nd-level": [ + ]) + + add("everything-on-the-2nd-level", [ "00", "01", "02", "03", "04", "10", "11", "12", "13", "14", "20", "21", "22", "23", "24", "30", "31", "32", "33", "34", - ], - "two-levels-mixed": [ + ]) + add("two-levels-mixed", [ "00", "01", "2", "30", "33", @@ -151,64 +190,65 @@ let _fixtures: KeyValuePairs = [ "8", "94", "98", "9A", "A3", "A4", - ], - "vee": [ + ]) + add("vee", [ "11110", "11115", "11119", "1111B", "66664", "66667", - ], - "fork": [ + ]) + + add("fork", [ "31110", "31115", "31119", "3111B", "36664", "36667", - ], - "chain-left": [ + ]) + add("chain-left", [ "0", "10", "110", "1110", "11110", "11111", - ], - "chain-right": [ + ]) + add("chain-right", [ "1", "01", "001", "0001", "00001", "000001", - ], - "expansion0": [ - "00000001*3", - "00001", - ], - "expansion1": [ - "00000001*3", + ]) + add("expansion0", [ + "000001*3", + "0001", + ]) + add("expansion1", [ + "000001*3", "01", - "00001", - ], - "expansion2": [ - "11111111*3", + "0001", + ]) + add("expansion2", [ + "111111*3", "10", - "11110", - ], - "expansion3": [ + "1110", + ]) + add("expansion3", [ "01", - "00001", - "00000001*3", - ], - "expansion4": [ + "0001", + "000001*3", + ]) + add("expansion4", [ "10", - "11110", - "11111111*3", - ], - "nested": [ + "1110", + "111111*3", + ]) + add("nested", flavor: .large, [ "50", "51", "520", @@ -243,24 +283,21 @@ let _fixtures: KeyValuePairs = [ "5224", "53", "54", - ], - "deep": [ + ]) + add("deep", [ "0", - + // Deeply nested children with only the leaf containing items - "1234560", - "1234561", - "1234562", - "1234563", - + "123450", + "123451", + "123452", + "123453", + "22", "25", - ], -] - -let fixtures: [Fixture] = _fixtures.map { - Fixture(title: $0, contents: $1) -} + ]) + return fixtures +}() struct Fixture { let title: String @@ -280,20 +317,20 @@ struct Fixture { var items: [(path: String, item: RawCollider)] = [] var seen: Set = [] - for var path in contents { + for path in contents { if let i = path.unicodeScalars.firstIndex(of: "*") { // We need to extend the path of collisions with zeroes to // make sure they sort correctly. let p = String(path.unicodeScalars.prefix(upTo: i)) guard let count = Int(path.suffix(from: i).dropFirst(), radix: 10) else { fatalError("Invalid item: '\(path)'") } - path = normalized(p) + let path = normalized(p) let hash = Hash(path)! for _ in 0 ..< count { items.append((path, RawCollider(items.count, hash))) } } else { - path = normalized(path) + let path = normalized(path) let hash = Hash(path)! items.append((path, RawCollider(items.count, hash))) } diff --git a/Tests/HashTreeCollectionsTests/TreeSet Tests.swift b/Tests/HashTreeCollectionsTests/TreeSet Tests.swift index 5ce7cc88..aa3f675e 100644 --- a/Tests/HashTreeCollectionsTests/TreeSet Tests.swift +++ b/Tests/HashTreeCollectionsTests/TreeSet Tests.swift @@ -87,11 +87,11 @@ class TreeSetTests: CollectionTestCase { func test_descriptions() { let empty: TreeSet = [] expectEqual(empty.description, "[]") - expectEqual(empty.debugDescription, "TreeSet([])") + expectEqual(empty.debugDescription, "[]") let a: TreeSet = ["a"] - expectEqual(a.description, "[a]") - expectEqual(a.debugDescription, "TreeSet([\"a\"])") + expectEqual(a.description, #"["a"]"#) + expectEqual(a.debugDescription, #"["a"]"#) } func test_index_descriptions() { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 57c7516e..ddc969f0 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -866,16 +866,13 @@ class OrderedDictionaryTests: CollectionTestCase { func test_CustomDebugStringConvertible() { let a: OrderedDictionary = [:] - expectEqual(a.debugDescription, - "OrderedDictionary([:])") + expectEqual(a.debugDescription, "[:]") let b: OrderedDictionary = [0: 1] - expectEqual(b.debugDescription, - "OrderedDictionary([0: 1])") + expectEqual(b.debugDescription, "[0: 1]") let c: OrderedDictionary = [0: 1, 2: 3, 4: 5] - expectEqual(c.debugDescription, - "OrderedDictionary([0: 1, 2: 3, 4: 5])") + expectEqual(c.debugDescription, "[0: 1, 2: 3, 4: 5]") } func test_CustomReflectable() { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift index 0ea74f77..d8c1d395 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -99,16 +99,13 @@ class OrderedDictionaryElementsTests: CollectionTestCase { func test_CustomDebugStringConvertible() { let a: OrderedDictionary = [:] - expectEqual(a.elements.debugDescription, - "OrderedDictionary.Elements([:])") + expectEqual(a.elements.debugDescription, "[:]") let b: OrderedDictionary = [0: 1] - expectEqual(b.elements.debugDescription, - "OrderedDictionary.Elements([0: 1])") + expectEqual(b.elements.debugDescription, "[0: 1]") let c: OrderedDictionary = [0: 1, 2: 3, 4: 5] - expectEqual(c.elements.debugDescription, - "OrderedDictionary.Elements([0: 1, 2: 3, 4: 5])") + expectEqual(c.elements.debugDescription, "[0: 1, 2: 3, 4: 5]") } func test_SubSequence_descriptions() { @@ -119,10 +116,8 @@ class OrderedDictionaryElementsTests: CollectionTestCase { let s = d.elements[0 ..< 1] - expectEqual(s.description, "[a: 1]") - expectEqual( - s.debugDescription, - "OrderedDictionary.Elements.SubSequence([\"a\": 1])") + expectEqual(s.description, #"["a": 1]"#) + expectEqual(s.debugDescription, #"["a": 1]"#) } func test_customReflectable() { diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift index ea2a739f..a65d3ff9 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift @@ -35,9 +35,7 @@ class OrderedDictionaryValueTests: CollectionTestCase { ] expectEqual(d.values.description, "[1, 2]") - expectEqual( - d.values.debugDescription, - "OrderedDictionary.Keys([1, 2])") + expectEqual(d.values.debugDescription, "[1, 2]") } func test_values_RandomAccessCollection() { diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index c745ea79..7d4c90ba 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -147,13 +147,13 @@ class OrderedSetTests: CollectionTestCase { func test_CustomDebugStringConvertible() { let a: OrderedSet = [] - expectEqual(a.debugDescription, "OrderedSet([])") + expectEqual(a.debugDescription, "[]") let b: OrderedSet = [0] - expectEqual(b.debugDescription, "OrderedSet([0])") + expectEqual(b.debugDescription, "[0]") let c: OrderedSet = [0, 1, 2, 3, 4] - expectEqual(c.debugDescription, "OrderedSet([0, 1, 2, 3, 4])") + expectEqual(c.debugDescription, "[0, 1, 2, 3, 4]") } func test_SubSequence_descriptions() { @@ -162,10 +162,7 @@ class OrderedSetTests: CollectionTestCase { let slice = s[1 ..< 3] expectEqual(slice.description, "[1, 2]") - expectEqual( - slice.debugDescription, - "OrderedSet.SubSequence([1, 2])") - + expectEqual(slice.debugDescription, "[1, 2]") } func test_customReflectable() { diff --git a/Tests/RopeModuleTests/SampleStrings.swift b/Tests/RopeModuleTests/SampleStrings.swift index 1f93619d..78d851fb 100644 --- a/Tests/RopeModuleTests/SampleStrings.swift +++ b/Tests/RopeModuleTests/SampleStrings.swift @@ -27,7 +27,8 @@ func randomStride( }) } -let sampleString = #""" +let sampleString: String = { + var str = #""" 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 \# @@ -58,10 +59,16 @@ let sampleString = #""" ¯\_(ツ)_/¯ ಠ_ಠ - 🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦\# + 🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦 + """# + if MemoryLayout.size == 8 { + /// Add even more flags and extra long combining sequences. This considerably increases test + /// workload. (Not necessarily due to grapheme cluster length, but because test performance is + /// quadratic or worse in the size of the overall text.) + str += #""" 🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦\# 🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦🇺🇸🇨🇦 - + 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̵̤̽ṷ̴͇̎͘ń̷͓̒!̷͍̾̚ @@ -70,9 +77,12 @@ 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̸.̵ """# + } + return str +}() let shortSample = #""" - Swift 👨‍👨‍👧‍👧 简洁 c̴̭̈͘ǫ̷̯͋̊d̸͖̩̈̈́ḛ̴́ 🇺🇸🇨🇦🇺🇸 코드 + Swift 👨‍👨‍👧‍👧简c̴̭̈͘ǫ̷̯͋̊d̸͖̩̈̈́ḛ̴́🇺🇸🇨🇦🇺🇸코 """# let sampleString2 = diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index fd0f6306..3fdbfd71 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -38,44 +38,44 @@ class TestBigString: CollectionTestCase { let min = BigString._minimumCapacity let max = BigString._maximumCapacity - XCTAssertLessThanOrEqual(min, max) + expectLessThanOrEqual(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) + expectGreaterThanOrEqual(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.startIndex.utf8Offset, 0) + expectEqual(s.count, 0) + expectEqual(s.unicodeScalars.count, 0) + expectEqual(s.utf16.count, 0) + expectEqual(s.utf8.count, 0) + expectTrue(s.isEmpty) + expectEqual(s.startIndex, s.endIndex) + expectEqual(s.startIndex.utf8Offset, 0) - XCTAssertEqual(String(s), "") - XCTAssertEqual(String(s[...]), "") + expectEqual(String(s), "") + expectEqual(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) + expectEqual(a, b) + expectNotEqual(a.unicodeScalars, b.unicodeScalars) + expectNotEqual(a.utf8, b.utf8) + expectNotEqual(a.utf16, b.utf16) } func test_descriptions() { let s: BigString = "Café" - XCTAssertEqual(s.description, "Café") - XCTAssertEqual(s.unicodeScalars.description, "Café") + expectEqual(s.description, "Café") + expectEqual(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>") + expectEqual(s.utf8.description, "<43 61 66 C3 A9>") + expectEqual(s.utf16.description, "<0043 0061 0066 00E9>") #endif } @@ -83,13 +83,13 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(big.count, sampleString.count) + expectEqual(big.unicodeScalars.count, sampleString.unicodeScalars.count) + expectEqual(big.utf16.count, sampleString.utf16.count) + expectEqual(big.utf8.count, sampleString.utf8.count) let flat = String(big) - XCTAssertEqual(flat, sampleString) + expectEqual(flat, sampleString) } func testUTF8View() { @@ -148,7 +148,7 @@ class TestBigString: CollectionTestCase { let a = it1.next() let b = it2.next() guard a == b else { - XCTAssertEqual(a, b) + expectEqual(a, b) break } if a == nil { break } @@ -162,7 +162,7 @@ class TestBigString: CollectionTestCase { } ) - XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + expectEqual(indices2.count, indices1.count, file: file, line: line) let c = min(indices1.count, indices2.count) @@ -172,7 +172,7 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } for i in 0 ..< c { @@ -180,7 +180,7 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } return (indices1, indices2) } @@ -198,7 +198,7 @@ class TestBigString: CollectionTestCase { let a = it1.next() let b = it2.next() guard a == b else { - XCTAssertEqual(a, b) + expectEqual(a, b) break } if a == nil { break } @@ -212,7 +212,7 @@ class TestBigString: CollectionTestCase { } ) - XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + expectEqual(indices2.count, indices1.count, file: file, line: line) let c = min(indices1.count, indices2.count) @@ -222,7 +222,7 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } for i in 0 ..< c { @@ -230,7 +230,7 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } return (indices1, indices2) } @@ -248,7 +248,7 @@ class TestBigString: CollectionTestCase { let a = it1.next() let b = it2.next() guard a == b else { - XCTAssertEqual(a, b) + expectEqual(a, b) break } if a == nil { break } @@ -262,7 +262,7 @@ class TestBigString: CollectionTestCase { } ) - XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + expectEqual(indices2.count, indices1.count, file: file, line: line) let c = min(indices1.count, indices2.count) @@ -272,7 +272,7 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } for i in 0 ..< c { @@ -280,7 +280,7 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } return (indices1, indices2) } @@ -298,7 +298,7 @@ class TestBigString: CollectionTestCase { let a = it1.next() let b = it2.next() guard a == b else { - XCTAssertEqual(a, b) + expectEqual(a, b) break } if a == nil { break } @@ -312,7 +312,7 @@ class TestBigString: CollectionTestCase { } ) - XCTAssertEqual(indices2.count, indices1.count, file: file, line: line) + expectEqual(indices2.count, indices1.count, file: file, line: line) let c = min(indices1.count, indices2.count) @@ -322,7 +322,7 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(c1, c2, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } for i in 0 ..< c { @@ -330,7 +330,7 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(d2, d1, "i: \(i), i1: \(i1._description), i2: \(i2)", file: file, line: line) } return (indices1, indices2) } @@ -338,44 +338,44 @@ class TestBigString: CollectionTestCase { 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()) + expectEqual(it.next(), "C") + expectEqual(it.next(), "a") + expectEqual(it.next(), "f") + expectEqual(it.next(), "e\u{301}") + expectEqual(it.next(), " ") + expectEqual(it.next(), "👩‍👩‍👧") + expectNil(it.next()) let flat = sampleString let big = BigString(flat) let c1 = Array(flat) let c2 = Array(big) - XCTAssertEqual(c1, c2) + expectEqual(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()) + expectEqual(it.next(), "C") + expectEqual(it.next(), "a") + expectEqual(it.next(), "f") + expectEqual(it.next(), "e") + expectEqual(it.next(), "\u{301}") + expectEqual(it.next(), " ") + expectEqual(it.next(), "👩") + expectEqual(it.next(), "\u{200D}") + expectEqual(it.next(), "👩") + expectEqual(it.next(), "\u{200D}") + expectEqual(it.next(), "👧") + expectNil(it.next()) let flat = sampleString let big = BigString(flat) let c1 = Array(flat.unicodeScalars) let c2 = Array(big.unicodeScalars) - XCTAssertEqual(c1, c2) + expectEqual(c1, c2) } func test_iterator_utf8() { @@ -384,7 +384,7 @@ class TestBigString: CollectionTestCase { let c1 = Array(flat.utf8) let c2 = Array(big.utf8) - XCTAssertEqual(c1, c2) + expectEqual(c1, c2) } func test_iterator_utf16() { @@ -393,7 +393,7 @@ class TestBigString: CollectionTestCase { let c1 = Array(flat.utf16) let c2 = Array(big.utf16) - XCTAssertEqual(c1, c2) + expectEqual(c1, c2) } func test_indices_character() { @@ -411,10 +411,10 @@ class TestBigString: CollectionTestCase { let i2 = indices2[i] let j2 = big.index(i2, offsetBy: j - i) - XCTAssertEqual(big.index(roundingDown: i2), i2) - XCTAssertEqual(big.index(roundingDown: j2), j2) + expectEqual(big.index(roundingDown: i2), i2) + expectEqual(big.index(roundingDown: j2), j2) let b = String(big[i2 ..< j2]) - XCTAssertEqual(b, a) + expectEqual(b, a) } } } @@ -432,11 +432,11 @@ class TestBigString: CollectionTestCase { let i2 = indices2[i] let j2 = big.unicodeScalars.index(i2, offsetBy: j - i) - XCTAssertEqual(big.unicodeScalars.index(roundingDown: i2), i2) - XCTAssertEqual(big.unicodeScalars.index(roundingDown: j2), j2) + expectEqual(big.unicodeScalars.index(roundingDown: i2), i2) + expectEqual(big.unicodeScalars.index(roundingDown: j2), j2) let slice = big.unicodeScalars[i2 ..< j2] let b = String(slice) - XCTAssertEqual(b, a) + expectEqual(b, a) } } } @@ -454,11 +454,11 @@ class TestBigString: 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) + expectEqual(big.utf16.index(roundingDown: i2), i2) + expectEqual(big.utf16.index(roundingDown: j2), j2) let b = big.utf16[i2 ..< j2] - XCTAssertEqual(b.first, a.first) - XCTAssertEqual(b.last, a.last) + expectEqual(b.first, a.first) + expectEqual(b.last, a.last) } } } @@ -476,11 +476,11 @@ class TestBigString: 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) + expectEqual(big.utf8.index(roundingDown: i2), i2) + expectEqual(big.utf8.index(roundingDown: j2), j2) let b = big.utf8[i2 ..< j2] - XCTAssertEqual(b.first, a.first) - XCTAssertEqual(b.last, a.last) + expectEqual(b.first, a.first) + expectEqual(b.last, a.last) } } } @@ -496,14 +496,14 @@ class TestBigString: CollectionTestCase { let next = String(flat[i ..< j]) big.append(contentsOf: next) //big.invariantCheck() - //XCTAssertEqual(String(big)[...], s[..= current { current = str.index(after: current) } } - XCTAssertEqual(current, str.endIndex, "end", file: file, line: line) + expectEqual(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.index(roundingDown: str.endIndex), str.endIndex) + expectEqual(str.index(roundingDown: str.endIndex), str.endIndex) } @@ -808,8 +808,8 @@ class TestBigString: CollectionTestCase { next = str.unicodeScalars.index(after: current) } let j = str.unicodeScalars.index(roundingDown: i) - XCTAssertEqual(j, current, "\(i)", file: file, line: line) - XCTAssertEqual(str.unicodeScalars[i], str.unicodeScalars[j], "i: \(i)", file: file, line: line) + expectEqual(j, current, "\(i)", file: file, line: line) + expectEqual(str.unicodeScalars[i], str.unicodeScalars[j], "i: \(i)", file: file, line: line) } } @@ -817,7 +817,7 @@ class TestBigString: CollectionTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.unicodeScalars.index(roundingDown: str.endIndex), str.endIndex) + expectEqual(str.unicodeScalars.index(roundingDown: str.endIndex), str.endIndex) } func testUnicodeScalarIndexRoundingUp() { @@ -835,7 +835,7 @@ class TestBigString: CollectionTestCase { current = str.unicodeScalars.index(after: current) } let j = str.unicodeScalars.index(roundingUp: i) - XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + expectEqual(j, current, "i: \(i)", file: file, line: line) } } @@ -843,7 +843,7 @@ class TestBigString: CollectionTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.unicodeScalars.index(roundingDown: str.endIndex), str.endIndex) + expectEqual(str.unicodeScalars.index(roundingDown: str.endIndex), str.endIndex) } func testUTF8IndexRoundingDown() { @@ -863,8 +863,8 @@ class TestBigString: CollectionTestCase { 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) + expectEqual(j, current, "i: \(i)", file: file, line: line) + expectEqual(str.utf8[i], str.utf8[j], "i: \(i)", file: file, line: line) } } @@ -872,7 +872,7 @@ class TestBigString: CollectionTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.utf8.index(roundingDown: str.endIndex), str.endIndex) + expectEqual(str.utf8.index(roundingDown: str.endIndex), str.endIndex) } func testUTF8IndexRoundingUp() { @@ -890,7 +890,7 @@ class TestBigString: CollectionTestCase { current = str.utf8.index(after: current) } let j = str.utf8.index(roundingUp: i) - XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + expectEqual(j, current, "i: \(i)", file: file, line: line) } } @@ -898,7 +898,7 @@ class TestBigString: CollectionTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.utf8.index(roundingDown: str.endIndex), str.endIndex) + expectEqual(str.utf8.index(roundingDown: str.endIndex), str.endIndex) } func testUTF16IndexRoundingDown() { @@ -923,11 +923,11 @@ class TestBigString: CollectionTestCase { } let j = str.utf16.index(roundingDown: i) if UTF16.isTrailSurrogate(str.utf16[i]) { - XCTAssertEqual(j, i, "i: \(i)", file: file, line: line) + expectEqual(j, i, "i: \(i)", file: file, line: line) } else { - XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + expectEqual(j, current, "i: \(i)", file: file, line: line) } - XCTAssertEqual(str.utf16[i], str.utf16[j], "i: \(i)", file: file, line: line) + expectEqual(str.utf16[i], str.utf16[j], "i: \(i)", file: file, line: line) } } @@ -935,7 +935,7 @@ class TestBigString: CollectionTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.utf16.index(roundingDown: str.endIndex), str.endIndex) + expectEqual(str.utf16.index(roundingDown: str.endIndex), str.endIndex) } func testUTF1t6IndexRoundingUp() { @@ -953,7 +953,7 @@ class TestBigString: CollectionTestCase { current = str.utf8.index(after: current) } let j = str.utf8.index(roundingUp: i) - XCTAssertEqual(j, current, "i: \(i)", file: file, line: line) + expectEqual(j, current, "i: \(i)", file: file, line: line) } } @@ -961,36 +961,36 @@ class TestBigString: CollectionTestCase { check(str.utf16.indices) check(str.unicodeScalars.indices) check(str.indices) - XCTAssertEqual(str.utf8.index(roundingDown: str.endIndex), str.endIndex) + expectEqual(str.utf8.index(roundingDown: str.endIndex), str.endIndex) } func testSubstringMutationIndexRounding() { let b1: BigString = "Foobar" var s1 = b1.suffix(3) - XCTAssertEqual(s1, "bar") + expectEqual(s1, "bar") s1.insert("\u{308}", at: s1.startIndex) // Combining diaresis - XCTAssertEqual(s1.base, "Foöbar") - XCTAssertEqual(s1, "öbar") + expectEqual(s1.base, "Foöbar") + expectEqual(s1, "öbar") let b2: BigString = "Foo👩👧bar" // WOMAN, GIRL var s2: BigSubstring = b2.prefix(4) - XCTAssertEqual(s2, "Foo👩") + expectEqual(s2, "Foo👩") s2.append("\u{200d}") // ZWJ - XCTAssertEqual(s2, "Foo") - XCTAssertEqual(s2.base, "Foo👩‍👧bar") // family with mother and daughter + expectEqual(s2, "Foo") + expectEqual(s2.base, "Foo👩‍👧bar") // family with mother and daughter let b3: BigString = "Foo🇺🇸🇨🇦🇺🇸🇨🇦bar" // Regional indicators "USCAUSCA" var s3: BigSubstring = b3.prefix(6) - XCTAssertEqual(s3, "Foo🇺🇸🇨🇦🇺🇸") + expectEqual(s3, "Foo🇺🇸🇨🇦🇺🇸") s3.insert("\u{1f1ed}", at: s3.index(s3.startIndex, offsetBy: 3)) // Regional indicator "H" - XCTAssertEqual(s3, "Foo🇭🇺🇸🇨🇦🇺") // Regional indicators "HUSCAUSCA" - XCTAssertEqual(s3.base, "Foo🇭🇺🇸🇨🇦🇺🇸🇨\u{1f1e6}bar") + expectEqual(s3, "Foo🇭🇺🇸🇨🇦🇺") // Regional indicators "HUSCAUSCA" + expectEqual(s3.base, "Foo🇭🇺🇸🇨🇦🇺🇸🇨\u{1f1e6}bar") } func test_unicodeScalars_mutations() { let b1: BigString = "Foo👩👧bar" // WOMAN, GIRL var s1 = b1.prefix(4) - XCTAssertEqual(s1, "Foo👩") + expectEqual(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) { @@ -998,38 +998,38 @@ class TestBigString: CollectionTestCase { } mutate(&s1.unicodeScalars) { view in view.append("\u{200d}") // ZWJ - XCTAssertEqual(view, "Foo👩\u{200d}") + expectEqual(view, "Foo👩\u{200d}") } - XCTAssertEqual(s1, "Foo") - XCTAssertEqual(s1.base, "Foo👩‍👧bar") + expectEqual(s1, "Foo") + expectEqual(s1.base, "Foo👩‍👧bar") } func test_ExpressibleByStringLiteral_and_CustomStringConvertible() { let a: BigString = "foobar" - XCTAssertEqual(a.description, "foobar") - XCTAssertEqual(a.debugDescription, "\"foobar\"") + expectEqual(a.description, "foobar") + expectEqual(a.debugDescription, "\"foobar\"") let b: BigSubstring = "foobar" - XCTAssertEqual(b.description, "foobar") - XCTAssertEqual(b.debugDescription, "\"foobar\"") + expectEqual(b.description, "foobar") + expectEqual(b.debugDescription, "\"foobar\"") let c: BigString.UnicodeScalarView = "foobar" - XCTAssertEqual(c.description, "foobar") - XCTAssertEqual(c.debugDescription, "\"foobar\"") + expectEqual(c.description, "foobar") + expectEqual(c.debugDescription, "\"foobar\"") let d: BigSubstring.UnicodeScalarView = "foobar" - XCTAssertEqual(d.description, "foobar") - XCTAssertEqual(d.debugDescription, "\"foobar\"") + expectEqual(d.description, "foobar") + expectEqual(d.debugDescription, "\"foobar\"") } func testCharacterwiseEquality() { let cafe1: BigString = "Cafe\u{301}" let cafe2: BigString = "Café" - XCTAssertEqual(cafe1, cafe2) - XCTAssertNotEqual(cafe1.unicodeScalars, cafe2.unicodeScalars) - XCTAssertNotEqual(cafe1.utf8, cafe2.utf8) - XCTAssertNotEqual(cafe1.utf16, cafe2.utf16) + expectEqual(cafe1, cafe2) + expectNotEqual(cafe1.unicodeScalars, cafe2.unicodeScalars) + expectNotEqual(cafe1.utf8, cafe2.utf8) + expectNotEqual(cafe1.utf16, cafe2.utf16) } } #endif diff --git a/Tests/RopeModuleTests/TestRope.swift b/Tests/RopeModuleTests/TestRope.swift index 901bfe41..3e949d31 100644 --- a/Tests/RopeModuleTests/TestRope.swift +++ b/Tests/RopeModuleTests/TestRope.swift @@ -114,18 +114,19 @@ struct Chunk: RopeElement, Equatable, CustomStringConvertible { } } -class TestRope: XCTestCase { +class TestRope: CollectionTestCase { override func setUp() { + super.setUp() print("Global seed: \(RepeatableRandomNumberGenerator.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) + expectTrue(empty.isEmpty) + expectEqual(empty.count, 0) + expectTrue(empty.summary.isZero) + expectEqual(empty.startIndex, empty.endIndex) } func test_build() { @@ -143,9 +144,9 @@ class TestRope: XCTestCase { let actualSum = rope.summary let expectedSum: Chunk.Summary = ref.reduce(into: .zero) { $0.add($1.summary) } - XCTAssertEqual(actualSum, expectedSum) + expectEqual(actualSum, expectedSum) - XCTAssertTrue(rope.elementsEqual(ref)) + expectTrue(rope.elementsEqual(ref)) } func test_iteration() { @@ -159,15 +160,15 @@ class TestRope: XCTestCase { var i = 0 while let next = it.next() { let expected = ref[i] - XCTAssertEqual(next, expected) + expectEqual(next, expected) guard next == expected else { break } i += 1 } - XCTAssertEqual(i, ref.count) + expectEqual(i, ref.count) let expectedLength = ref.reduce(into: 0) { $0 += $1.length } let actualLength = rope.reduce(into: 0) { $0 += $1.length } - XCTAssertEqual(actualLength, expectedLength) + expectEqual(actualLength, expectedLength) } } @@ -177,17 +178,17 @@ class TestRope: XCTestCase { Chunk(length: ($0 % 4) + 1, value: $0) } let rope = Rope(ref) - XCTAssertTrue(rope.elementsEqual(ref)) + expectTrue(rope.elementsEqual(ref)) var i = rope.startIndex var j = 0 while i != rope.endIndex, j != ref.count { - XCTAssertEqual(rope[i], ref[j]) + expectEqual(rope[i], ref[j]) i = rope.index(after: i) j += 1 } - XCTAssertEqual(i, rope.endIndex) - XCTAssertEqual(j, ref.count) + expectEqual(i, rope.endIndex) + expectEqual(j, ref.count) } } @@ -197,7 +198,7 @@ class TestRope: XCTestCase { Chunk(length: ($0 % 4) + 1, value: $0) } let rope = Rope(ref) - XCTAssertTrue(rope.elementsEqual(ref)) + expectTrue(rope.elementsEqual(ref)) var indices: [Rope.Index] = [] var i = rope.startIndex @@ -208,7 +209,7 @@ class TestRope: XCTestCase { while let j = indices.popLast() { i = rope.index(before: i) - XCTAssertEqual(i, j) + expectEqual(i, j) } } } @@ -222,7 +223,7 @@ class TestRope: XCTestCase { let rope = Rope(ref) let indices = Array(rope.indices) + [rope.endIndex] - XCTAssertEqual(indices.count, c + 1) + expectEqual(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()) @@ -230,11 +231,33 @@ class TestRope: XCTestCase { i <= j ? ref[i..(chunks) + let ref = chunks.flatMap { Array(repeating: $0.value, count: $0.length) } + + for i in 0 ..< ref.count { + let (index, remaining) = rope.find(at: i, in: Chunk.Metric(), preferEnd: false) + let chunk = rope[index] + expectEqual(chunk.value, ref[i]) + let pos = ref[..(ref) let indices = Array(rope.indices) + [rope.endIndex] - XCTAssertEqual(indices.count, c + 1) + expectEqual(indices.count, c + 1) for i in indices.indices { for j in indices.indices { let d = ( @@ -252,8 +275,8 @@ class TestRope: XCTestCase { ? ref[i.. [Chunk] { @@ -452,10 +475,18 @@ class TestRope: XCTestCase { _ y: [Int], file: StaticString = #file, line: UInt = #line + ) { + checkEqual(x, chunkify(y), file: file, line: line) + } + + func checkEqual( + _ x: Rope, + _ y: [Chunk], + file: StaticString = #file, + line: UInt = #line ) { let u = Array(x) - let v = chunkify(y) - XCTAssertEqual(u, v, file: file, line: line) + expectEqual(u, y, file: file, line: line) } func checkRemoveSubrange( @@ -475,6 +506,9 @@ class TestRope: XCTestCase { func test_removeSubrange_simple() { var rope = Rope() + + checkRemoveSubrange(rope, [], range: 0 ..< 0) + for i in 0 ..< 10 { rope.append(Chunk(length: 10, value: i)) } @@ -524,7 +558,6 @@ class TestRope: XCTestCase { checkRemoveSubrange(rope, ref, range: 1 ..< 99) checkRemoveSubrange(rope, ref, range: 1 ..< 59) checkRemoveSubrange(rope, ref, range: 61 ..< 99) - } func test_removeSubrange_larger() { @@ -573,4 +606,65 @@ class TestRope: XCTestCase { } } + func test_replaceSubrange_simple() { + let ranges: [Range] = [ + // Basics + 0 ..< 0, 30 ..< 30, 0 ..< 100, + // Whole individual chunks + 90 ..< 100, 0 ..< 10, 30 ..< 40, 70 ..< 80, + // Prefixes of single chunks + 0 ..< 1, 30 ..< 35, 60 ..< 66, 90 ..< 98, + + // Suffixes of single chunks + 9 ..< 10, 35 ..< 40, 64 ..< 70, 98 ..< 100, + + // Neighboring couple of whole chunks + 0 ..< 20, 80 ..< 100, 10 ..< 30, + 50 ..< 70, // Crosses nodes! + + // Longer whole chunk sequences + 0 ..< 30, 70 ..< 90, + 0 ..< 60, // entire first node + 60 ..< 100, // entire second node + 40 ..< 70, // crosses into second node + 10 ..< 90, // crosses into second node + + // Arbitrary cuts + 0 ..< 69, 42 ..< 73, 21 ..< 89, 1 ..< 99, 1 ..< 59, 61 ..< 99, + ] + + let replacements: [[Chunk]] = [ + [], + [-1], + Array(repeating: -1, count: 10), + Array(repeating: -1, count: 100), + ].map { chunkify($0) } + + let rope: Rope = { + var rope = Rope() + for i in 0 ..< 10 { + rope.append(Chunk(length: 10, value: i)) + } + return rope + }() + let ref = (0 ..< 10).flatMap { Array(repeating: $0, count: 10) } + + withEvery("replacement", in: replacements) { replacement in + var rope = Rope() + rope.replaceSubrange(0 ..< 0, in: Chunk.Metric(), with: replacement) + checkEqual(rope, replacement) + } + + withEvery("replacement", in: replacements) { replacement in + withEvery("range", in: ranges) { range in + var expected = ref + expected.removeSubrange(range) + + var actual = rope + actual.removeSubrange(range, in: Chunk.Metric()) + + checkEqual(actual, expected) + } + } + } } diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift index 11b7aa31..4997cacf 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift @@ -179,7 +179,7 @@ extension MinimalDecoder.KeyedContainer: KeyedDecodingContainerProtocol { return input[key.stringValue] != nil } - func _decode(key: Key) throws -> Value { + func _decode(key: K) throws -> Value { expectTrue(isValid, "Container isn't valid", trapping: true) commitPendingContainer() guard let value = input[key.stringValue] else { diff --git a/Xcode/Collections.xcconfig b/Xcode/Collections.xcconfig index 13193a67..e6ed4fd3 100644 --- a/Xcode/Collections.xcconfig +++ b/Xcode/Collections.xcconfig @@ -38,4 +38,6 @@ ENABLE_TESTABILITY = NO ENABLE_TESTABILITY[config=Debug] = YES GENERATE_INFOPLIST_FILE = YES + CODE_SIGN_STYLE = Automatic +CODE_SIGN_IDENTITY = - diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index adec5dde..38b1e44e 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -281,7 +281,7 @@ 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 */; }; + 7DE9215D29CA70F4004483EB /* _HashNodeHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91FE629CA70F3004483EB /* _HashNodeHeader.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 */; }; @@ -731,7 +731,7 @@ 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 = ""; }; + 7DE91FE629CA70F3004483EB /* _HashNodeHeader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _HashNodeHeader.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 = ""; }; @@ -1457,7 +1457,7 @@ 7DE91FDE29CA70F3004483EB /* _RawHashNode+UnsafeHandle.swift */, 7DE91FCF29CA70F3004483EB /* _HashSlot.swift */, 7DE91FCB29CA70F3004483EB /* _HashStack.swift */, - 7DE91FE629CA70F3004483EB /* _StorageHeader.swift */, + 7DE91FE629CA70F3004483EB /* _HashNodeHeader.swift */, 7DE91FD929CA70F3004483EB /* _UnmanagedHashNode.swift */, 7DE91FE829CA70F3004483EB /* _UnsafePath.swift */, ); @@ -2055,7 +2055,7 @@ 7DE920EC29CA70F4004483EB /* BitArray+Collection.swift in Sources */, 7DE9201729CA70F3004483EB /* OrderedDictionary+Codable.swift in Sources */, 7DE9208329CA70F4004483EB /* BigString+CustomDebugStringConvertible.swift in Sources */, - 7DE9215D29CA70F4004483EB /* _StorageHeader.swift in Sources */, + 7DE9215D29CA70F4004483EB /* _HashNodeHeader.swift in Sources */, 7DE9213329CA70F4004483EB /* TreeSet+Collection.swift in Sources */, 7DE9217929CA70F4004483EB /* Heap+UnsafeHandle.swift in Sources */, 7DE920BC29CA70F4004483EB /* _UniqueCollection.swift in Sources */, diff --git a/Xcode/CollectionsTests.xcconfig b/Xcode/CollectionsTests.xcconfig index 8c257edc..5c7e65de 100644 --- a/Xcode/CollectionsTests.xcconfig +++ b/Xcode/CollectionsTests.xcconfig @@ -24,7 +24,9 @@ CURRENT_PROJECT_VERSION = 1 MARKETING_VERSION = 1.0 GENERATE_INFOPLIST_FILE = YES + CODE_SIGN_STYLE = Automatic +CODE_SIGN_IDENTITY = - ENABLE_TESTABILITY = NO