generated from rafaelesantos/swift-readme-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6336120
commit 187d6a9
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import Foundation | ||
|
||
public actor RefdsDictionary< | ||
Key: Hashable & Sendable, | ||
Value, | ||
Transform: Comparable | ||
> { | ||
private var elements: [Key: Value] = [:] | ||
private let keyPath: KeyPath<Value, Transform> | ||
|
||
public init( | ||
for type: Value.Type, | ||
by keyPath: KeyPath<Value, Transform> | ||
) { | ||
self.keyPath = keyPath | ||
} | ||
|
||
public subscript(key: Key) -> Value? { | ||
get { elements[key] } | ||
set { | ||
guard let newValue else { return remove(for: key) } | ||
if elements[key] == nil { insert(for: key) } | ||
elements[key] = newValue | ||
} | ||
} | ||
|
||
public var keys: [Key] = [] | ||
public var values: [Value] { | ||
keys.compactMap { elements[$0] } | ||
} | ||
|
||
private func insert(for key: Key) { | ||
let index = keys.firstIndex(where: { k in | ||
guard let lhs = elements[k].map({ $0[keyPath: keyPath] }), | ||
let rhs = elements[key].map({ $0[keyPath: keyPath] }) else { return false } | ||
return lhs >= rhs | ||
}) ?? keys.count | ||
keys.insert(key, at: index) | ||
} | ||
|
||
private func remove(for key: Key) { | ||
elements.removeValue(forKey: key) | ||
keys.removeAll { $0 == key } | ||
} | ||
} |