Skip to content

Commit 1c09782

Browse files
committed
stdlib: Dictionary: contain the unsigned division optimization in a getter method, expose a clean API to the outside
1 parent d102209 commit 1c09782

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

stdlib/public/core/HashedCollections.swift.gyb

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2460,13 +2460,16 @@ internal struct _BitMap {
24602460
internal let values: UnsafeMutablePointer<UInt>
24612461
internal let bitCount: Int
24622462

2463-
// Note: We use UInt here to get unsigned math (shifts).
2464-
internal static func wordIndex(_ i: UInt) -> UInt {
2465-
return i / UInt._sizeInBits
2463+
internal static func wordIndex(_ i: Int) -> Int {
2464+
// Note: We perform the operation on UInts to get faster unsigned math
2465+
// (shifts).
2466+
return Int(bitPattern: UInt(bitPattern: i) / UInt(UInt._sizeInBits))
24662467
}
24672468

2468-
internal static func bitIndex(_ i: UInt) -> UInt {
2469-
return i % UInt._sizeInBits
2469+
internal static func bitIndex(_ i: Int) -> UInt {
2470+
// Note: We perform the operation on UInts to get faster unsigned math
2471+
// (shifts).
2472+
return UInt(bitPattern: i) % UInt(UInt._sizeInBits)
24702473
}
24712474

24722475
internal static func wordsFor(_ bitCount: Int) -> Int {
@@ -2493,21 +2496,18 @@ internal struct _BitMap {
24932496
internal subscript(i: Int) -> Bool {
24942497
get {
24952498
_sanityCheck(i < Int(bitCount) && i >= 0, "index out of bounds")
2496-
let idx = UInt(i)
2497-
let word = values[Int(_BitMap.wordIndex(idx))]
2498-
let bit = word & (1 << _BitMap.bitIndex(idx))
2499+
let word = values[_BitMap.wordIndex(i)]
2500+
let bit = word & (1 << _BitMap.bitIndex(i))
24992501
return bit != 0
25002502
}
25012503
nonmutating set {
25022504
_sanityCheck(i < Int(bitCount) && i >= 0, "index out of bounds")
2503-
let idx = UInt(i)
2504-
let wordIdx = _BitMap.wordIndex(idx)
2505+
let wordIdx = _BitMap.wordIndex(i)
2506+
let bitMask = 1 << _BitMap.bitIndex(i)
25052507
if newValue {
2506-
values[Int(wordIdx)] =
2507-
values[Int(wordIdx)] | (1 << _BitMap.bitIndex(idx))
2508+
values[wordIdx] = values[wordIdx] | bitMask
25082509
} else {
2509-
values[Int(wordIdx)] =
2510-
values[Int(wordIdx)] & ~(1 << _BitMap.bitIndex(idx))
2510+
values[wordIdx] = values[wordIdx] & ~bitMask
25112511
}
25122512
}
25132513
}

0 commit comments

Comments
 (0)