Skip to content

Commit fa15cb2

Browse files
committed
[DNM] Extract in-place rotation to ContiguousArray
1 parent f244420 commit fa15cb2

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

stdlib/public/core/Sequence.swift

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,18 @@ extension Sequence where Element : Equatable {
800800
}
801801
}
802802

803+
extension ContiguousArray {
804+
/// Rotates array in place to the left by specified distance.
805+
@usableFromInline
806+
mutating func _rotate(left distance: Int) {
807+
guard distance > 0 else { return }
808+
let i = index(startIndex, offsetBy: distance)
809+
self[startIndex..<i].reverse()
810+
self[i..<endIndex].reverse()
811+
self.reverse()
812+
}
813+
}
814+
803815
extension Sequence {
804816

805817
/// Returns the longest possible subsequences of the sequence, in order, that
@@ -891,7 +903,7 @@ extension Sequence {
891903
// Put incoming elements into a ring buffer to save space. Once all
892904
// elements are consumed, reorder the ring buffer and return it.
893905
// This saves memory for sequences particularly longer than `maxLength`.
894-
var ringBuffer: [Element] = []
906+
var ringBuffer = ContiguousArray<Element>()
895907
ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount))
896908

897909
var i = 0
@@ -901,20 +913,12 @@ extension Sequence {
901913
ringBuffer.append(element)
902914
} else {
903915
ringBuffer[i] = element
904-
i += 1
905-
i %= maxLength
916+
i = (i + 1) % maxLength
906917
}
907918
}
908919

909-
if i != ringBuffer.startIndex {
910-
var rotated: [Element] = []
911-
rotated.reserveCapacity(ringBuffer.count)
912-
rotated += ringBuffer[i..<ringBuffer.endIndex]
913-
rotated += ringBuffer[0..<i]
914-
return rotated
915-
} else {
916-
return ringBuffer
917-
}
920+
ringBuffer._rotate(left: i)
921+
return Array(ringBuffer)
918922
}
919923

920924
/// Returns a sequence containing all but the given number of initial

0 commit comments

Comments
 (0)