Skip to content

Commit 8b8f547

Browse files
authored
Merge pull request #66085 from oxy/gh56321
[stdlib] don't copy array contents on `removeAll(keepingCapacity: true)`
2 parents b2d0f25 + ff76106 commit 8b8f547

File tree

3 files changed

+20
-7
lines changed

3 files changed

+20
-7
lines changed

stdlib/public/core/Array.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1378,9 +1378,16 @@ extension Array: RangeReplaceableCollection {
13781378
if !keepCapacity {
13791379
_buffer = _Buffer()
13801380
}
1381-
else {
1381+
else if _buffer.isMutableAndUniquelyReferenced() {
13821382
self.replaceSubrange(indices, with: EmptyCollection())
13831383
}
1384+
else {
1385+
let buffer = _ContiguousArrayBuffer<Element>(
1386+
_uninitializedCount: 0,
1387+
minimumCapacity: capacity
1388+
)
1389+
_buffer = _Buffer(_buffer: buffer, shiftedToStartIndex: startIndex)
1390+
}
13841391
}
13851392

13861393
//===--- algorithms -----------------------------------------------------===//

stdlib/public/core/ArraySlice.swift

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -195,11 +195,7 @@ extension ArraySlice {
195195
func _checkSubscript(
196196
_ index: Int, wasNativeTypeChecked: Bool
197197
) -> _DependenceToken {
198-
#if _runtime(_ObjC)
199198
_buffer._checkValidSubscript(index)
200-
#else
201-
_buffer._checkValidSubscript(index)
202-
#endif
203199
return _DependenceToken()
204200
}
205201

@@ -1071,9 +1067,16 @@ extension ArraySlice: RangeReplaceableCollection {
10711067
if !keepCapacity {
10721068
_buffer = _Buffer()
10731069
}
1074-
else {
1070+
else if _buffer.isMutableAndUniquelyReferenced() {
10751071
self.replaceSubrange(indices, with: EmptyCollection())
10761072
}
1073+
else {
1074+
let buffer = _ContiguousArrayBuffer<Element>(
1075+
_uninitializedCount: 0,
1076+
minimumCapacity: capacity
1077+
)
1078+
_buffer = _Buffer(_buffer: buffer, shiftedToStartIndex: startIndex)
1079+
}
10771080
}
10781081

10791082
//===--- algorithms -----------------------------------------------------===//

stdlib/public/core/ContiguousArray.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -975,9 +975,12 @@ extension ContiguousArray: RangeReplaceableCollection {
975975
if !keepCapacity {
976976
_buffer = _Buffer()
977977
}
978-
else {
978+
else if _buffer.isMutableAndUniquelyReferenced() {
979979
self.replaceSubrange(indices, with: EmptyCollection())
980980
}
981+
else {
982+
_buffer = _Buffer(_uninitializedCount: 0, minimumCapacity: capacity)
983+
}
981984
}
982985

983986
//===--- algorithms -----------------------------------------------------===//

0 commit comments

Comments
 (0)