Files
swift-collections/Sources/SortedCollections/SortedSet/SortedSet.Index.swift
T
Vihan Bhargava 817c97a403 Implement initial SortedDictionary API and implementations for SortedSet.
Key Changes:
 - SortedSet
   - Implement BidirectionalCollection
 - SortedDictionary
   - Implement Codable
   - Implement Partial RangeReplaceableCollection
     - Includes remove*() operations
   - init(grouping:by:)
   - var keys: Keys (aka SortedSet<Key>)
   - func (compact)mapValues(_:)

Minor Changes:
 - Correct time documented complexities of various methods
 - Implement more variations of removal methods.
2021-08-09 19:13:50 -07:00

55 lines
1.5 KiB
Swift

//===----------------------------------------------------------------------===//
//
// 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 {
/// Returns the index for a given element, if it exists
/// - Complexity: O(`log n`)
@inlinable
public func firstIndex(of element: Element) -> Index? {
if let index = self._root.anyIndex(forKey: element) {
return Index(index)
} else {
return nil
}
}
/// The position of an element within a sorted set
public struct Index {
@usableFromInline
internal var _index: _Tree.Index
@inlinable
@inline(__always)
internal init(_ _index: _Tree.Index) {
self._index = _index
}
}
}
// MARK: Equatable
extension SortedSet.Index: Equatable {
// TODO: Potentially validate if lhs & rhs aren't pointing to deallocated dictionaries.
@inlinable
public static func ==(lhs: SortedSet.Index, rhs: SortedSet.Index) -> Bool {
lhs._index.ensureValid(with: rhs._index)
return lhs._index == rhs._index
}
}
// MARK: Comparable
extension SortedSet.Index: Comparable {
@inlinable
public static func <(lhs: SortedSet.Index, rhs: SortedSet.Index) -> Bool {
lhs._index.ensureValid(with: rhs._index)
return lhs._index < rhs._index
}
}