Skip to content

Commit 3afe8eb

Browse files
authored
Merge pull request #78919 from kubamracek/embedded-dict-init
[embedded] Support Dictionary.init(uniqueKeysWithValues:) in Embedded Swift
2 parents fd9777e + 6d31a8b commit 3afe8eb

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

stdlib/public/core/Dictionary.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,10 +486,20 @@ public struct Dictionary<Key: Hashable, Value> {
486486
// error instead of calling fatalError() directly because we want the
487487
// message to include the duplicate key, and the closure only has access to
488488
// the conflicting values.
489+
#if !$Embedded
489490
try! native.merge(
490491
keysAndValues,
491492
isUnique: true,
492493
uniquingKeysWith: { _, _ in throw _MergeError.keyCollision })
494+
#else
495+
native.merge(
496+
keysAndValues,
497+
isUnique: true,
498+
uniquingKeysWith: { _, _ throws(_MergeError) in
499+
throw _MergeError.keyCollision
500+
}
501+
)
502+
#endif
493503
self.init(_native: native)
494504
}
495505

stdlib/public/core/NativeDictionary.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -791,6 +791,35 @@ extension _NativeDictionary { // High-level operations
791791
}
792792
}
793793

794+
#if $Embedded
795+
@inlinable
796+
internal mutating func merge<S: Sequence>(
797+
_ keysAndValues: __owned S,
798+
isUnique: Bool,
799+
uniquingKeysWith combine: (Value, Value) throws(_MergeError) -> Value
800+
) where S.Element == (Key, Value) {
801+
var isUnique = isUnique
802+
for (key, value) in keysAndValues {
803+
let (bucket, found) = mutatingFind(key, isUnique: isUnique)
804+
isUnique = true
805+
if found {
806+
do throws(_MergeError) {
807+
let newValue = try combine(uncheckedValue(at: bucket), value)
808+
_values[bucket.offset] = newValue
809+
} catch {
810+
#if !$Embedded
811+
fatalError("Duplicate values for key: '\(key)'")
812+
#else
813+
fatalError("Duplicate values for a key in a Dictionary")
814+
#endif
815+
}
816+
} else {
817+
_insert(at: bucket, key: key, value: value)
818+
}
819+
}
820+
}
821+
#endif
822+
794823
@inlinable
795824
@inline(__always)
796825
internal init<S: Sequence>(

test/embedded/dict-init.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// RUN: %target-run-simple-swift(-enable-experimental-feature Embedded -wmo) | %FileCheck %s
2+
3+
// REQUIRES: swift_in_compiler
4+
// REQUIRES: executable_test
5+
// REQUIRES: OS=macosx
6+
// REQUIRES: swift_feature_Embedded
7+
8+
public func foo() {
9+
let d = Dictionary<Int, StaticString>.init(uniqueKeysWithValues: [(10, "hello"), (20, "world")])
10+
print(d[10]!)
11+
print(d[20]!)
12+
}
13+
14+
foo()
15+
16+
// CHECK: hello
17+
// CHECK: world

0 commit comments

Comments
 (0)