Documentation refactors, polishes, and add SubSequences

Key Changes:
 - Add custom SubSequences
 - Custom SortedDictionary.(Keys|Values).Sequence iterator
 - Add SortedDictionary.modifyValue(forKey:default:_:)

Minor Changes:
 - Update documentation
 - Various API optimizations
 - Fix bug where offsetBy:limitedBy: calls did not validate indices
 - Remove unique initializers with documented duplicate handling behavior.
 - Implement _Node.UnsafeHandle.append*() methods
 - SortedSet no longer allocates a 'values' buffer (_Node.Header.values is now optional)

Documentation:
 - Complexity guarantees
   - BidirectionalCollection conformances
   - Sequence/IteratorProtocol methods

Optimizations:
 - Add optimized dictionary value mapping (through Node.init(mappingFrom:_:))
 - Custom _BTree.forEach
 - Greater explicit @inline(__always) annotations throughout.
 - Simplify _BTree: Sequence implementation
 - Move methods to using _BTree.Builder
 - _BTree.FixedSizeArray now uses `withUnsafePointer` to prevent branching.
This commit is contained in:
Vihan Bhargava committed 2021-08-09 19:14:19 -07:00
1 parent 21d9bde3ec
commit 0d0d66f671
29 files changed
+1546 -242

No files matched your search

