Skip to content

[embedded] Support Dictionary.init(uniqueKeysWithValues:) in Embedded Swift #78919

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 31, 2025
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
10 changes: 10 additions & 0 deletions stdlib/public/core/Dictionary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -486,10 +486,20 @@ public struct Dictionary<Key: Hashable, Value> {
// error instead of calling fatalError() directly because we want the
// message to include the duplicate key, and the closure only has access to
// the conflicting values.
#if !$Embedded
try! native.merge(
keysAndValues,
isUnique: true,
uniquingKeysWith: { _, _ in throw _MergeError.keyCollision })
#else
native.merge(
keysAndValues,
isUnique: true,
uniquingKeysWith: { _, _ throws(_MergeError) in
throw _MergeError.keyCollision
}
)
#endif
self.init(_native: native)
}

Expand Down
29 changes: 29 additions & 0 deletions stdlib/public/core/NativeDictionary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,35 @@ extension _NativeDictionary { // High-level operations
}
}

#if $Embedded
@inlinable
internal mutating func merge<S: Sequence>(
_ keysAndValues: __owned S,
isUnique: Bool,
uniquingKeysWith combine: (Value, Value) throws(_MergeError) -> Value
) where S.Element == (Key, Value) {
var isUnique = isUnique
for (key, value) in keysAndValues {
let (bucket, found) = mutatingFind(key, isUnique: isUnique)
isUnique = true
if found {
do throws(_MergeError) {
let newValue = try combine(uncheckedValue(at: bucket), value)
_values[bucket.offset] = newValue
} catch {
#if !$Embedded
fatalError("Duplicate values for key: '\(key)'")
#else
fatalError("Duplicate values for a key in a Dictionary")
#endif
}
} else {
_insert(at: bucket, key: key, value: value)
}
}
}
#endif

@inlinable
@inline(__always)
internal init<S: Sequence>(
Expand Down
17 changes: 17 additions & 0 deletions test/embedded/dict-init.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// RUN: %target-run-simple-swift(-enable-experimental-feature Embedded -wmo) | %FileCheck %s

// REQUIRES: swift_in_compiler
// REQUIRES: executable_test
// REQUIRES: OS=macosx
// REQUIRES: swift_feature_Embedded

public func foo() {
let d = Dictionary<Int, StaticString>.init(uniqueKeysWithValues: [(10, "hello"), (20, "world")])
print(d[10]!)
print(d[20]!)
}

foo()

// CHECK: hello
// CHECK: world