@@ -363,8 +363,10 @@ extension DoubleWidth : FixedWidthInteger {
363
363
364
364
let low =
365
365
DoubleWidth < Low > ( mid1. partial, a. partial)
366
+ let ( sum_, overflow_) =
367
+ mid1. carry. addingReportingOverflow ( mid2. partial)
366
368
let high =
367
- DoubleWidth ( High ( mid2. carry + d. carry) , mid1 . carry + mid2 . partial )
369
+ DoubleWidth ( High ( mid2. carry + d. carry + ( overflow_ ? 1 : 0 ) ) , sum_ )
368
370
369
371
if isNegative {
370
372
let ( lowComplement, overflow) = ( ~ low) . addingReportingOverflow ( 1 )
@@ -631,10 +633,14 @@ extension DoubleWidth : UnsignedInteger where Base : UnsignedInteger {
631
633
) -> ( quotient: Low , remainder: Magnitude ) {
632
634
// The following invariants are guaranteed to hold by dividingFullWidth or
633
635
// quotientAndRemainder before this method is invoked:
634
- assert ( lhs. high != ( 0 as Low ) )
635
636
assert ( rhs. leadingZeroBitCount == 0 )
636
637
assert ( Magnitude ( lhs. high, lhs. mid) < rhs)
637
638
639
+ guard lhs. high != ( 0 as Low ) else {
640
+ let lhs_ = Magnitude ( lhs. mid, lhs. low)
641
+ return lhs_ < rhs ? ( 0 , lhs_) : ( 1 , lhs_ &- rhs)
642
+ }
643
+
638
644
// Estimate the quotient.
639
645
var quotient = lhs. high == rhs. high
640
646
? Low . max
@@ -735,12 +741,13 @@ extension DoubleWidth : UnsignedInteger where Base : UnsignedInteger {
735
741
736
742
// Left shift both rhs and lhs, then divide and right shift the remainder.
737
743
let shift = rhs. leadingZeroBitCount
744
+ // Note the use of `>>` instead of `&>>` below,
745
+ // as `high` should be zero if `shift` is zero.
738
746
let high = ( lhs >> ( Magnitude . bitWidth &- shift) ) . low
739
747
let rhs = rhs &<< shift
740
748
let lhs = lhs &<< shift
741
- let ( quotient, remainder) = high == ( 0 as Low )
742
- ? ( 1 , lhs &- rhs)
743
- : Magnitude . _divide ( ( high, lhs. high, lhs. low) , by: rhs)
749
+ let ( quotient, remainder) =
750
+ Magnitude . _divide ( ( high, lhs. high, lhs. low) , by: rhs)
744
751
return ( Magnitude ( 0 , quotient) , remainder &>> shift)
745
752
}
746
753
}
0 commit comments