Skip to content

Commit 849819f

Browse files
committed
improve Decimal conversion performance using _mantissa
1 parent 97a80fb commit 849819f

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

Sources/Floating Point Conversion.swift

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,16 @@ extension BigUInt {
4949
guard integer.sign == .plus else { return nil }
5050
assert(integer.floatingPointClass == .positiveNormal)
5151

52-
let significand = BigUInt("\(integer.significand)")!
52+
// keeping around in case the `Decimal._mantissa` property gets deprecated in the future.
53+
// let significand = BigUInt("\(integer.significand)")!
54+
let significand = {
55+
var start = BigUInt(0)
56+
for (place, value) in integer.significand.mantissaParts.enumerated() {
57+
guard value > 0 else { continue }
58+
start += (1 << (place * 16)) * BigUInt(value)
59+
}
60+
return start
61+
}()
5362
let exponent = BigUInt(10).power(integer.exponent)
5463

5564
self = significand * exponent
@@ -124,3 +133,20 @@ extension BigInt.Sign {
124133
}
125134
}
126135
}
136+
137+
#if canImport(Foundation)
138+
private extension Decimal {
139+
var mantissaParts: [UInt16] {
140+
[
141+
_mantissa.0,
142+
_mantissa.1,
143+
_mantissa.2,
144+
_mantissa.3,
145+
_mantissa.4,
146+
_mantissa.5,
147+
_mantissa.6,
148+
_mantissa.7,
149+
]
150+
}
151+
}
152+
#endif

0 commit comments

Comments
 (0)