Initial commit for SortedCollections

Signed-off-by: Vihan Bhargava <vihan_bhargava@apple.com>
This commit is contained in:
Vihan Bhargava committed 2021-08-09 19:13:41 -07:00
1 parent cc69069676
commit 9cf2cdadc0
40 files changed
+4019 -41

No files matched your search

@@ -0,0 +1,89 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: BidirectionalCollection {
/// The number of elements in the sorted dictionary.
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var count: Int { self._root.count }
/// A Boolean value that indicates whether the dictionary is empty.
@inlinable
@inline(__always)
public var isEmpty: Bool { self._root.isEmpty }
/// The position of the first element in a nonempty dictionary.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: O(`log n`)
@inlinable
@inline(__always)
public var startIndex: Index { Index(self._root.startIndex) }
/// The dictionary'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(self._root.endIndex) }
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return self._root.distance(from: start._index, to: end._index)
}
@inlinable
public func formIndex(after index: inout Index) {
index._index.ensureValid(for: self._root)
self._root.formIndex(after: &index._index)
}
@inlinable
public func index(after index: Index) -> Index {
index._index.ensureValid(for: self._root)
return Index(self._root.index(after: index._index))
}
@inlinable
public func formIndex(before index: inout Index) {
index._index.ensureValid(for: self._root)
self._root.formIndex(before: &index._index)
}
@inlinable
public func index(before index: Index) -> Index {
index._index.ensureValid(for: self._root)
return Index(self._root.index(before: index._index))
}
@inlinable
public func formIndex(_ i: inout Index, offsetBy distance: Int) {
i._index.ensureValid(for: self._root)
self._root.formIndex(&i._index, offsetBy: distance)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
i._index.ensureValid(for: self._root)
return Index(self._root.index(i._index, offsetBy: distance))
}
@inlinable
public subscript(position: Index) -> Element {
position._index.ensureValid(for: self._root)
return self._root[position._index]
}
}
@@ -0,0 +1,21 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: CustomReflectable {
// TODO: Review this implementation
// TODO: Implement nice playground output.
/// The custom mirror for this instance.
public var customMirror: Mirror {
// TODO: instead of Array(self), implement a Element view?
Mirror(self, unlabeledChildren: Array(self), displayStyle: .dictionary)
}
}
@@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: CustomStringConvertible, CustomDebugStringConvertible {
// TODO: see if there is way to reduce boilerplate here
@inlinable
public var description: String {
if isEmpty { return "[:]" }
var result = "["
var first = true
for (key, value) in self {
if first {
first = false
} else {
result += ", "
}
result += "\(key): \(value)"
}
result += "]"
return result
}
@inlinable
public var debugDescription: String {
if isEmpty { return "[:]" }
var result = "["
var first = true
for (key, value) in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(key, value, separator: ": ", terminator: "", to: &result)
}
result += "]"
return result
}
}
@@ -0,0 +1,34 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: Equatable where Value: Equatable {
// TODO: look into more efficient ways to implement this
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is false.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
/// - Complexity: O(`n log n`)
@inlinable
public static func ==(lhs: SortedDictionary<Key, Value>, rhs: SortedDictionary<Key, Value>) -> Bool {
if lhs.count != rhs.count { return false }
for ((k1, v1), (k2, v2)) in zip(lhs, rhs) {
if k1 != k2 || v1 != v2 {
return false
}
}
return true
}
}
@@ -0,0 +1,33 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: ExpressibleByDictionaryLiteral {
/// Creates a new sorted dictionary from the contents of a dictionary
/// literal.
///
/// Duplicate elements in the literal are allowed, but the resulting
/// set will only contain the first occurrence of each.
///
/// Do not call this initializer directly. It is used by the compiler when you
/// use a dictionary literal. Instead, create a new ordered dictionary using a
/// dictionary literal as its value by enclosing a comma-separated list of
/// values in square brackets. You can use an array literal anywhere a set is
/// expected by the type context.
///
/// - Parameter elements: A variadic list of key-value pairs for the new
/// dictionary.
///
/// - Complexity: O(`n log n`)
@inlinable
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init(uniqueKeysWithValues: elements)
}
}
@@ -0,0 +1,26 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: Hashable where Key: Hashable, Value: Hashable {
/// Hashes the essential components of this value by feeding them
/// into the givenhasher.
/// - Parameter hasher: The hasher to use when combining
/// the components of this instance.
/// - Complexity: O(`n log n`)
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(self.count)
for (key, value) in self {
hasher.combine(key)
hasher.combine(value)
}
}
}
@@ -0,0 +1,36 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: Sequence {
// /// An iterator over the elements of the sorted dictionary
// public struct Iterator: IteratorProtocol {
// @usableFromInline
// internal var _iterator: _Tree.Iterator
//
// @inlinable
// internal init(_base: SortedDictionary) {
// self._iterator = _base._root.makeIterator()
// }
//
// @inlinable
// public mutating func next() -> Element? {
// return self._iterator.next()
// }
// }
//
// /// Returns an iterator over the elements of the sorted dictionary.
// ///
// /// - Complexity: O(1)
// @inlinable
// public __consuming func makeIterator() -> Iterator {
// return Iterator(_base: self)
// }
//}
@@ -0,0 +1,54 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary {
/// Returns the index for a given key, if it exists
/// - Complexity: O(`log n`)
@inlinable
public func index(forKey key: Key) -> Index? {
if let index = self._root.anyIndex(forKey: key) {
return Index(index)
} else {
return nil
}
}
/// The position of an element within a sorted dictionary
public struct Index {
@usableFromInline
internal var _index: _Tree.Index
@inlinable
@inline(__always)
internal init(_ _index: _Tree.Index) {
self._index = _index
}
}
}
// MARK: Equatable
extension SortedDictionary.Index: Equatable {
// TODO: Potentially validate if lhs & rhs aren't pointing to deallocated dictionaries.
@inlinable
public static func ==(lhs: SortedDictionary.Index, rhs: SortedDictionary.Index) -> Bool {
lhs._index.ensureValid(with: rhs._index)
return lhs._index == rhs._index
}
}
// MARK: Comparable
extension SortedDictionary.Index: Comparable {
@inlinable
public static func <(lhs: SortedDictionary.Index, rhs: SortedDictionary.Index) -> Bool {
lhs._index.ensureValid(with: rhs._index)
return lhs._index < rhs._index
}
}
@@ -0,0 +1,141 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A collection which maintains key-value pairs in ascending sorted order.
///
/// A sorted dictionary is a type of tree, providing efficient read and write operations
/// to the entries it contains. Each entry in the sorted dictionary is identified using a
/// key, which is a comparable type such as a string or number. You can use that key
/// to retrieve the corresponding value.
public struct SortedDictionary<Key: Comparable, Value> {
/// An element of the sorted dictionary. A key-value tuple.
public typealias Element = (key: Key, value: Value)
@usableFromInline
internal typealias _Tree = _BTree<Key, Value>
@usableFromInline
internal var _root: _Tree
/// Creates an empty dictionary.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public init() {
self._root = _Tree()
}
/// Creates a dictionary rooted at a given BTree.
@inlinable
internal init(_rootedAt tree: _Tree) {
self._root = tree
}
/// Creates a dictionary from a sequence of key-value pairs which must
/// be unique.
/// - Complexity: O(`n log n`)
@inlinable
@inline(__always)
public init<S>(
uniqueKeysWithValues keysAndValues: S
) where S: Sequence, S.Element == Element {
self.init()
for (key, value) in keysAndValues {
self._root.setAnyValue(value, forKey: key)
}
}
}
// MARK: Mutations
extension SortedDictionary {
/// Updates the value stored in the dictionary for the given key, or
/// adds a new key-value pair if the key does not exist.
///
/// Use this method instead of key-based subscripting when you need to
/// know whether the new value supplants the value of an existing key. If
/// the value of an existing key is updated, `updateValue(_:forKey:)` returns
/// the original value.
///
/// - Parameters:
/// - value: The new value to add to the dictionary.
/// - key: The key to associate with value. If key already exists in the
/// dictionary, value replaces the existing associated value. If key
/// isn’t already a key of the dictionary, the (key, value) pair is added.
/// - Returns: The value that was replaced, or nil if a new key-value pair was added.
/// - Complexity: O(`log n`)
@inlinable
@discardableResult
public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? {
return self._root.setAnyValue(value, forKey: key)
}
}
// MARK: Subscripts
extension SortedDictionary {
/// Accesses the value associated with the key for both read and write operations
///
/// This key-based subscript returns the value for the given key if the key is found in
/// the dictionary, or nil if the key is not found.
///
/// When you assign a value for a key and that key already exists, the dictionary overwrites
/// the existing value. If the dictionary doesn’t contain the key, the key and value are added
/// as a new key-value pair.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The value associated with key if key is in the dictionary; otherwise, nil.
/// - Complexity: O(`log n`)
@inlinable
@inline(__always)
public subscript(key: Key) -> Value? {
get {
return self._root.anyValue(for: key)
}
// TODO: implement _modify
mutating set {
if let newValue = newValue {
self._root.setAnyValue(newValue, forKey: key)
} else {
// TODO: Removal
self._root.removeAny(key: key)
}
}
}
/// Accesses the value with the given key. If the dictionary doesn’t contain the given
/// key, accesses the provided default value as if the key and default value existed
/// in the dictionary.
///
/// Use this subscript when you want either the value for a particular key or, when that
/// key is not present in the dictionary, a default value.
///
/// - Parameters:
/// - key: The key the look up in the dictionary.
/// - defaultValue: The default value to use if key doesn’t exist in the dictionary.
/// - Returns: The value associated with key in the dictionary; otherwise, defaultValue.
/// - Complexity: O(`log n`)
@inlinable
@inline(__always)
public subscript(
key: Key, default defaultValue: @autoclosure () -> Value
) -> Value {
get {
return self[key] ?? defaultValue()
}
mutating set {
self[key] = newValue
}
}
}