@@ -11,12 +11,15 @@
extension SortedSet: BidirectionalCollection {
/// The number of elements in the sorted set.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var count: Int { self._root.count }
/// A Boolean value that indicates whether the set is empty.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var isEmpty: Bool { self._root.isEmpty }
@@ -25,12 +28,12 @@ extension SortedSet: BidirectionalCollection {
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: O(`log n`)
/// - Complexity: O(log(`self.count`))
@inlinable
@inline(__always)
public var startIndex: Index { Index(self._root.startIndex) }
/// The dictionary's "past the end" position---that is, the position one
/// The set's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
@@ -40,44 +43,133 @@ extension SortedSet: BidirectionalCollection {
@inline(__always)
public var endIndex: Index { Index(self._root.endIndex) }
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If end is equal to start, the result is zero.
/// - Returns: The distance between start and end. The result can be negative.
/// - Complexity: O(1)
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
start._index.ensureValid(forTree: self._root)
end._index.ensureValid(forTree: self._root)
return self._root.distance(from: start._index, to: end._index)
}
/// Replaces the given index with its successor.
///
/// - Parameter index: A valid index of the collection. `index` must be less than `endIndex`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
public func formIndex(after index: inout Index) {
index._index.ensureValid(forTree: self._root)
self._root.formIndex(after: &index._index)
}
/// Returns the position immediately after the given index.
///
/// - Parameter index: A valid index of the collection. `index` must be less than `endIndex`.
/// - Returns: The index value immediately after `index`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
public func index(after index: Index) -> Index {
index._index.ensureValid(forTree: self._root)
return Index(self._root.index(after: index._index))
}
/// Replaces the given index with its predecessor.
///
/// - Parameter index: A valid index of the collection. `index` must be greater
/// than `startIndex`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
public func formIndex(before index: inout Index) {
index._index.ensureValid(forTree: self._root)
self._root.formIndex(before: &index._index)
}
/// Returns the position immediately before the given index.
///
/// - Parameter index: A valid index of the collection. `index` must be greater
/// than `startIndex`.
/// - Returns: The index value immediately before `index`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
public func index(before index: Index) -> Index {
index._index.ensureValid(forTree: self._root)
return Index(self._root.index(before: index._index))
}
/// Offsets the given index by the specified distance.
///
/// The value passed as distance must not offset i beyond the bounds of the collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
public func formIndex(_ i: inout Index, offsetBy distance: Int) {
i._index.ensureValid(forTree: self._root)
self._root.formIndex(&i._index, offsetBy: distance)
}
/// Returns an index that is the specified distance from the given index.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - Returns: An index offset by `distance` from the index `i`. If `distance`
/// is positive, this is the same value as the result of `distance` calls to
/// `index(after:)`. If `distance` is negative, this is the same value as the
/// result of `abs(distance)` calls to `index(before:)`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
i._index.ensureValid(forTree: self._root)
return Index(self._root.index(i._index, offsetBy: distance))
}
/// Returns an index that is the specified distance from the given index, unless that distance is beyond
/// a given limiting index.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `distance > 0`, a limit that is less
/// than `i` has no effect. Likewise, if `distance < 0`, a limit that is greater than `i` has
/// no effect.
/// - Returns: An index offset by `distance` from the index `i`, unless that index would be
/// beyond `limit` in the direction of movement. In that case, the method returns `nil`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
i._index.ensureValid(forTree: self._root)
limit._index.ensureValid(forTree: self._root)
if let i = self._root.index(i._index, offsetBy: distance, limitedBy: limit._index) {
return Index(i)
} else {
return nil
}
}
/// Offsets the given index by the specified distance, or so that it equals the given limiting index.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `distance > 0`, a limit that is less
/// than `i` has no effect. Likewise, if `distance < 0`, a limit that is greater than `i` has
/// no effect.
/// - Returns: `true` if `i` has been offset by exactly `distance` steps without going beyond
/// `limit`; otherwise, `false`. When the return value is `false`, the value of `i` is
/// equal to `limit`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
internal func formIndex(_ i: inout Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool {
i._index.ensureValid(forTree: self._root)
limit._index.ensureValid(forTree: self._root)
return self._root.formIndex(&i._index, offsetBy: distance, limitedBy: limit._index)
}
}
@@ -9,30 +9,42 @@
//
//===----------------------------------------------------------------------===//
// TODO: add custom forEach?
// TODO: benchmark
extension SortedSet: Sequence {
@inlinable
@inline(__always)
public func forEach(_ body: (Element) throws -> Void) rethrows {
try self._root.forEach({ try body($0.key) })
}
/// An iterator over the elements of the sorted set
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _iterator: _Tree.Iterator
@inlinable
@inline(__always)
internal init(_base: SortedSet) {
self._iterator = _base._root.makeIterator()
}
/// Advances to the next element and returns it, or nil if no next element exists.
///
/// - Returns: The next element in the underlying sequence, if a next element exists;
/// otherwise, `nil`.
/// - Complexity: O(1) amortized over the entire sequence.
@inlinable
@inline(__always)
public mutating func next() -> Element? {
return self._iterator.next()?.key
}
}
/// Returns an iterator over the elements of the sorted dictionary.
/// Returns an iterator over the elements of the sorted set.
///
/// - Complexity: O(1)
/// - Complexity: O(log(`self.count`))
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: self)
}
@@ -33,8 +33,7 @@ extension SortedSet: SetAlgebra {
/// method returns `(false, oldMember)`, where `oldMember` is the element
/// that was equal to `newMember`. In some cases, `oldMember` may be
/// distinguishable from `newMember` by identity comparison or some other means.
/// - Complexity: O(`log n`) where `n` is the number of members in the
/// sorted set.
/// - Complexity: O(log(`self.count`))
@inlinable
@inline(__always)
@discardableResult
@@ -54,6 +53,7 @@ extension SortedSet: SetAlgebra {
/// - Returns: An element equal to `newMember` if the set already contained such a
/// member; otherwise, `nil`. In some cases, the returned element may be distinguishable
/// from `newMember` by identity comparison or some other means.
/// - Complexity: O(log(`self.count`))
@inlinable
@inline(__always)
@discardableResult
@@ -70,8 +70,7 @@ extension SortedSet: SetAlgebra {
/// distinguishable from `newMember` by identity comparison or some other
/// means.
///
/// - Complexity: O(`log n`) where `n` is the number of members in the
/// sorted set.
/// - Complexity: O(log(`self.count`))
@inlinable
@inline(__always)
@discardableResult
@@ -80,12 +79,30 @@ extension SortedSet: SetAlgebra {
}
// MARK: Combining Sets
// TODO: add optimized implementations
/// Returns a new set with the elements of both this and the given set.
///
/// - Parameter other: A sorted set of the same type as the current set.
/// - Returns: A new sorted set with the unique elements of this set and `other`.
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), the element from the second set is inserted.
/// - Complexity: O(max(`self.count`, `other.count`))
@inlinable
public func union(_ other: __owned Self) -> Self {
var newSet = self
newSet.formUnion(other)
return newSet
var builder = _Tree.Builder()
var it1 = self.makeIterator()
var it2 = other.makeIterator()
while let e1 = it1.next(), let e2 = it2.next() {
if e1 <= e2 {
builder.append((e1, ()))
// while
} else {
builder.append((e2, ()))
}
}
return SortedSet(_rootedAt: builder.finish())
}
@inlinable
@@ -135,8 +152,10 @@ extension SortedSet: SetAlgebra {
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a subset of other; otherwise, `false`.
/// - Complexity: O(max(`self.count`, `other.count`))
@inlinable
public func isSubset(of other: SortedSet<Element>) -> Bool {
// TODO: could be worthwhile to evaluate recursive approach
if self.count > other.count { return false }
var superIterator = other.makeIterator()
@@ -0,0 +1,268 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension SortedSet {
public struct SubSequence {
@usableFromInline
internal typealias _TreeSubSequence = _Tree.SubSequence
@usableFromInline
internal let _subSequence: _TreeSubSequence
@inlinable
@inline(__always)
internal init(_ _subSequence: _TreeSubSequence) {
self._subSequence = _subSequence
}
/// The underlying collection of the subsequence.
@inlinable
@inline(__always)
internal var base: SortedSet { SortedSet(_rootedAt: _subSequence.base) }
}
}
extension SortedSet.SubSequence: Sequence {
public typealias Element = SortedSet.Element
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _iterator: _TreeSubSequence.Iterator
@inlinable
@inline(__always)
internal init(_ _iterator: _TreeSubSequence.Iterator) {
self._iterator = _iterator
}
/// Advances to the next element and returns it, or nil if no next element exists.
///
/// - Returns: The next element in the underlying sequence, if a next element exists;
/// otherwise, `nil`.
/// - Complexity: O(1) amortized over the entire sequence.
@inlinable
@inline(__always)
public mutating func next() -> Element? {
_iterator.next()?.key
}
}
/// Returns an iterator over the elements of the subsequence.
///
/// - Complexity: O(log(`self.count`))
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
Iterator(_subSequence.makeIterator())
}
}
extension SortedSet.SubSequence: BidirectionalCollection {
public typealias Index = SortedSet.Index
public typealias SubSequence = Self
/// The position of the first element in a nonempty subsequence.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var startIndex: Index { Index(_subSequence.startIndex) }
/// The subsequence's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var endIndex: Index { Index(_subSequence.endIndex) }
/// The number of elements in the subsequence.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var count: Int { _subSequence.count }
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If end is equal to start, the result is zero.
/// - Returns: The distance between start and end. The result can be negative.
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func distance(from start: Index, to end: Index) -> Int {
start._index.ensureValid(forTree: _subSequence.base)
end._index.ensureValid(forTree: _subSequence.base)
return _subSequence.distance(from: start._index, to: end._index)
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than `endIndex`.
/// - Returns: The index value immediately after `i`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
@inline(__always)
public func index(after i: Index) -> Index {
i._index.ensureValid(forTree: _subSequence.base)
return Index(_subSequence.index(after: i._index))
}
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than `endIndex`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
@inline(__always)
public func formIndex(after i: inout Index) {
i._index.ensureValid(forTree: _subSequence.base)
return _subSequence.formIndex(after: &i._index)
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater
/// than `startIndex`.
/// - Returns: The index value immediately before `i`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
@inline(__always)
public func index(before i: Index) -> Index {
i._index.ensureValid(forTree: _subSequence.base)
return Index(_subSequence.index(before: i._index))
}
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater
/// than `startIndex`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
@inline(__always)
public func formIndex(before i: inout Index) {
i._index.ensureValid(forTree: _subSequence.base)
_subSequence.formIndex(before: &i._index)
}
/// Returns an index that is the specified distance from the given index.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - Returns: An index offset by `distance` from the index `i`. If `distance`
/// is positive, this is the same value as the result of `distance` calls to
/// `index(after:)`. If `distance` is negative, this is the same value as the
/// result of `abs(distance)` calls to `index(before:)`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
@inline(__always)
public func index(_ i: Index, offsetBy distance: Int) -> Index {
i._index.ensureValid(forTree: _subSequence.base)
return Index(_subSequence.index(i._index, offsetBy: distance))
}
/// Offsets the given index by the specified distance.
///
/// The value passed as distance must not offset i beyond the bounds of the collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
@inline(__always)
internal func formIndex(_ i: inout Index, offsetBy distance: Int) {
i._index.ensureValid(forTree: _subSequence.base)
_subSequence.formIndex(&i._index, offsetBy: distance)
}
/// Returns an index that is the specified distance from the given index, unless that distance is beyond
/// a given limiting index.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `distance > 0`, a limit that is less
/// than `i` has no effect. Likewise, if `distance < 0`, a limit that is greater than `i` has
/// no effect.
/// - Returns: An index offset by `distance` from the index `i`, unless that index would be
/// beyond `limit` in the direction of movement. In that case, the method returns `nil`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
@inline(__always)
public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
i._index.ensureValid(forTree: _subSequence.base)
limit._index.ensureValid(forTree: _subSequence.base)
if let i = _subSequence.index(i._index, offsetBy: distance, limitedBy: limit._index) {
return Index(i)
} else {
return nil
}
}
/// Offsets the given index by the specified distance, or so that it equals the given limiting index.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `distance > 0`, a limit that is less
/// than `i` has no effect. Likewise, if `distance < 0`, a limit that is greater than `i` has
/// no effect.
/// - Returns: `true` if `i` has been offset by exactly `distance` steps without going beyond
/// `limit`; otherwise, `false`. When the return value is `false`, the value of `i` is
/// equal to `limit`.
/// - Complexity: O(log(`self.count`)) in the worst-case.
@inlinable
@inline(__always)
internal func formIndex(_ i: inout Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool {
i._index.ensureValid(forTree: _subSequence.base)
limit._index.ensureValid(forTree: _subSequence.base)
return _subSequence.formIndex(&i._index, offsetBy: distance, limitedBy: limit._index)
}
@inlinable
@inline(__always)
public subscript(position: Index) -> Element {
position._index.ensureValid(forTree: _subSequence.base)
return _subSequence[position._index].key
}
@inlinable
@inline(__always)
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_subSequence._failEarlyRangeCheck(
index._index,
bounds: bounds.lowerBound._index..<bounds.upperBound._index
)
}
@inlinable
@inline(__always)
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
_subSequence._failEarlyRangeCheck(
range.lowerBound._index..<range.upperBound._index,
bounds: bounds.lowerBound._index..<bounds.upperBound._index
)
}
}
@@ -10,23 +10,27 @@
//===----------------------------------------------------------------------===//
extension SortedSet {
/// Accesses the member at the specified position.
///
/// - Parameter position: The position of the key-value pair to access.
/// `position` must be a valid index of the sorted set and not equal
/// to `endIndex`.
/// - Returns: A member of the set.
/// - Complexity: O(1)
@inlinable
public subscript(position: Index) -> Element {
position._index.ensureValid(forTree: self._root)
return self._root[position._index].key
}
/// Returns a sequence of elements in the collection bounded by the provided
/// range.
///
/// This is particularly useful when applied with a bound corresponding to some
/// group of elements.
///
/// let students: SortedSet = ...
/// students["A"..<"B"] // Sequence of students with names beginning with "A"
///
/// - Complexity: O(log(`self.count`))
@inlinable
public subscript(range: Range<Element>) -> Slice<Self> {
let start = self._root.startIndex(forKey: range.lowerBound)
let end = self._root.startIndex(forKey: range.upperBound)
return Slice(base: self, bounds: Index(start)..<Index(end))
public subscript(range: Range<Element>) -> SubSequence {
let start = _root.startIndex(forKey: range.lowerBound)
let end = _root.startIndex(forKey: range.upperBound)
let range = _Tree.SubSequence(base: _root, bounds: start..<end)
return SubSequence(range)
}
}