1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_spi(SwiftCorelibsFoundation) import FoundationEssentials
/*************** Exceptions ***********/
public struct NSExceptionName : RawRepresentable, Equatable, Hashable, Sendable {
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
}
extension NSExceptionName {
public static let decimalNumberExactnessException = NSExceptionName(rawValue: "NSDecimalNumberExactnessException")
public static let decimalNumberOverflowException = NSExceptionName(rawValue: "NSDecimalNumberOverflowException")
public static let decimalNumberUnderflowException = NSExceptionName(rawValue: "NSDecimalNumberUnderflowException")
public static let decimalNumberDivideByZeroException = NSExceptionName(rawValue: "NSDecimalNumberDivideByZeroException")
}
/*************** Rounding and Exception behavior ***********/
// Rounding policies :
// Original
// value 1.2 1.21 1.25 1.35 1.27
// Plain 1.2 1.2 1.3 1.4 1.3
// Down 1.2 1.2 1.2 1.3 1.2
// Up 1.2 1.3 1.3 1.4 1.3
// Bankers 1.2 1.2 1.2 1.4 1.3
/*************** Type definitions ***********/
extension NSDecimalNumber {
public typealias RoundingMode = Decimal.RoundingMode
public typealias CalculationError = Decimal.CalculationError
}
public protocol NSDecimalNumberBehaviors {
func roundingMode() -> NSDecimalNumber.RoundingMode
func scale() -> Int16
}
public var NSDecimalMaxSize: Int32 { 8 }
public var NSDecimalNoScale: Int32 { Int32(Int16.max) }
// Receiver can raise, return a new value, or return nil to ignore the exception.
fileprivate func handle(_ error: NSDecimalNumber.CalculationError, _ handler: NSDecimalNumberBehaviors) {
// handle the error condition, such as throwing an error for over/underflow
}
/*************** NSDecimalNumber: the class ***********/
open class NSDecimalNumber : NSNumber, @unchecked Sendable {
fileprivate let decimal: Decimal
public convenience init(mantissa: UInt64, exponent: Int16, isNegative: Bool) {
let d = Decimal(mantissa: mantissa, exponent: exponent, isNegative: isNegative)
self.init(decimal: d)
}
public init(decimal dcm: Decimal) {
self.decimal = dcm
super.init()
}
public convenience init(string numberValue: String?) {
self.init(decimal: Decimal(string: numberValue ?? "") ?? Decimal.nan)
}
public convenience init(string numberValue: String?, locale: Any?) {
self.init(decimal: Decimal(string: numberValue ?? "", locale: locale as? Locale) ?? Decimal.nan)
}
public required init?(coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let exponent:Int32 = coder.decodeInt32(forKey: "NS.exponent")
let length:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.length"))
let isNegative:UInt32 = UInt32(coder.decodeBool(forKey: "NS.negative") ? 1 : 0)
let isCompact:UInt32 = UInt32(coder.decodeBool(forKey: "NS.compact") ? 1 : 0)
// let byteOrder:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.bo"))
guard let mantissaData: Data = coder.decodeObject(forKey: "NS.mantissa") as? Data else {
return nil // raise "Critical NSDecimalNumber archived data is missing"
}
guard mantissaData.count == Int(NSDecimalMaxSize * 2) else {
return nil // raise "Critical NSDecimalNumber archived data is wrong size"
}
// Byte order?
let mantissa : Decimal.Mantissa = (
UInt16(mantissaData[0]) << 8 & UInt16(mantissaData[1]),
UInt16(mantissaData[2]) << 8 & UInt16(mantissaData[3]),
UInt16(mantissaData[4]) << 8 & UInt16(mantissaData[5]),
UInt16(mantissaData[6]) << 8 & UInt16(mantissaData[7]),
UInt16(mantissaData[8]) << 8 & UInt16(mantissaData[9]),
UInt16(mantissaData[10]) << 8 & UInt16(mantissaData[11]),
UInt16(mantissaData[12]) << 8 & UInt16(mantissaData[13]),
UInt16(mantissaData[14]) << 8 & UInt16(mantissaData[15])
)
self.decimal = Decimal(_exponent: exponent, _length: length, _isNegative: isNegative, _isCompact: isCompact, _reserved: 0, _mantissa: mantissa)
super.init()
}
public init(value: Int) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt) {
decimal = Decimal(value)
super.init()
}
public init(value: Int8) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt8) {
decimal = Decimal(value)
super.init()
}
public init(value: Int16) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt16) {
decimal = Decimal(value)
super.init()
}
public init(value: Int32) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt32) {
decimal = Decimal(value)
super.init()
}
public init(value: Int64) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt64) {
decimal = Decimal(value)
super.init()
}
public init(value: Bool) {
decimal = Decimal(value ? 1 : 0)
super.init()
}
public init(value: Float) {
decimal = Decimal(Double(value))
super.init()
}
public init(value: Double) {
decimal = Decimal(value)
super.init()
}
public required convenience init(floatLiteral value: Double) {
self.init(decimal:Decimal(value))
}
public required convenience init(booleanLiteral value: Bool) {
if value {
self.init(integerLiteral: 1)
} else {
self.init(integerLiteral: 0)
}
}
public required convenience init(integerLiteral value: Int) {
self.init(decimal:Decimal(value))
}
public required convenience init(bytes buffer: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) {
NSRequiresConcreteImplementation()
}
open override var description: String {
var number = self.decimal
return NSDecimalString(&number, nil)
}
open override func description(withLocale locale: Locale?) -> String {
var number = self.decimal
return NSDecimalString(&number, locale)
}
open class var zero: NSDecimalNumber {
return NSDecimalNumber(integerLiteral: 0)
}
open class var one: NSDecimalNumber {
return NSDecimalNumber(integerLiteral: 1)
}
open class var minimum: NSDecimalNumber {
return NSDecimalNumber(decimal:-Decimal.greatestFiniteMagnitude)
}
open class var maximum: NSDecimalNumber {
return NSDecimalNumber(decimal:Decimal.greatestFiniteMagnitude)
}
open class var notANumber: NSDecimalNumber {
return NSDecimalNumber(decimal: Decimal.nan)
}
open func adding(_ other: NSDecimalNumber) -> NSDecimalNumber {
return adding(other, withBehavior: nil)
}
open func adding(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalAdd(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func subtracting(_ other: NSDecimalNumber) -> NSDecimalNumber {
return subtracting(other, withBehavior: nil)
}
open func subtracting(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalSubtract(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func multiplying(by other: NSDecimalNumber) -> NSDecimalNumber {
return multiplying(by: other, withBehavior: nil)
}
open func multiplying(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalMultiply(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func dividing(by other: NSDecimalNumber) -> NSDecimalNumber {
return dividing(by: other, withBehavior: nil)
}
open func dividing(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalDivide(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func raising(toPower power: Int) -> NSDecimalNumber {
return raising(toPower:power, withBehavior: nil)
}
open func raising(toPower power: Int, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var input = self.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalPower(&result, &input, power, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func multiplying(byPowerOf10 power: Int16) -> NSDecimalNumber {
return multiplying(byPowerOf10: power, withBehavior: nil)
}
open func multiplying(byPowerOf10 power: Int16, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var input = self.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalMultiplyByPowerOf10(&result, &input, power, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
// Round to the scale of the behavior.
open func rounding(accordingToBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var input = self.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let scale = behavior.scale()
NSDecimalRound(&result, &input, Int(scale), roundingMode)
return NSDecimalNumber(decimal: result)
}
// compare two NSDecimalNumbers
open override func compare(_ decimalNumber: NSNumber) -> ComparisonResult {
if let num = decimalNumber as? NSDecimalNumber {
var lhs = decimal
var rhs = num.decimal
return NSDecimalCompare(&lhs, &rhs)
} else {
// NOTE: The lhs must be an NSNumber and not self (an NSDecimalNumber) so that NSNumber.compare() is used
return decimalNumber.compare(self)
}
}
open class var defaultBehavior: NSDecimalNumberBehaviors {
return NSDecimalNumberHandler.defaultBehavior
}
// One behavior per thread - The default behavior is
// rounding mode: NSRoundPlain
// scale: No defined scale (full precision)
// ignore exactnessException
// raise on overflow, underflow and divide by zero.
static let OBJC_TYPE = "d".utf8CString
open override var objCType: UnsafePointer<Int8> {
return NSDecimalNumber.OBJC_TYPE.withUnsafeBufferPointer{ $0.baseAddress! }
}
// return 'd' for double
open override var int8Value: Int8 {
return Int8(truncatingIfNeeded: int64Value)
}
open override var uint8Value: UInt8 {
return UInt8(truncatingIfNeeded: uint64Value)
}
open override var int16Value: Int16 {
return Int16(truncatingIfNeeded: int64Value)
}
open override var uint16Value: UInt16 {
return UInt16(truncatingIfNeeded: uint64Value)
}
open override var int32Value: Int32 {
return Int32(truncatingIfNeeded: int64Value)
}
open override var uint32Value: UInt32 {
return UInt32(truncatingIfNeeded: uint64Value)
}
open override var int64Value: Int64 {
decimal._int64Value
}
open override var uint64Value: UInt64 {
decimal._uint64Value
}
open override var floatValue: Float {
return Float(decimal._doubleValue)
}
open override var doubleValue: Double {
return decimal._doubleValue
}
open override var boolValue: Bool {
return !decimal.isZero
}
open override var intValue: Int {
return Int(truncatingIfNeeded: int64Value)
}
open override var uintValue: UInt {
return UInt(truncatingIfNeeded: uint64Value)
}
open override func isEqual(_ value: Any?) -> Bool {
if let other = value as? NSDecimalNumber {
return self.decimal == other.decimal
}
if let other = value as? NSNumber {
// NOTE: The lhs must be an NSNumber and not self (an NSDecimalNumber) so that NSNumber.compare() is used
return other.compare(self) == .orderedSame
}
return false
}
override var _swiftValueOfOptimalType: (Any & Sendable) {
return decimal
}
}
// return an approximate double value
/*********** A class for defining common behaviors *******/
open class NSDecimalNumberHandler : NSObject, NSDecimalNumberBehaviors, NSCoding, @unchecked Sendable {
static let defaultBehavior = NSDecimalNumberHandler()
let _roundingMode: NSDecimalNumber.RoundingMode
let _scale:Int16
let _raiseOnExactness: Bool
let _raiseOnOverflow: Bool
let _raiseOnUnderflow: Bool
let _raiseOnDivideByZero: Bool
public override init() {
_roundingMode = .plain
_scale = Int16(NSDecimalNoScale)
_raiseOnExactness = false
_raiseOnOverflow = true
_raiseOnUnderflow = true
_raiseOnDivideByZero = true
}
public required init?(coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
_roundingMode = NSDecimalNumber.RoundingMode(rawValue: UInt(coder.decodeInteger(forKey: "NS.roundingMode")))!
if coder.containsValue(forKey: "NS.scale") {
_scale = Int16(coder.decodeInteger(forKey: "NS.scale"))
} else {
_scale = Int16(NSDecimalNoScale)
}
_raiseOnExactness = coder.decodeBool(forKey: "NS.raise.exactness")
_raiseOnOverflow = coder.decodeBool(forKey: "NS.raise.overflow")
_raiseOnUnderflow = coder.decodeBool(forKey: "NS.raise.underflow")
_raiseOnDivideByZero = coder.decodeBool(forKey: "NS.raise.dividebyzero")
}
open func encode(with coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if _roundingMode != .plain {
coder.encode(Int(_roundingMode.rawValue), forKey: "NS.roundingmode")
}
if _scale != Int16(NSDecimalNoScale) {
coder.encode(_scale, forKey:"NS.scale")
}
if _raiseOnExactness {
coder.encode(_raiseOnExactness, forKey:"NS.raise.exactness")
}
if _raiseOnOverflow {
coder.encode(_raiseOnOverflow, forKey:"NS.raise.overflow")
}
if _raiseOnUnderflow {
coder.encode(_raiseOnUnderflow, forKey:"NS.raise.underflow")
}
if _raiseOnDivideByZero {
coder.encode(_raiseOnDivideByZero, forKey:"NS.raise.dividebyzero")
}
}
open class var `default`: NSDecimalNumberHandler {
return defaultBehavior
}
// rounding mode: NSRoundPlain
// scale: No defined scale (full precision)
// ignore exactnessException (return nil)
// raise on overflow, underflow and divide by zero.
public init(roundingMode: NSDecimalNumber.RoundingMode, scale: Int16, raiseOnExactness exact: Bool, raiseOnOverflow overflow: Bool, raiseOnUnderflow underflow: Bool, raiseOnDivideByZero divideByZero: Bool) {
_roundingMode = roundingMode
_scale = scale
_raiseOnExactness = exact
_raiseOnOverflow = overflow
_raiseOnUnderflow = underflow
_raiseOnDivideByZero = divideByZero
}
open func roundingMode() -> NSDecimalNumber.RoundingMode {
return _roundingMode
}
// The scale could return NoScale for no defined scale.
open func scale() -> Int16 {
return _scale
}
}
extension NSNumber {
public var decimalValue: Decimal {
if let d = self as? NSDecimalNumber {
return d.decimal
} else {
return Decimal(self.doubleValue)
}
}
}
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension Decimal {
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func add(_ other: Decimal) {
self += other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func subtract(_ other: Decimal) {
self -= other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func multiply(by other: Decimal) {
self *= other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func divide(by other: Decimal) {
self /= other
}
}
|