Skip to content

[stdlib] Dictionary.merge: Don’t leave storage in an inconsistent state when closure throws #19638

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 1 commit into from
Oct 1, 2018
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
5 changes: 2 additions & 3 deletions stdlib/public/core/NativeDictionary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -613,9 +613,8 @@ extension _NativeDictionary { // High-level operations
isUnique = true
if found {
do {
let v = (_values + bucket.offset).move()
let newValue = try combine(v, value)
(_values + bucket.offset).initialize(to: newValue)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can optimize the happy path by moving back in the failure case:

let v = (_values + bucket.offset).move()
do {
  let newValue = try combine(v, value)
  (_values + bucket.offset).initialize(to: newValue)
} catch _MergeError.keyCollision {
  fatalError("Duplicate values for key: '\(key)'")
} catch {
  // Put the value back.
  (_values + bucket.offset).initialize(to: v)
  throw error
}

let newValue = try combine(uncheckedValue(at: bucket), value)
_values[bucket.offset] = newValue
} catch _MergeError.keyCollision {
fatalError("Duplicate values for key: '\(key)'")
}
Expand Down
24 changes: 24 additions & 0 deletions validation-test/stdlib/Dictionary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,30 @@ DictionaryTestSuite.test("COW.Fast.MergeDictionaryDoesNotReallocate")
}
}


DictionaryTestSuite.test("Merge.ThrowingIsSafe") {
var d: [TestKeyTy: TestValueTy] = [
TestKeyTy(10): TestValueTy(1),
TestKeyTy(20): TestValueTy(2),
TestKeyTy(30): TestValueTy(3),
]

let d2: [TestKeyTy: TestValueTy] = [
TestKeyTy(40): TestValueTy(4),
TestKeyTy(50): TestValueTy(5),
TestKeyTy(10): TestValueTy(1),
]

struct TE: Error {}
do {
// Throwing must not leave the dictionary in an inconsistent state.
try d.merge(d2) { v1, v2 in throw TE() }
expectTrue(false, "merge did not throw")
} catch {
expectTrue(error is TE)
}
}

DictionaryTestSuite.test("COW.Fast.DefaultedSubscriptDoesNotReallocate") {
do {
var d1 = getCOWFastDictionary()
Expand Down