Skip to content

Commit f16de80

Browse files
committed
Add element-swapping support
1 parent c9e3edd commit f16de80

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

Sources/EmbeddedIntegerCollection/EmbeddedIntegerCollection.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,11 @@ extension EmbeddedIntegerCollection: RandomAccessCollection, MutableCollection {
170170
}
171171
}
172172

173+
public mutating func swapAt(_ i: Int, _ j: Int) {
174+
let flipMask = Wrapped(self[i] ^ self[j])
175+
word ^= flipMask << abs(i) | flipMask << abs(j)
176+
}
177+
173178
@inlinable
174179
public var indices: Indices {
175180
.init(every: Element.bitWidth, over: startIndex..<endIndex)

Tests/EmbeddedIntegerCollectionTests/EmbeddedIntegerCollectionTests.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,3 +197,29 @@ func moreIndexChecks(_ startingBitRange: EmbeddedIteratorDirection) async throws
197197
}
198198
#expect(manualIndices.elementsEqual(collectionIndices))
199199
}
200+
201+
@Test("Element swapping", arguments: EmbeddedIteratorDirection.allCases)
202+
func elementSwap(_ startingBitRange: EmbeddedIteratorDirection) async throws {
203+
var collection = EmbeddedIntegerCollection<UInt32, UInt8>(
204+
iteratingFrom: startingBitRange
205+
)
206+
let firstIndex = collection.startIndex
207+
let secondIndex = collection.index(after: firstIndex)
208+
let thirdIndex = collection.index(after: secondIndex)
209+
let fourthIndex = collection.index(after: thirdIndex)
210+
assert(collection.index(after: fourthIndex) == collection.endIndex)
211+
collection[firstIndex] = 0x40
212+
collection[secondIndex] = 0x41
213+
collection[thirdIndex] = 0x42
214+
collection[fourthIndex] = 0x43
215+
216+
#expect(collection.elementsEqual([0x40, 0x41, 0x42, 0x43]))
217+
collection.swapAt(secondIndex, secondIndex)
218+
#expect(collection.elementsEqual([0x40, 0x41, 0x42, 0x43]))
219+
collection.swapAt(firstIndex, thirdIndex)
220+
#expect(collection.elementsEqual([0x42, 0x41, 0x40, 0x43]))
221+
collection.swapAt(firstIndex, thirdIndex)
222+
#expect(collection.elementsEqual([0x40, 0x41, 0x42, 0x43]))
223+
collection.swapAt(fourthIndex, secondIndex)
224+
#expect(collection.elementsEqual([0x40, 0x43, 0x42, 0x41]))
225+
}

0 commit comments

Comments
 (0)