Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ Support levels:
<li><code>init()</code></li>
<li><code>init(minimumCapacity: Int)</code></li>
<li><code>init(uniqueKeysWithValues keysAndValues: any Sequence&lt;(Key, Value)&gt;)</code></li>
<li><code>init(_ keysAndValues: any Sequence&lt;(Key, Value)&gt;, uniquingKeysWith combine: (Value, Value) throws -&gt; Value) rethrows</code></li>
<li><code>func filter(_ isIncluded: ((Key, Value)) throws -&gt; Bool) rethrows -&gt; Dictionary&lt;Key, Value&gt;</code></li>
<li><code>subscript(key: Key) -&gt; Value?</code></li>
<li><code>subscript(key: Key, default defaultValue: Value) -&gt; Value</code></li>
Expand Down
1 change: 0 additions & 1 deletion Sources/SkipLib/Dictionary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ public struct Dictionary<Key, Value>: Collection {
public init(uniqueKeysWithValues keysAndValues: any Sequence<(Key, Value)>) {
}

@available(*, unavailable)
public init(_ keysAndValues: any Sequence<(Key, Value)>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows {
}

Expand Down
13 changes: 13 additions & 0 deletions Sources/SkipLib/Skip/Dictionary.kt
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,19 @@ class Dictionary<K, V>: Collection<Tuple2<K, V>>, MutableStruct, KotlinConvertin
_entryCollection = EntryCollection(this)
}

@Suppress("UNCHECKED_CAST")
constructor(keysAndValues: Sequence<Tuple2<K, V>>, uniquingKeysWith: (V, V) -> V): this() {
for (entry in keysAndValues.iterable) {
val key = entry.element0
val value = entry.element1
if (storage.containsKey(key)) {
storage[key] = uniquingKeysWith((storage[key] as V).sref(), value).sref()
} else {
storage[key] = value
}
}
}

@Suppress("UNCHECKED_CAST")
constructor(map: Map<K, V>, nocopy: Boolean = false, shared: Boolean = false) {
if (nocopy && map is LinkedHashMap<*, *>) {
Expand Down
109 changes: 109 additions & 0 deletions Tests/SkipLibTests/DictionaryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,108 @@ import Testing
#expect(multipleElementDictionary["b"] == 2)
}

@Test func uniquingKeysInitCombinesInSequenceOrder() {
let pairs = [("a", 1), ("b", 2), ("a", 3), ("a", 4)]
var combinedValues: [Int] = []

let result = Dictionary(pairs, uniquingKeysWith: { old, new in
combinedValues.append(old)
combinedValues.append(new)
return old * 10 + new
})

#expect(result == ["a": 134, "b": 2])
#expect(combinedValues == [1, 3, 13, 4])
}

@Test func uniquingKeysInitCanKeepFirstOrLastValue() {
let pairs = [("a", 1), ("b", 2), ("a", 3)]

let first = Dictionary(pairs, uniquingKeysWith: { old, _ in old })
let last = Dictionary(pairs, uniquingKeysWith: { _, new in new })

#expect(first == ["a": 1, "b": 2])
#expect(last == ["a": 3, "b": 2])
}

@Test func uniquingKeysInitPreservesNilValues() {
let pairs: [(String, Int?)] = [("a", nil), ("a", 1), ("a", nil), ("b", nil)]
var combinations = 0
var sawInitialNil = false

let result = Dictionary(pairs, uniquingKeysWith: { old, new in
if combinations == 0 {
sawInitialNil = old == nil
}
combinations += 1
return new
})

#expect(combinations == 2)
#expect(sawInitialNil)
#expect(result.count == 2)
#expect(result.keys.contains("a"))
#expect(result.keys.contains("b"))
#expect(result.values.allSatisfy { $0 == nil })
}

@Test func uniquingKeysInitDoesNotCombineUniqueOrEmptyInput() {
let pairs = [("a", 1), ("b", 2)]
let emptyPairs: [(String, Int)] = []
var combinations = 0
let combine: (Int, Int) -> Int = { _, new in
combinations += 1
return new
}

let result = Dictionary(pairs, uniquingKeysWith: combine)
let empty = Dictionary(emptyPairs, uniquingKeysWith: combine)

#expect(result == ["a": 1, "b": 2])
#expect(empty.isEmpty)
#expect(combinations == 0)
}

@Test func uniquingKeysInitPropagatesCombinerError() {
let pairs = [("a", 1), ("a", 2), ("a", 3)]
var combinations = 0
var caughtExpectedError = false
let combine: (Int, Int) throws -> Int = { _, _ in
combinations += 1
throw CombinationError.failed
}

do {
_ = try Dictionary(pairs, uniquingKeysWith: combine)
} catch {
caughtExpectedError = error is CombinationError
}

#expect(caughtExpectedError)
#expect(combinations == 1)
}

@Test func uniquingKeysInitPreservesValueSemantics() {
var original = [1]
let pairs = [("a", original), ("a", [2])]
var combined: [Int] = []

var result = Dictionary(pairs, uniquingKeysWith: { old, new in
combined = old + new
return combined
})
original.append(3)
combined.append(4)
var copy = result
copy["a"]?.append(5)
result["a"]?.append(6)

#expect(pairs[0].1 == [1])
#expect(result["a"] == [1, 2, 6])
#expect(copy["a"] == [1, 2, 5])
#expect(combined == [1, 2, 4])
}

@Test func subscriptDidSet() {
let holder = DictionaryHolder()
holder.dictionary["a"] = 1
Expand Down Expand Up @@ -162,3 +264,10 @@ private class DictionaryHolder {
}
}
}

// MARK: - Test Errors
private extension DictionaryTests {
enum CombinationError: Error {
case failed
}
}
Loading