Skip to content

Commit

Permalink
Fix NSDecimalPower(_:_:_:_:) behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
Oschly committed Jul 22, 2023
1 parent c0cd1d1 commit 713937f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
22 changes: 17 additions & 5 deletions Sources/Foundation/Decimal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1801,7 +1801,7 @@ public func NSDecimalPower(_ result: UnsafeMutablePointer<Decimal>, _ number: Un
return .overflow
}
NSDecimalCopy(result,number)
return result.pointee.power(UInt(power), roundingMode:roundingMode)
return result.pointee.power(power, roundingMode:roundingMode)
}

public func NSDecimalMultiplyByPowerOf10(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ power: Int16, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
Expand Down Expand Up @@ -2242,19 +2242,19 @@ extension Decimal {
_exponent = newExponent
return .noError
}
fileprivate mutating func power(_ p:UInt, roundingMode:RoundingMode) -> CalculationError {
fileprivate mutating func power(_ p:Int, roundingMode:RoundingMode) -> CalculationError {
if isNaN {
return .overflow
}
var power = p
var power = abs(p)
if power == 0 {
_exponent = 0
_length = 1
_isNegative = 0
self[0] = 1
_isCompact = 1
return .noError
} else if power == 1 {
} else if power == 1 || isZero {
return .noError
}

Expand Down Expand Up @@ -2297,7 +2297,19 @@ extension Decimal {
let previousError = error
var rightOp = self
error = NSDecimalMultiply(&self, &temporary, &rightOp, roundingMode)


// if power is negative, use multiplicative inverse
if p < 0 {
rightOp = self

error = NSDecimalDivide(
&self,
&temporary,
&rightOp,
roundingMode
)
}

if previousError != .noError { // FIXME is this the intent?
error = previousError
}
Expand Down
5 changes: 5 additions & 0 deletions Tests/Foundation/Tests/TestDecimal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -398,9 +398,14 @@ class TestDecimal: XCTestCase {
a = Decimal(8)
XCTAssertEqual(.noError, NSDecimalPower(&result, &a, 2, .plain))
XCTAssertEqual(Decimal(64), result)
a = Decimal(8)
XCTAssertEqual(.noError, NSDecimalPower(&result, &a, -2, .plain))
XCTAssertEqual(Decimal(1/64), result)
a = Decimal(-2)
XCTAssertEqual(.noError, NSDecimalPower(&result, &a, 3, .plain))
XCTAssertEqual(Decimal(-8), result)
XCTAssertEqual(.noError, NSDecimalPower(&result, &a, -3, .plain))
XCTAssertEqual(Decimal(-1/8), result)
for i in -2...10 {
for j in 0...5 {
var actual = Decimal(i)
Expand Down

0 comments on commit 713937f

Please sign in to comment.