@@ -13,52 +13,40 @@ extension Shrink {
13
13
public typealias Element = IntegerType
14
14
15
15
@usableFromInline var current : IntegerType
16
- @usableFromInline var leap : IntegerType
17
-
18
- @usableFromInline let isSubtracting : Bool
19
-
20
- /// The first value in the sequence.
21
- @usableFromInline let first : IntegerType
22
16
/// Stop the sequence when reaching the end. Do not yield this value.
23
17
@usableFromInline let end : IntegerType
24
18
25
19
@usableFromInline init ( from: IntegerType , bound: IntegerType ) {
26
- first = bound
27
20
current = bound
28
21
end = from
29
- isSubtracting = bound > from
30
-
31
- let newLeap : ( partialValue: IntegerType , overflow: Bool )
32
- if isSubtracting {
33
- newLeap = ( bound / 2 ) . subtractingReportingOverflow ( from / 2 )
34
- } else {
35
- newLeap = ( from / 2 ) . subtractingReportingOverflow ( bound / 2 )
36
- }
37
- leap = !newLeap. overflow ? newLeap. partialValue : . max / 2
38
22
}
39
23
40
24
public mutating func next( ) -> IntegerType ? {
41
- let hasReachedEnd = isSubtracting ? current <= end : current >= end
42
- guard !hasReachedEnd, leap > 0 else {
25
+ guard current != end else {
43
26
return nil
44
27
}
45
-
46
28
defer {
47
- if isSubtracting {
48
- current -= leap
49
- } else {
50
- current += leap
51
- }
52
- }
53
- if current != first {
54
- leap /= 2
29
+ let next = current. midpoint ( towards: end)
30
+ current = current != next ? next : end
55
31
}
56
32
return current
57
33
}
58
34
}
59
35
}
60
36
61
37
extension FixedWidthInteger {
38
+
39
+ // Adapted from https://github.com/apple/swift-numerics/pull/293
40
+ @inlinable func midpoint( towards other: Self ) -> Self {
41
+ // Isolate bits in a + b with weight 2, and those with weight 1
42
+ let twos = self & other
43
+ let ones = self ^ other
44
+ let floor = twos &+ ones >> 1
45
+ let frac = ones & 1
46
+
47
+ return floor &+ ( self < other ? frac : 0 )
48
+ }
49
+
62
50
/// Get a shrinking sequence that shrinks this value to a specific value.
63
51
/// - Parameter bound: The value to shrink towards.
64
52
/// - Returns: A new sequence.
0 commit comments