Skip to content

Commit 73b0ad3

Browse files
authored
Merge pull request #74122 from Azoy/dict-builder-condition
[stdlib] Guard for empty singleton in dictionary builder
2 parents 91afad2 + 1cda063 commit 73b0ad3

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

stdlib/public/core/DictionaryBuilder.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,17 @@ extension _NativeDictionary {
102102
) -> Int
103103
) {
104104
self.init(capacity: capacity)
105+
106+
// If the capacity is 0, then our storage is the empty singleton. Those are
107+
// read only, so we shouldn't attempt to write to them.
108+
if capacity == 0 {
109+
let c = initializer(
110+
UnsafeMutableBufferPointer(start: nil, count: 0),
111+
UnsafeMutableBufferPointer(start: nil, count: 0))
112+
_precondition(c == 0)
113+
return
114+
}
115+
105116
let initializedCount = initializer(
106117
UnsafeMutableBufferPointer(start: _keys, count: capacity),
107118
UnsafeMutableBufferPointer(start: _values, count: capacity))

validation-test/stdlib/Dictionary.swift

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5735,8 +5735,10 @@ DictionaryTestSuite.test("BulkLoadingInitializer.Unique") {
57355735
_unsafeUninitializedCapacity: c,
57365736
allowingDuplicates: false
57375737
) { keys, values in
5738-
let k = keys.baseAddress!
5739-
let v = values.baseAddress!
5738+
guard let k = keys.baseAddress, let v = values.baseAddress else {
5739+
return 0
5740+
}
5741+
57405742
for i in 0 ..< c {
57415743
(k + i).initialize(to: TestKeyTy(i))
57425744
(v + i).initialize(to: TestEquatableValueTy(i))
@@ -5762,8 +5764,10 @@ DictionaryTestSuite.test("BulkLoadingInitializer.Nonunique") {
57625764
_unsafeUninitializedCapacity: c,
57635765
allowingDuplicates: true
57645766
) { keys, values in
5765-
let k = keys.baseAddress!
5766-
let v = values.baseAddress!
5767+
guard let k = keys.baseAddress, let v = values.baseAddress else {
5768+
return 0
5769+
}
5770+
57675771
for i in 0 ..< c {
57685772
(k + i).initialize(to: TestKeyTy(i / 2))
57695773
(v + i).initialize(to: TestEquatableValueTy(i / 2))

0 commit comments

Comments
 (0)