forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDecimal.swift
2317 lines (2032 loc) · 74.9 KB
/
Decimal.swift
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2016 - 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
//
import CoreFoundation
public var NSDecimalMaxSize: Int32 { 8 }
public var NSDecimalNoScale: Int32 { Int32(Int16.max) }
public struct Decimal {
fileprivate var __exponent: Int8
fileprivate var __lengthAndFlags: UInt8
fileprivate var __reserved: UInt16
public var _exponent: Int32 {
get {
return Int32(__exponent)
}
set {
__exponent = Int8(truncatingIfNeeded: newValue)
}
}
// _length == 0 && _isNegative == 1 -> NaN.
public var _length: UInt32 {
get {
return UInt32((__lengthAndFlags & 0b0000_1111))
}
set {
guard newValue <= maxMantissaLength else {
fatalError("Attempt to set a length greater than capacity \(newValue) > \(maxMantissaLength)")
}
__lengthAndFlags =
(__lengthAndFlags & 0b1111_0000) |
UInt8(newValue & 0b0000_1111)
}
}
public var _isNegative: UInt32 {
get {
return UInt32(((__lengthAndFlags) & 0b0001_0000) >> 4)
}
set {
__lengthAndFlags =
(__lengthAndFlags & 0b1110_1111) |
(UInt8(newValue & 0b0000_0001 ) << 4)
}
}
public var _isCompact: UInt32 {
get {
return UInt32(((__lengthAndFlags) & 0b0010_0000) >> 5)
}
set {
__lengthAndFlags =
(__lengthAndFlags & 0b1101_1111) |
(UInt8(newValue & 0b0000_00001 ) << 5)
}
}
public var _reserved: UInt32 {
get {
return UInt32(UInt32(__lengthAndFlags & 0b1100_0000) << 10 | UInt32(__reserved))
}
set {
__lengthAndFlags =
(__lengthAndFlags & 0b0011_1111) |
UInt8(UInt32(newValue & (0b11 << 16)) >> 10)
__reserved = UInt16(newValue & 0b1111_1111_1111_1111)
}
}
public var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)
public init() {
self._mantissa = (0,0,0,0,0,0,0,0)
self.__exponent = 0
self.__lengthAndFlags = 0
self.__reserved = 0
}
public init(_exponent: Int32, _length: UInt32, _isNegative: UInt32, _isCompact: UInt32, _reserved: UInt32, _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)) {
self._mantissa = _mantissa
self.__exponent = Int8(truncatingIfNeeded: _exponent)
self.__lengthAndFlags = UInt8(_length & 0b1111)
self.__reserved = 0
self._isNegative = _isNegative
self._isCompact = _isCompact
self._reserved = _reserved
}
}
extension Decimal {
public typealias RoundingMode = NSDecimalNumber.RoundingMode
public typealias CalculationError = NSDecimalNumber.CalculationError
}
public func pow(_ x: Decimal, _ y: Int) -> Decimal {
var x = x
var result = Decimal()
NSDecimalPower(&result, &x, y, .plain)
return result
}
extension Decimal : Hashable, Comparable {
// (Used by VariableLengthNumber and doubleValue.)
fileprivate subscript(index: UInt32) -> UInt16 {
get {
switch index {
case 0: return _mantissa.0
case 1: return _mantissa.1
case 2: return _mantissa.2
case 3: return _mantissa.3
case 4: return _mantissa.4
case 5: return _mantissa.5
case 6: return _mantissa.6
case 7: return _mantissa.7
default: fatalError("Invalid index \(index) for _mantissa")
}
}
set {
switch index {
case 0: _mantissa.0 = newValue
case 1: _mantissa.1 = newValue
case 2: _mantissa.2 = newValue
case 3: _mantissa.3 = newValue
case 4: _mantissa.4 = newValue
case 5: _mantissa.5 = newValue
case 6: _mantissa.6 = newValue
case 7: _mantissa.7 = newValue
default: fatalError("Invalid index \(index) for _mantissa")
}
}
}
// (Used by NSDecimalNumber and hash(into:).)
internal var doubleValue: Double {
if _length == 0 {
return _isNegative == 1 ? Double.nan : 0
}
var d = 0.0
for idx in (0..<min(_length, 8)).reversed() {
d = d * 65536 + Double(self[idx])
}
if _exponent < 0 {
for _ in _exponent..<0 {
d /= 10.0
}
} else {
for _ in 0..<_exponent {
d *= 10.0
}
}
return _isNegative != 0 ? -d : d
}
// The low 64 bits of the integer part. (Used by uint64Value and int64Value.)
private var _unsignedInt64Value: UInt64 {
if _exponent < -20 || _exponent > 20 {
return 0
}
if _length == 0 || isZero || magnitude < (0 as Decimal) {
return 0
}
var copy = self.significand
if _exponent < 0 {
for _ in _exponent..<0 {
_ = divideByShort(©, 10)
}
} else if _exponent > 0 {
for _ in 0..<_exponent {
_ = multiplyByShort(©, 10)
}
}
let uint64 = UInt64(copy._mantissa.3) << 48 | UInt64(copy._mantissa.2) << 32 | UInt64(copy._mantissa.1) << 16 | UInt64(copy._mantissa.0)
return uint64
}
// A best-effort conversion of the integer value, trying to match Darwin for
// values outside of UInt64.min...UInt64.max. (Used by NSDecimalNumber.)
internal var uint64Value: UInt64 {
let value = _unsignedInt64Value
if !self.isNegative {
return value
}
if value == Int64.max.magnitude + 1 {
return UInt64(bitPattern: Int64.min)
}
if value <= Int64.max.magnitude {
var value = Int64(value)
value.negate()
return UInt64(bitPattern: value)
}
return value
}
// A best-effort conversion of the integer value, trying to match Darwin for
// values outside of Int64.min...Int64.max. (Used by NSDecimalNumber.)
internal var int64Value: Int64 {
let uint64Value = _unsignedInt64Value
if self.isNegative {
if uint64Value == Int64.max.magnitude + 1 {
return Int64.min
}
if uint64Value <= Int64.max.magnitude {
var value = Int64(uint64Value)
value.negate()
return value
}
}
return Int64(bitPattern: uint64Value)
}
public func hash(into hasher: inout Hasher) {
// FIXME: This is a weak hash. We should rather normalize self to a
// canonical member of the exact same equivalence relation that
// NSDecimalCompare implements, then simply feed all components to the
// hasher.
hasher.combine(doubleValue)
}
public static func ==(lhs: Decimal, rhs: Decimal) -> Bool {
if lhs.isNaN {
return rhs.isNaN
}
if lhs.__exponent == rhs.__exponent && lhs.__lengthAndFlags == rhs.__lengthAndFlags && lhs.__reserved == rhs.__reserved {
if lhs._mantissa.0 == rhs._mantissa.0 &&
lhs._mantissa.1 == rhs._mantissa.1 &&
lhs._mantissa.2 == rhs._mantissa.2 &&
lhs._mantissa.3 == rhs._mantissa.3 &&
lhs._mantissa.4 == rhs._mantissa.4 &&
lhs._mantissa.5 == rhs._mantissa.5 &&
lhs._mantissa.6 == rhs._mantissa.6 &&
lhs._mantissa.7 == rhs._mantissa.7 {
return true
}
}
var lhsVal = lhs
var rhsVal = rhs
return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedSame
}
public static func <(lhs: Decimal, rhs: Decimal) -> Bool {
var lhsVal = lhs
var rhsVal = rhs
return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedAscending
}
}
extension Decimal : CustomStringConvertible {
public init?(string: String, locale: Locale? = nil) {
let scan = Scanner(string: string)
var theDecimal = Decimal()
scan.locale = locale
if !scan.scanDecimal(&theDecimal) {
return nil
}
self = theDecimal
}
public var description: String {
var value = self
return NSDecimalString(&value, nil)
}
}
extension Decimal : Codable {
private enum CodingKeys : Int, CodingKey {
case exponent
case length
case isNegative
case isCompact
case mantissa
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let exponent = try container.decode(CInt.self, forKey: .exponent)
let length = try container.decode(CUnsignedInt.self, forKey: .length)
let isNegative = try container.decode(Bool.self, forKey: .isNegative)
let isCompact = try container.decode(Bool.self, forKey: .isCompact)
var mantissaContainer = try container.nestedUnkeyedContainer(forKey: .mantissa)
var mantissa: (CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort,
CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort) = (0,0,0,0,0,0,0,0)
mantissa.0 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.1 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.2 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.3 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.4 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.5 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.6 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.7 = try mantissaContainer.decode(CUnsignedShort.self)
self.init(_exponent: exponent,
_length: length,
_isNegative: CUnsignedInt(isNegative ? 1 : 0),
_isCompact: CUnsignedInt(isCompact ? 1 : 0),
_reserved: 0,
_mantissa: mantissa)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(_exponent, forKey: .exponent)
try container.encode(_length, forKey: .length)
try container.encode(_isNegative == 0 ? false : true, forKey: .isNegative)
try container.encode(_isCompact == 0 ? false : true, forKey: .isCompact)
var mantissaContainer = container.nestedUnkeyedContainer(forKey: .mantissa)
try mantissaContainer.encode(_mantissa.0)
try mantissaContainer.encode(_mantissa.1)
try mantissaContainer.encode(_mantissa.2)
try mantissaContainer.encode(_mantissa.3)
try mantissaContainer.encode(_mantissa.4)
try mantissaContainer.encode(_mantissa.5)
try mantissaContainer.encode(_mantissa.6)
try mantissaContainer.encode(_mantissa.7)
}
}
extension Decimal : ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self.init(value)
}
}
extension Decimal : ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.init(value)
}
}
extension Decimal : SignedNumeric {
public var magnitude: Decimal {
guard _length != 0 else { return self }
return Decimal(
_exponent: self._exponent, _length: self._length,
_isNegative: 0, _isCompact: self._isCompact,
_reserved: 0, _mantissa: self._mantissa)
}
// FIXME(integers): implement properly
public init?<T : BinaryInteger>(exactly source: T) {
fatalError()
}
public static func +=(lhs: inout Decimal, rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalAdd($0, $0, &rhs, .plain)
}
}
public static func -=(lhs: inout Decimal, rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalSubtract($0, $0, &rhs, .plain)
}
}
public static func *=(lhs: inout Decimal, rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalMultiply($0, $0, &rhs, .plain)
}
}
public static func /=(lhs: inout Decimal, rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalDivide($0, $0, &rhs, .plain)
}
}
public static func +(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer += rhs
return answer
}
public static func -(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer -= rhs
return answer
}
public static func *(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer *= rhs
return answer
}
public static func /(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer /= rhs
return answer
}
public mutating func negate() {
guard _length != 0 else { return }
_isNegative = _isNegative == 0 ? 1 : 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
}
}
extension Decimal : Strideable {
public func distance(to other: Decimal) -> Decimal {
return self - other
}
public func advanced(by n: Decimal) -> Decimal {
return self + n
}
}
// The methods in this extension exist to match the protocol requirements of
// FloatingPoint, even if we can't conform directly.
//
// If it becomes clear that conformance is truly impossible, we can deprecate
// some of the methods (e.g. `isEqual(to:)` in favor of operators).
extension Decimal {
public static let leastFiniteMagnitude = Decimal(
_exponent: 127,
_length: 8,
_isNegative: 1,
_isCompact: 1,
_reserved: 0,
_mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)
)
public static let greatestFiniteMagnitude = Decimal(
_exponent: 127,
_length: 8,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)
)
public static let leastNormalMagnitude = Decimal(
_exponent: -127,
_length: 1,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)
)
public static let leastNonzeroMagnitude = Decimal(
_exponent: -127,
_length: 1,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)
)
public static let pi = Decimal(
_exponent: -38,
_length: 8,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0x6623, 0x7d57, 0x16e7, 0xad0d, 0xaf52, 0x4641, 0xdfa7, 0xec58)
)
@available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.")
public static var infinity: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") }
@available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.")
public static var signalingNaN: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") }
public static var quietNaN: Decimal {
return Decimal(
_exponent: 0, _length: 0, _isNegative: 1, _isCompact: 0,
_reserved: 0, _mantissa: (0, 0, 0, 0, 0, 0, 0, 0))
}
public static var nan: Decimal { quietNaN }
public static var radix: Int { 10 }
public init(_ value: UInt8) {
self.init(UInt64(value))
}
public init(_ value: Int8) {
self.init(Int64(value))
}
public init(_ value: UInt16) {
self.init(UInt64(value))
}
public init(_ value: Int16) {
self.init(Int64(value))
}
public init(_ value: UInt32) {
self.init(UInt64(value))
}
public init(_ value: Int32) {
self.init(Int64(value))
}
public init(_ value: UInt64) {
self = Decimal()
if value == 0 {
return
}
var compactValue = value
var exponent: Int32 = 0
while compactValue % 10 == 0 {
compactValue /= 10
exponent += 1
}
_isCompact = 1
_exponent = exponent
let wordCount = ((UInt64.bitWidth - compactValue.leadingZeroBitCount) + (UInt16.bitWidth - 1)) / UInt16.bitWidth
_length = UInt32(wordCount)
_mantissa.0 = UInt16(truncatingIfNeeded: compactValue >> 0)
_mantissa.1 = UInt16(truncatingIfNeeded: compactValue >> 16)
_mantissa.2 = UInt16(truncatingIfNeeded: compactValue >> 32)
_mantissa.3 = UInt16(truncatingIfNeeded: compactValue >> 48)
}
public init(_ value: Int64) {
self.init(value.magnitude)
if value < 0 {
_isNegative = 1
}
}
public init(_ value: UInt) {
self.init(UInt64(value))
}
public init(_ value: Int) {
self.init(Int64(value))
}
public init(_ value: Double) {
precondition(!value.isInfinite, "Decimal does not yet fully adopt FloatingPoint")
if value.isNaN {
self = Decimal.nan
} else if value == 0.0 {
self = Decimal()
} else {
self = Decimal()
let negative = value < 0
var val = negative ? -1 * value : value
var exponent = 0
while val < Double(UInt64.max - 1) {
val *= 10.0
exponent -= 1
}
while Double(UInt64.max - 1) < val {
val /= 10.0
exponent += 1
}
var mantissa = UInt64(val)
var i: Int32 = 0
// This is a bit ugly but it is the closest approximation of the C
// initializer that can be expressed here.
while mantissa != 0 && i < NSDecimalMaxSize {
switch i {
case 0:
_mantissa.0 = UInt16(truncatingIfNeeded: mantissa)
case 1:
_mantissa.1 = UInt16(truncatingIfNeeded: mantissa)
case 2:
_mantissa.2 = UInt16(truncatingIfNeeded: mantissa)
case 3:
_mantissa.3 = UInt16(truncatingIfNeeded: mantissa)
case 4:
_mantissa.4 = UInt16(truncatingIfNeeded: mantissa)
case 5:
_mantissa.5 = UInt16(truncatingIfNeeded: mantissa)
case 6:
_mantissa.6 = UInt16(truncatingIfNeeded: mantissa)
case 7:
_mantissa.7 = UInt16(truncatingIfNeeded: mantissa)
default:
fatalError("initialization overflow")
}
mantissa = mantissa >> 16
i += 1
}
_length = UInt32(i)
_isNegative = negative ? 1 : 0
_isCompact = 0
_exponent = Int32(exponent)
self.compact()
}
}
public init(sign: FloatingPointSign, exponent: Int, significand: Decimal) {
self.init(
_exponent: Int32(exponent) + significand._exponent,
_length: significand._length,
_isNegative: sign == .plus ? 0 : 1,
_isCompact: significand._isCompact,
_reserved: 0,
_mantissa: significand._mantissa)
}
public init(signOf: Decimal, magnitudeOf magnitude: Decimal) {
self.init(
_exponent: magnitude._exponent,
_length: magnitude._length,
_isNegative: signOf._isNegative,
_isCompact: magnitude._isCompact,
_reserved: 0,
_mantissa: magnitude._mantissa)
}
public var exponent: Int {
return Int(_exponent)
}
public var significand: Decimal {
return Decimal(
_exponent: 0, _length: _length, _isNegative: _isNegative, _isCompact: _isCompact,
_reserved: 0, _mantissa: _mantissa)
}
public var sign: FloatingPointSign {
return _isNegative == 0 ? FloatingPointSign.plus : FloatingPointSign.minus
}
public var ulp: Decimal {
if !self.isFinite { return Decimal.nan }
return Decimal(
_exponent: _exponent, _length: 8, _isNegative: 0, _isCompact: 1,
_reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
public var nextUp: Decimal {
return self + Decimal(
_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1,
_reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
public var nextDown: Decimal {
return self - Decimal(
_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1,
_reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
/// The IEEE 754 "class" of this type.
public var floatingPointClass: FloatingPointClassification {
if _length == 0 && _isNegative == 1 {
return .quietNaN
} else if _length == 0 {
return .positiveZero
}
// NSDecimal does not really represent normal and subnormal in the same
// manner as the IEEE standard, for now we can probably claim normal for
// any nonzero, non-NaN values.
if _isNegative == 1 {
return .negativeNormal
} else {
return .positiveNormal
}
}
public var isCanonical: Bool { true }
/// `true` iff `self` is negative.
public var isSignMinus: Bool { _isNegative != 0 }
/// `true` iff `self` is +0.0 or -0.0.
public var isZero: Bool { _length == 0 && _isNegative == 0 }
/// `true` iff `self` is subnormal.
public var isSubnormal: Bool { false }
/// `true` iff `self` is normal (not zero, subnormal, infinity, or NaN).
public var isNormal: Bool { !isZero && !isInfinite && !isNaN }
/// `true` iff `self` is zero, subnormal, or normal (not infinity or NaN).
public var isFinite: Bool { !isNaN }
/// `true` iff `self` is infinity.
public var isInfinite: Bool { false }
/// `true` iff `self` is NaN.
public var isNaN: Bool { _length == 0 && _isNegative == 1 }
/// `true` iff `self` is a signaling NaN.
public var isSignaling: Bool { false }
/// `true` iff `self` is a signaling NaN.
public var isSignalingNaN: Bool { false }
public func isEqual(to other: Decimal) -> Bool {
return self.compare(to: other) == .orderedSame
}
public func isLess(than other: Decimal) -> Bool {
return self.compare(to: other) == .orderedAscending
}
public func isLessThanOrEqualTo(_ other: Decimal) -> Bool {
let comparison = self.compare(to: other)
return comparison == .orderedAscending || comparison == .orderedSame
}
public func isTotallyOrdered(belowOrEqualTo other: Decimal) -> Bool {
// Note: Decimal does not have -0 or infinities to worry about
if self.isNaN {
return false
}
if self < other {
return true
}
if other < self {
return false
}
// Fall through to == behavior
return true
}
@available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.")
public mutating func formTruncatingRemainder(dividingBy other: Decimal) { fatalError("Decimal does not yet fully adopt FloatingPoint") }
}
extension Decimal: _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSDecimalNumber {
return NSDecimalNumber(decimal: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSDecimalNumber, result: inout Decimal?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSDecimalNumber, result: inout Decimal?) -> Bool {
result = x.decimalValue
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDecimalNumber?) -> Decimal {
var result: Decimal?
guard let src = source else { return Decimal(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Decimal(0) }
return result!
}
}
// MARK: - End of conformances shared with Darwin overlay
fileprivate func divideByShort<T:VariableLengthNumber>(_ d: inout T, _ divisor:UInt16) -> (UInt16,NSDecimalNumber.CalculationError) {
if divisor == 0 {
d._length = 0
return (0,.divideByZero)
}
// note the below is not the same as from length to 0 by -1
var carry: UInt32 = 0
for i in (0..<d._length).reversed() {
let accumulator = UInt32(d[i]) + carry * (1<<16)
d[i] = UInt16(accumulator / UInt32(divisor))
carry = accumulator % UInt32(divisor)
}
d.trimTrailingZeros()
return (UInt16(carry),.noError)
}
fileprivate func multiplyByShort<T:VariableLengthNumber>(_ d: inout T, _ mul:UInt16) -> NSDecimalNumber.CalculationError {
if mul == 0 {
d._length = 0
return .noError
}
var carry: UInt32 = 0
// FIXME handle NSCalculationOverflow here?
for i in 0..<d._length {
let accumulator: UInt32 = UInt32(d[i]) * UInt32(mul) + carry
carry = accumulator >> 16
d[i] = UInt16(truncatingIfNeeded: accumulator)
}
if carry != 0 {
if d._length >= Decimal.maxSize {
return .overflow
}
d[d._length] = UInt16(truncatingIfNeeded: carry)
d._length += 1
}
return .noError
}
fileprivate func addShort<T:VariableLengthNumber>(_ d: inout T, _ add:UInt16) -> NSDecimalNumber.CalculationError {
var carry:UInt32 = UInt32(add)
for i in 0..<d._length {
let accumulator: UInt32 = UInt32(d[i]) + carry
carry = accumulator >> 16
d[i] = UInt16(truncatingIfNeeded: accumulator)
}
if carry != 0 {
if d._length >= Decimal.maxSize {
return .overflow
}
d[d._length] = UInt16(truncatingIfNeeded: carry)
d._length += 1
}
return .noError
}
public func NSDecimalIsNotANumber(_ dcm: UnsafePointer<Decimal>) -> Bool {
return dcm.pointee.isNaN
}
/*************** Operations ***********/
public func NSDecimalCopy(_ destination: UnsafeMutablePointer<Decimal>, _ source: UnsafePointer<Decimal>) {
destination.pointee.__lengthAndFlags = source.pointee.__lengthAndFlags
destination.pointee.__exponent = source.pointee.__exponent
destination.pointee.__reserved = source.pointee.__reserved
destination.pointee._mantissa = source.pointee._mantissa
}
public func NSDecimalCompact(_ number: UnsafeMutablePointer<Decimal>) {
number.pointee.compact()
}
// NSDecimalCompare:Compares leftOperand and rightOperand.
public func NSDecimalCompare(_ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>) -> ComparisonResult {
let left = leftOperand.pointee
let right = rightOperand.pointee
return left.compare(to: right)
}
fileprivate extension UInt16 {
func compareTo(_ other: UInt16) -> ComparisonResult {
if self < other {
return .orderedAscending
} else if self > other {
return .orderedDescending
} else {
return .orderedSame
}
}
}
fileprivate func mantissaCompare<T:VariableLengthNumber>(
_ left: T,
_ right: T) -> ComparisonResult {
if left._length > right._length {
return .orderedDescending
}
if left._length < right._length {
return .orderedAscending
}
let length = left._length // == right._length
for i in (0..<length).reversed() {
let comparison = left[i].compareTo(right[i])
if comparison != .orderedSame {
return comparison
}
}
return .orderedSame
}
fileprivate func fitMantissa(_ big: inout WideDecimal, _ exponent: inout Int32, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if big._length <= Decimal.maxSize {
return .noError
}
var remainder: UInt16 = 0
var previousRemainder: Bool = false
// Divide by 10 as much as possible
while big._length > Decimal.maxSize + 1 {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&big,10000)
exponent += 4
}
while big._length > Decimal.maxSize {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&big,10)
exponent += 1
}
// If we are on a tie, adjust with previous remainder.
// .50001 is equivalent to .6
if previousRemainder && (remainder == 0 || remainder == 5) {
remainder += 1
}
if remainder == 0 {
return .noError
}
// Round the result
switch roundingMode {
case .down:
break
case .bankers:
if remainder == 5 && (big[0] & 1) == 0 {
break
}
fallthrough
case .plain:
if remainder < 5 {
break
}
fallthrough
case .up:
let originalLength = big._length
// big._length += 1 ??
_ = addShort(&big,1)
if originalLength > big._length {
// the last digit is == 0. Remove it.
_ = divideByShort(&big, 10)
exponent += 1
}
}
return .lossOfPrecision;
}
fileprivate func integerMultiply<T:VariableLengthNumber>(_ big: inout T,
_ left: T,
_ right: Decimal) -> NSDecimalNumber.CalculationError {
if left._length == 0 || right._length == 0 {
big._length = 0
return .noError
}
if big._length == 0 || big._length > left._length + right._length {
big._length = min(big.maxMantissaLength,left._length + right._length)
}
big.zeroMantissa()
var carry: UInt16 = 0
for j in 0..<right._length {
var accumulator: UInt32 = 0
carry = 0
for i in 0..<left._length {
if i + j < big._length {
let bigij = UInt32(big[i+j])
accumulator = UInt32(carry) + bigij + UInt32(right[j]) * UInt32(left[i])
carry = UInt16(truncatingIfNeeded:accumulator >> 16)
big[i+j] = UInt16(truncatingIfNeeded:accumulator)
} else if carry != 0 || (right[j] == 0 && left[j] == 0) {
return .overflow
}
}
if carry != 0 {
if left._length + j < big._length {
big[left._length + j] = carry
} else {
return .overflow
}
}