Skip to content

Commit d9383e6

Browse files
jairajputglessard
andauthored
Fix crash when accessing span of empty InlineArray (#85268)
Fix crash when creating a Span from an empty InlineArray whose storage is only byte-aligned. #85265. --------- Co-authored-by: Guillaume Lessard <glessard@tffenterprises.com>
1 parent 3ce0f94 commit d9383e6

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

stdlib/public/core/InlineArray.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,10 @@ extension InlineArray where Element: ~Copyable {
587587
@lifetime(borrow self)
588588
@_transparent
589589
borrowing get {
590+
guard count > 0 else {
591+
let span = Span<Element>()
592+
return unsafe _overrideLifetime(span, borrowing: self)
593+
}
590594
let span = unsafe Span(_unsafeStart: _protectedAddress, count: count)
591595
return unsafe _overrideLifetime(span, borrowing: self)
592596
}
@@ -598,6 +602,10 @@ extension InlineArray where Element: ~Copyable {
598602
@lifetime(&self)
599603
@_transparent
600604
mutating get {
605+
guard count > 0 else {
606+
let span = MutableSpan<Element>()
607+
return unsafe _overrideLifetime(span, mutating: &self)
608+
}
601609
let span = unsafe MutableSpan(
602610
_unsafeStart: _protectedMutableAddress,
603611
count: count

test/stdlib/Span/InlineSpanProperties.swift

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,16 @@ suite.test("InlineArray.span property (String)")
119119
}
120120
}
121121
122+
suite.test("InlineArray.span property (empty, aligned)")
123+
.require(.stdlib_6_2).code {
124+
guard #available(SwiftStdlib 6.2, *) else { return }
125+
126+
let empty: InlineArray<0, Padded> = []
127+
let span = empty.span
128+
expectTrue(span.isEmpty)
129+
expectEqual(span.count, 0)
130+
}
131+
122132
suite.test("InlineArray.mutableSpan property")
123133
.require(.stdlib_6_2).code
124134
{
@@ -146,3 +156,14 @@ suite.test("InlineArray.mutableSpan property (String)")
146156
let s = span[3]
147157
expectTrue(s._isIdentical(to: v[3]))
148158
}
159+
160+
suite.test("InlineArray.mutableSpan property (empty, aligned)")
161+
.require(.stdlib_6_2).code
162+
{
163+
guard #available(SwiftStdlib 6.2, *) else { return }
164+
165+
var empty: InlineArray<0, Padded> = []
166+
var span = empty.mutableSpan
167+
expectTrue(span.isEmpty)
168+
expectEqual(span.count, 0)
169+
}

0 commit comments

Comments
 (0)