-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathDoubleWidth.swift.gyb
1108 lines (946 loc) · 34 KB
/
DoubleWidth.swift.gyb
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
// RUN: %target-run-simple-swiftgyb
// REQUIRES: executable_test
// REQUIRES: CPU=x86_64
import StdlibUnittest
// XXX: Auxiliary tests & benchmark for DoubleWidth were removed in PR #23024.
// When the DoubleWidth makes comeback, revert the commits from there to
// ressurect what was just a dead code in the meantime…
/// A fixed-width integer that has twice the bit width of its base type.
///
/// You can use the `DoubleWidth` type to continue calculations with the result
/// of a full width arithmetic operation. Normally, when you perform a full
/// width operation, the result is a tuple of the high and low parts of the
/// result.
///
/// let a = 2241543570477705381
/// let b = 186319822866995413
/// let c = a.multipliedFullWidth(by: b)
/// // c == (high: 22640526660490081, low: 7959093232766896457)
///
/// The tuple `c` can't be used in any further comparisons or calculations. To
/// use this value, create a `DoubleWidth` instance from the result. You can
/// use the `DoubleWidth` instance in the same way that you would use any other
/// integer type.
///
/// let d = DoubleWidth(a.multipliedFullWidth(by: b))
/// // d == 417644001000058515200174966092417353
///
/// // Check the calculation:
/// print(d / DoubleWidth(a) == b)
/// // Prints "true"
///
/// if d > Int.max {
/// print("Too big to be an 'Int'!")
/// } else {
/// print("Small enough to fit in an 'Int'")
/// }
/// // Prints "Too big to be an 'Int'!"
///
/// The `DoubleWidth` type is not intended as a replacement for a variable-width
/// integer type. Nesting `DoubleWidth` instances, in particular, may result in
/// undesirable performance.
public struct DoubleWidth<Base : FixedWidthInteger> {
public typealias High = Base
public typealias Low = Base.Magnitude
#if _endian(big)
internal var _storage: (high: High, low: Low)
#else
internal var _storage: (low: Low, high: High)
#endif
/// The high part of the value.
public var high: High {
return _storage.high
}
/// The low part of the value.
public var low: Low {
return _storage.low
}
/// Creates a new instance from the given tuple of high and low parts.
///
/// - Parameter value: The tuple to use as the source of the new instance's
/// high and low parts.
public init(_ value: (high: High, low: Low)) {
#if _endian(big)
self._storage = (high: value.0, low: value.1)
#else
self._storage = (low: value.1, high: value.0)
#endif
}
// We expect users to invoke the public initializer above as demonstrated in
// the documentation (that is, by passing in the result of a full width
// operation).
//
// Internally, we'll need to create new instances by supplying high and low
// parts directly; ((double parentheses)) greatly impair readability,
// especially when nested:
//
// DoubleWidth<DoubleWidth>((DoubleWidth((0, 0)), DoubleWidth((0, 0))))
//
// For that reason, we'll include an internal initializer that takes two
// separate arguments.
internal init(_ _high: High, _ low: Low) {
self.init((_high, low))
}
public init() {
self.init(0, 0)
}
}
extension DoubleWidth : CustomStringConvertible {
public var description: String {
return String(self, radix: 10)
}
}
extension DoubleWidth : CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(_storage.high), \(_storage.low))"
}
}
extension DoubleWidth : Equatable {
public static func ==(lhs: DoubleWidth, rhs: DoubleWidth) -> Bool {
return lhs._storage.low == rhs._storage.low
&& lhs._storage.high == rhs._storage.high
}
}
extension DoubleWidth : Comparable {
public static func <(lhs: DoubleWidth, rhs: DoubleWidth) -> Bool {
if lhs._storage.high < rhs._storage.high { return true }
else if lhs._storage.high > rhs._storage.high { return false }
else { return lhs._storage.low < rhs._storage.low }
}
}
extension DoubleWidth : Hashable {
public var hashValue: Int {
return _hashValue(for: self)
}
public func hash(into hasher: inout Hasher) {
hasher.combine(low)
hasher.combine(high)
}
}
extension DoubleWidth : Numeric {
public typealias Magnitude = DoubleWidth<Low>
public var magnitude: Magnitude {
let result = Magnitude(Low(truncatingIfNeeded: _storage.high), _storage.low)
if Base.isSigned && _storage.high < (0 as High) {
return ~result &+ 1
} else {
return result
}
}
internal init(_ _magnitude: Magnitude) {
self.init(High(_magnitude._storage.high), _magnitude._storage.low)
}
public init<T : BinaryInteger>(_ source: T) {
guard let result = DoubleWidth<Base>(exactly: source) else {
preconditionFailure("Value is outside the representable range")
}
self = result
}
public init?<T : BinaryInteger>(exactly source: T) {
// Can't represent a negative 'source' if Base is unsigned.
guard DoubleWidth.isSigned || source >= 0 else { return nil }
// Is 'source' entirely representable in Low?
if let low = Low(exactly: source.magnitude) {
self.init(source < (0 as T) ? (~0, ~low &+ 1) : (0, low))
} else {
// At this point we know source.bitWidth > Base.bitWidth, or else we
// would've taken the first branch.
let lowInT = source & T(~0 as Low)
let highInT = source >> Low.bitWidth
let low = Low(lowInT)
guard let high = High(exactly: highInT) else { return nil }
self.init(high, low)
}
}
}
#if false
// This conformance is only possible once the type is in the stdlib, as it uses
// Builtin
extension DoubleWidth: _ExpressibleByBuiltinIntegerLiteral {
public init(_builtinIntegerLiteral _x: Builtin.IntegerLiteral) {
var _x = _x
self = DoubleWidth()
// If we can capture the entire literal in a single Int64, stop there.
// This avoids some potential deep recursion due to literal expressions in
// other DoubleWidth methods.
let (_value, _overflow) = Builtin.s_to_s_checked_trunc_IntLiteral_Int64(_x)
if !Bool(_overflow) {
self = DoubleWidth(Int64(_value))
return
}
// Convert all but the most significant 64 bits as unsigned integers.
let _shift = Builtin.sext_Int64_IntLiteral((64 as Int64)._value)
let lowWordCount = (bitWidth - 1) / 64
for i in 0..<lowWordCount {
let value =
DoubleWidth(UInt64(Builtin.s_to_u_checked_trunc_IntLiteral_Int64(_x).0))
&<< DoubleWidth(i * 64)
self |= value
_x = Builtin.ashr_IntLiteral(_x, _shift)
}
// Finally, convert the most significant 64 bits and check for overflow.
let overflow: Bool
if Base.isSigned {
let (_value, _overflow) = Builtin.s_to_s_checked_trunc_IntLiteral_Int64(_x)
self |= DoubleWidth(Int64(_value)) &<< DoubleWidth(lowWordCount * 64)
overflow = Bool(_overflow)
} else {
let (_value, _overflow) = Builtin.s_to_u_checked_trunc_IntLiteral_Int64(_x)
self |= DoubleWidth(UInt64(_value)) &<< DoubleWidth(lowWordCount * 64)
overflow = Bool(_overflow)
}
precondition(!overflow, "Literal integer out of range for this type")
}
}
#endif
extension DoubleWidth {
public struct Words {
public var _high: High.Words
public var _low: Low.Words
public init(_ value: DoubleWidth<Base>) {
// Multiples of word size only.
guard Base.bitWidth == Base.Magnitude.bitWidth &&
(UInt.bitWidth % Base.bitWidth == 0 ||
Base.bitWidth % UInt.bitWidth == 0) else {
fatalError("Access to words is not supported on this type")
}
self._high = value._storage.high.words
self._low = value._storage.low.words
assert(!_low.isEmpty)
}
}
}
extension DoubleWidth.Words: RandomAccessCollection {
public typealias Index = Int
public var startIndex: Index {
return 0
}
public var endIndex: Index {
return count
}
public var count: Int {
if Base.bitWidth < UInt.bitWidth { return 1 }
return _low.count + _high.count
}
public subscript(_ i: Index) -> UInt {
if Base.bitWidth < UInt.bitWidth {
precondition(i == 0, "Invalid index")
assert(2 * Base.bitWidth <= UInt.bitWidth)
return _low.first! | (_high.first! &<< Base.bitWidth._lowWord)
}
if i < _low.count {
return _low[i + _low.startIndex]
}
return _high[i - _low.count + _high.startIndex]
}
}
extension DoubleWidth : FixedWidthInteger {
public var words: Words {
return Words(self)
}
public static var isSigned: Bool {
return Base.isSigned
}
public static var max: DoubleWidth {
return self.init(High.max, Low.max)
}
public static var min: DoubleWidth {
return self.init(High.min, Low.min)
}
public static var bitWidth: Int {
return High.bitWidth + Low.bitWidth
}
% for (operator, name) in [('+', 'adding'), ('-', 'subtracting')]:
% highAffectedByLowOverflow = 'Base.max' if operator == '+' else 'Base.min'
public func ${name}ReportingOverflow(_ rhs: DoubleWidth)
-> (partialValue: DoubleWidth, overflow: Bool) {
let (low, lowOverflow) =
_storage.low.${name}ReportingOverflow(rhs._storage.low)
let (high, highOverflow) =
_storage.high.${name}ReportingOverflow(rhs._storage.high)
let result = (high &${operator} (lowOverflow ? 1 : 0), low)
let overflow = highOverflow ||
high == ${highAffectedByLowOverflow} && lowOverflow
return (partialValue: DoubleWidth(result), overflow: overflow)
}
% end
public func multipliedReportingOverflow(
by rhs: DoubleWidth
) -> (partialValue: DoubleWidth, overflow: Bool) {
let (carry, product) = multipliedFullWidth(by: rhs)
let result = DoubleWidth(truncatingIfNeeded: product)
let isNegative = DoubleWidth.isSigned &&
(self < (0 as DoubleWidth)) != (rhs < (0 as DoubleWidth))
let didCarry = isNegative
? carry != ~(0 as DoubleWidth)
: carry != (0 as DoubleWidth)
let hadPositiveOverflow =
DoubleWidth.isSigned && !isNegative && product.leadingZeroBitCount == 0
return (result, didCarry || hadPositiveOverflow)
}
public func quotientAndRemainder(
dividingBy other: DoubleWidth
) -> (quotient: DoubleWidth, remainder: DoubleWidth) {
let (quotient, remainder) =
Magnitude._divide(self.magnitude, by: other.magnitude)
guard DoubleWidth.isSigned else {
return (DoubleWidth(quotient), DoubleWidth(remainder))
}
let isNegative = (self.high < (0 as High)) != (other.high < (0 as High))
let quotient_ = isNegative
? quotient == DoubleWidth.min.magnitude
? DoubleWidth.min
: 0 - DoubleWidth(quotient)
: DoubleWidth(quotient)
let remainder_ = self.high < (0 as High)
? 0 - DoubleWidth(remainder)
: DoubleWidth(remainder)
return (quotient_, remainder_)
}
public func dividedReportingOverflow(
by other: DoubleWidth
) -> (partialValue: DoubleWidth, overflow: Bool) {
if other == (0 as DoubleWidth) { return (self, true) }
if DoubleWidth.isSigned && other == -1 && self == .min {
return (self, true)
}
return (quotientAndRemainder(dividingBy: other).quotient, false)
}
public func remainderReportingOverflow(
dividingBy other: DoubleWidth
) -> (partialValue: DoubleWidth, overflow: Bool) {
if other == (0 as DoubleWidth) { return (self, true) }
if DoubleWidth.isSigned && other == -1 && self == .min { return (0, true) }
return (quotientAndRemainder(dividingBy: other).remainder, false)
}
public func multipliedFullWidth(
by other: DoubleWidth
) -> (high: DoubleWidth, low: DoubleWidth.Magnitude) {
let isNegative = DoubleWidth.isSigned &&
(self < (0 as DoubleWidth)) != (other < (0 as DoubleWidth))
func mul(_ x: Low, _ y: Low) -> (partial: Low, carry: Low) {
let (high, low) = x.multipliedFullWidth(by: y)
return (low, high)
}
func sum(_ x: Low, _ y: Low, _ z: Low) -> (partial: Low, carry: Low) {
let (sum1, overflow1) = x.addingReportingOverflow(y)
let (sum2, overflow2) = sum1.addingReportingOverflow(z)
let carry: Low = (overflow1 ? 1 : 0) + (overflow2 ? 1 : 0)
return (sum2, carry)
}
let lhs = self.magnitude
let rhs = other.magnitude
let a = mul(rhs._storage.low, lhs._storage.low)
let b = mul(rhs._storage.low, lhs._storage.high)
let c = mul(rhs._storage.high, lhs._storage.low)
let d = mul(rhs._storage.high, lhs._storage.high)
let mid1 = sum(a.carry, b.partial, c.partial)
let mid2 = sum(b.carry, c.carry, d.partial)
let low =
DoubleWidth<Low>(mid1.partial, a.partial)
let high =
DoubleWidth(High(mid2.carry + d.carry), mid1.carry + mid2.partial)
if isNegative {
let (lowComplement, overflow) = (~low).addingReportingOverflow(1)
return (~high + (overflow ? 1 : 0 as DoubleWidth), lowComplement)
} else {
return (high, low)
}
}
public func dividingFullWidth(
_ dividend: (high: DoubleWidth, low: DoubleWidth.Magnitude)
) -> (quotient: DoubleWidth, remainder: DoubleWidth) {
let other = DoubleWidth<DoubleWidth>(dividend)
let (quotient, remainder) =
Magnitude._divide(other.magnitude, by: self.magnitude)
guard DoubleWidth.isSigned else {
return (DoubleWidth(quotient), DoubleWidth(remainder))
}
let isNegative =
(self.high < (0 as High)) != (other.high.high < (0 as High))
let quotient_ = isNegative
? quotient == DoubleWidth.min.magnitude
? DoubleWidth.min
: 0 - DoubleWidth(quotient)
: DoubleWidth(quotient)
let remainder_ = other.high.high < (0 as High)
? 0 - DoubleWidth(remainder)
: DoubleWidth(remainder)
return (quotient_, remainder_)
}
% for operator in ['&', '|', '^']:
public static func ${operator}=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
lhs._storage.low ${operator}= rhs._storage.low
lhs._storage.high ${operator}= rhs._storage.high
}
% end
public static func <<=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
if DoubleWidth.isSigned && rhs < (0 as DoubleWidth) {
lhs >>= 0 - rhs
return
}
// Shift is larger than this type's bit width.
if rhs._storage.high != (0 as High) ||
rhs._storage.low >= DoubleWidth.bitWidth
{
lhs = 0
return
}
lhs &<<= rhs
}
public static func >>=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
if DoubleWidth.isSigned && rhs < (0 as DoubleWidth) {
lhs <<= 0 - rhs
return
}
// Shift is larger than this type's bit width.
if rhs._storage.high != (0 as High) ||
rhs._storage.low >= DoubleWidth.bitWidth
{
lhs = lhs < (0 as DoubleWidth) ? ~0 : 0
return
}
lhs &>>= rhs
}
/// Returns this value "masked" by its bit width.
///
/// "Masking" notionally involves repeatedly incrementing or decrementing this
/// value by `self.bitWidth` until the result is contained in the range
/// `0..<self.bitWidth`.
internal func _masked() -> DoubleWidth {
// FIXME(integers): test types with bit widths that aren't powers of 2
if DoubleWidth.bitWidth.nonzeroBitCount == 1 {
return self & DoubleWidth(DoubleWidth.bitWidth &- 1)
}
if DoubleWidth.isSigned && self._storage.high < (0 as High) {
return self % DoubleWidth(DoubleWidth.bitWidth) + self
}
return self % DoubleWidth(DoubleWidth.bitWidth)
}
public static func &<<=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
let rhs = rhs._masked()
guard rhs._storage.low < Base.bitWidth else {
lhs._storage.high = High(
truncatingIfNeeded: lhs._storage.low &<<
(rhs._storage.low &- Low(Base.bitWidth)))
lhs._storage.low = 0
return
}
guard rhs._storage.low != (0 as Low) else { return }
lhs._storage.high &<<= High(rhs._storage.low)
lhs._storage.high |= High(
truncatingIfNeeded: lhs._storage.low &>>
(Low(Base.bitWidth) &- rhs._storage.low))
lhs._storage.low &<<= rhs._storage.low
}
public static func &>>=(lhs: inout DoubleWidth, rhs: DoubleWidth) {
let rhs = rhs._masked()
guard rhs._storage.low < Base.bitWidth else {
lhs._storage.low = Low(
truncatingIfNeeded: lhs._storage.high &>>
High(rhs._storage.low &- Low(Base.bitWidth)))
lhs._storage.high = lhs._storage.high < (0 as High) ? ~0 : 0
return
}
guard rhs._storage.low != (0 as Low) else { return }
lhs._storage.low &>>= rhs._storage.low
lhs._storage.low |= Low(
truncatingIfNeeded: lhs._storage.high &<<
High(Low(Base.bitWidth) &- rhs._storage.low))
lhs._storage.high &>>= High(rhs._storage.low)
}
%{
binaryOperators = [
('+', 'adding', '_', '+'),
('-', 'subtracting', '_', '-'),
('*', 'multiplied', 'by', '*'),
('/', 'divided', 'by', '/'),
('%', 'remainder', 'dividingBy', '/'),
]
}%
% for (operator, name, firstArg, kind) in binaryOperators:
// FIXME(integers): remove this once the operators are back to Numeric
public static func ${operator} (
lhs: DoubleWidth, rhs: DoubleWidth
) -> DoubleWidth {
var lhs = lhs
lhs ${operator}= rhs
return lhs
}
% argumentLabel = (firstArg + ':') if firstArg != '_' else ''
public static func ${operator}=(
lhs: inout DoubleWidth, rhs: DoubleWidth
) {
let (result, overflow) = lhs.${name}ReportingOverflow(${argumentLabel}rhs)
precondition(!overflow, "Overflow in ${operator}=")
lhs = result
}
% end
public init(_truncatingBits bits: UInt) {
_storage.low = Low(_truncatingBits: bits)
_storage.high = High(_truncatingBits: bits >> UInt(Low.bitWidth))
}
public init(integerLiteral x: Int) {
self.init(x)
}
public var leadingZeroBitCount: Int {
return high == (0 as High)
? High.bitWidth + low.leadingZeroBitCount
: high.leadingZeroBitCount
}
public var trailingZeroBitCount: Int {
return low == (0 as Low)
? Low.bitWidth + high.trailingZeroBitCount
: low.trailingZeroBitCount
}
public var nonzeroBitCount: Int {
return high.nonzeroBitCount + low.nonzeroBitCount
}
public var byteSwapped: DoubleWidth {
return DoubleWidth(
High(truncatingIfNeeded: low.byteSwapped),
Low(truncatingIfNeeded: high.byteSwapped))
}
}
extension DoubleWidth : UnsignedInteger where Base : UnsignedInteger {
/// Returns the quotient and remainder after dividing a triple-width magnitude
/// `lhs` by a double-width magnitude `rhs`.
///
/// This operation is conceptually that described by Burnikel and Ziegler
/// (1998).
internal static func _divide(
_ lhs: (high: Low, mid: Low, low: Low), by rhs: Magnitude
) -> (quotient: Low, remainder: Magnitude) {
// The following invariants are guaranteed to hold by dividingFullWidth or
// quotientAndRemainder before this method is invoked:
assert(lhs.high != (0 as Low))
assert(rhs.leadingZeroBitCount == 0)
assert(Magnitude(lhs.high, lhs.mid) < rhs)
// Estimate the quotient.
var quotient = lhs.high == rhs.high
? Low.max
: rhs.high.dividingFullWidth((lhs.high, lhs.mid)).quotient
// Compute quotient * rhs.
// TODO: This could be performed more efficiently.
var product =
DoubleWidth<Magnitude>(
0, Magnitude(quotient.multipliedFullWidth(by: rhs.low)))
let (x, y) = quotient.multipliedFullWidth(by: rhs.high)
product += DoubleWidth<Magnitude>(Magnitude(0, x), Magnitude(y, 0))
// Compute the remainder after decrementing quotient as necessary.
var remainder =
DoubleWidth<Magnitude>(
Magnitude(0, lhs.high), Magnitude(lhs.mid, lhs.low))
while remainder < product {
quotient = quotient &- 1
remainder += DoubleWidth<Magnitude>(0, rhs)
}
remainder -= product
return (quotient, remainder.low)
}
/// Returns the quotient and remainder after dividing a quadruple-width
/// magnitude `lhs` by a double-width magnitude `rhs`.
internal static func _divide(
_ lhs: DoubleWidth<Magnitude>, by rhs: Magnitude
) -> (quotient: Magnitude, remainder: Magnitude) {
guard _fastPath(rhs > (0 as Magnitude)) else {
fatalError("Division by zero")
}
guard _fastPath(rhs >= lhs.high) else {
fatalError("Division results in an overflow")
}
if lhs.high == (0 as Magnitude) {
return lhs.low.quotientAndRemainder(dividingBy: rhs)
}
if rhs.high == (0 as Low) {
let a = lhs.high.high % rhs.low
let b = a == (0 as Low)
? lhs.high.low % rhs.low
: rhs.low.dividingFullWidth((a, lhs.high.low)).remainder
let (x, c) = b == (0 as Low)
? lhs.low.high.quotientAndRemainder(dividingBy: rhs.low)
: rhs.low.dividingFullWidth((b, lhs.low.high))
let (y, d) = c == (0 as Low)
? lhs.low.low.quotientAndRemainder(dividingBy: rhs.low)
: rhs.low.dividingFullWidth((c, lhs.low.low))
return (Magnitude(x, y), Magnitude(0, d))
}
// Left shift both rhs and lhs, then divide and right shift the remainder.
let shift = rhs.leadingZeroBitCount
let rhs = rhs &<< shift
let lhs = lhs &<< shift
if lhs.high.high == (0 as Low)
&& Magnitude(lhs.high.low, lhs.low.high) < rhs {
let (quotient, remainder) =
Magnitude._divide((lhs.high.low, lhs.low.high, lhs.low.low), by: rhs)
return (Magnitude(0, quotient), remainder &>> shift)
}
let (x, a) =
Magnitude._divide((lhs.high.high, lhs.high.low, lhs.low.high), by: rhs)
let (y, b) =
Magnitude._divide((a.high, a.low, lhs.low.low), by: rhs)
return (Magnitude(x, y), b &>> shift)
}
/// Returns the quotient and remainder after dividing a double-width
/// magnitude `lhs` by a double-width magnitude `rhs`.
internal static func _divide(
_ lhs: Magnitude, by rhs: Magnitude
) -> (quotient: Magnitude, remainder: Magnitude) {
guard _fastPath(rhs > (0 as Magnitude)) else {
fatalError("Division by zero")
}
guard rhs < lhs else {
if _fastPath(rhs > lhs) { return (0, lhs) }
return (1, 0)
}
if lhs.high == (0 as Low) {
let (quotient, remainder) =
lhs.low.quotientAndRemainder(dividingBy: rhs.low)
return (Magnitude(quotient), Magnitude(remainder))
}
if rhs.high == (0 as Low) {
let (x, a) = lhs.high.quotientAndRemainder(dividingBy: rhs.low)
let (y, b) = a == (0 as Low)
? lhs.low.quotientAndRemainder(dividingBy: rhs.low)
: rhs.low.dividingFullWidth((a, lhs.low))
return (Magnitude(x, y), Magnitude(0, b))
}
// Left shift both rhs and lhs, then divide and right shift the remainder.
let shift = rhs.leadingZeroBitCount
let rhs = rhs &<< shift
let high = (lhs &>> (Magnitude.bitWidth &- shift)).low
let lhs = lhs &<< shift
let (quotient, remainder) =
Magnitude._divide((high, lhs.high, lhs.low), by: rhs)
return (Magnitude(0, quotient), remainder &>> shift)
}
}
extension DoubleWidth : SignedNumeric, SignedInteger
where Base : SignedInteger {}
//===----------------------------------------------------------------------===//
// Tests
//===----------------------------------------------------------------------===//
var dwTests = TestSuite("DoubleWidth")
typealias UInt128 = DoubleWidth<UInt64>
typealias UInt256 = DoubleWidth<UInt128>
typealias UInt512 = DoubleWidth<UInt256>
typealias UInt1024 = DoubleWidth<UInt512>
typealias Int128 = DoubleWidth<Int64>
typealias Int256 = DoubleWidth<Int128>
typealias Int512 = DoubleWidth<Int256>
typealias Int1024 = DoubleWidth<Int512>
func checkSignedIntegerConformance<T: SignedInteger>(_ x: T) {}
func checkUnsignedIntegerConformance<T: UnsignedInteger>(_ x: T) {}
dwTests.test("Literals") {
let w: DoubleWidth<UInt8> = 100
expectTrue(w == 100 as Int)
let x: DoubleWidth<UInt8> = 1000
expectTrue(x == 1000 as Int)
let y: DoubleWidth<Int8> = 1000
expectTrue(y == 1000 as Int)
let z: DoubleWidth<Int8> = -1000
expectTrue(z == -1000 as Int)
expectCrashLater()
_ = -1 as DoubleWidth<UInt8>
}
#if false
// Uncomment these tests once _ExpressibleByBuiltinIntegerLiteral
// conformance is available
dwTests.test("Literals/Large/Signed") {
let a: Int256 =
0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
let b: Int256 =
-0x8000000000000000000000000000000000000000000000000000000000000000
expectEqual(a, Int256.max)
expectEqual(b, Int256.min)
expectCrashLater()
_ = -0x8000000000000000000000000000000000000000000000000000000000000001
as Int256
}
dwTests.test("Literals/Large/SignedOverflow") {
expectCrashLater()
_ = 0x8000000000000000000000000000000000000000000000000000000000000000
as Int256
}
dwTests.test("Literals/Large/Unsigned") {
let a: UInt256 =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
let b: UInt256 = 0
expectEqual(a, UInt256.max)
expectEqual(b, UInt256.min)
expectCrashLater()
_ = -1 as UInt256
}
dwTests.test("Literals/Large/UnsignedOverflow") {
expectCrashLater()
_ = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0
as UInt256
}
#endif
dwTests.test("Arithmetic/unsigned") {
let x: DoubleWidth<UInt8> = 1000
let y: DoubleWidth<UInt8> = 1111
expectEqual(x + 1, 1001)
expectEqual(x + x, 2000)
expectEqual(x - (1 as DoubleWidth<UInt8>), 999)
expectEqual(x - x, 0)
expectEqual(y - x, 111)
expectEqual(x * 7, 7000)
expectEqual(y * 7, 7777)
expectEqual(x / 3, 333)
expectEqual(x / x, 1)
expectEqual(x / y, 0)
expectEqual(y / x, 1)
expectEqual(x % 3, 1)
expectEqual(x % y, x)
}
dwTests.test("Arithmetic/signed") {
let x: DoubleWidth<Int8> = 1000
let y: DoubleWidth<Int8> = -1111
expectEqual(x + 1, 1001)
expectEqual(x + x, 2000)
expectEqual(x - (1 as DoubleWidth<Int8>), 999)
expectEqual(x - x, 0)
expectEqual(0 - x, -1000)
expectEqual(x + y, -111)
expectEqual(x - y, 2111)
expectEqual(x * 7, 7000)
expectEqual(y * 7, -7777)
expectEqual(x * -7, -7000)
expectEqual(y * -7, 7777)
expectEqual(x / 3, 333)
expectEqual(x / -3, -333)
expectEqual(x / x, 1)
expectEqual(x / y, 0)
expectEqual(y / x, -1)
expectEqual(y / y, 1)
expectEqual(x % 3, 1)
expectEqual(x % -3, 1)
expectEqual(y % 3, -1)
expectEqual(y % -3, -1)
expectEqual(-y, 1111)
expectEqual(-x, -1000)
}
dwTests.test("Nested") {
do {
let x = UInt1024.max
let (y, o) = x.addingReportingOverflow(1)
expectEqual(y, 0)
expectTrue(y == (0 as Int))
expectTrue(o)
}
do {
let x = Int1024.max
let (y, o) = x.addingReportingOverflow(1)
expectEqual(y, Int1024.min)
expectLT(y, 0)
expectTrue(y < (0 as Int))
expectTrue(y < (0 as UInt))
expectTrue(o)
}
expectFalse(UInt1024.isSigned)
expectEqual(UInt1024.bitWidth, 1024)
expectTrue(Int1024.isSigned)
expectEqual(Int1024.bitWidth, 1024)
expectEqualSequence(
UInt1024.max.words, repeatElement(UInt.max, count: 1024 / UInt.bitWidth))
}
dwTests.test("inits") {
typealias DWU16 = DoubleWidth<UInt8>
expectTrue(DWU16(UInt16.max) == UInt16.max)
expectNil(DWU16(exactly: UInt32.max))
expectEqual(DWU16(truncatingIfNeeded: UInt64.max), DWU16.max)
expectCrashLater()
_ = DWU16(UInt32.max)
}
dwTests.test("Magnitude") {
typealias DWU16 = DoubleWidth<UInt8>
typealias DWI16 = DoubleWidth<Int8>
expectTrue(DWU16.min.magnitude == UInt16.min.magnitude)
expectTrue((42 as DWU16).magnitude == (42 as UInt16).magnitude)
expectTrue(DWU16.max.magnitude == UInt16.max.magnitude)
expectTrue(DWI16.min.magnitude == Int16.min.magnitude)
expectTrue((-42 as DWI16).magnitude == (-42 as Int16).magnitude)
expectTrue(DWI16().magnitude == Int16(0).magnitude) // See SR-6602.
expectTrue((42 as DWI16).magnitude == (42 as Int16).magnitude)
expectTrue(DWI16.max.magnitude == Int16.max.magnitude)
}
dwTests.test("TwoWords") {
typealias DW = DoubleWidth<Int>
expectEqual(-1 as DW, DW(truncatingIfNeeded: -1 as Int8))
expectNil(Int(exactly: DW(Int.min) - 1))
expectNil(Int(exactly: DW(Int.max) + 1))
expectTrue(DW(Int.min) - 1 < Int.min)
expectTrue(DW(Int.max) + 1 > Int.max)
}
dwTests.test("Bitshifts") {
typealias DWU64 = DoubleWidth<DoubleWidth<DoubleWidth<UInt8>>>
typealias DWI64 = DoubleWidth<DoubleWidth<DoubleWidth<Int8>>>
func f<T: FixedWidthInteger, U: FixedWidthInteger>(_ x: T, type: U.Type) {
let y = U(x)
expectEqual(T.bitWidth, U.bitWidth)
for i in -(T.bitWidth + 1)...(T.bitWidth + 1) {
expectTrue(x << i == y << i)
expectTrue(x >> i == y >> i)
expectTrue(x &<< i == y &<< i)
expectTrue(x &>> i == y &>> i)
}
}
f(1 as UInt64, type: DWU64.self)
f(~(~0 as UInt64 >> 1), type: DWU64.self)
f(UInt64.max, type: DWU64.self)
// 0b01010101_10100101_11110000_10100101_11110000_10100101_11110000_10100101
f(17340530535757639845 as UInt64, type: DWU64.self)
f(1 as Int64, type: DWI64.self)
f(Int64.min, type: DWI64.self)
f(Int64.max, type: DWI64.self)
// 0b01010101_10100101_11110000_10100101_11110000_10100101_11110000_10100101
f(6171603459878809765 as Int64, type: DWI64.self)
}
dwTests.test("Remainder/DividingBy0") {
func f(_ x: Int1024, _ y: Int1024) -> Int1024 {
return x % y
}
expectCrashLater()
_ = f(42, 0)
}
dwTests.test("RemainderReportingOverflow/DividingByMinusOne") {
func f(_ x: Int256, _ y: Int256) -> Int256 {
return x.remainderReportingOverflow(dividingBy: y).partialValue
}
expectEqual(f(.max, -1), 0)
expectEqual(f(.min, -1), 0)
}
dwTests.test("Division/By0") {
func f(_ x: Int1024, _ y: Int1024) -> Int1024 {
return x / y
}
expectCrashLater()
_ = f(42, 0)
}
dwTests.test("DivideMinByMinusOne") {
func f(_ x: Int1024) -> Int1024 {
return x / -1
}
expectCrashLater()
_ = f(Int1024.min)
}
dwTests.test("isMultiple") {
func isMultipleTest<T: FixedWidthInteger>(type: T.Type) {
expectTrue(T.min.isMultiple(of: 2))
expectFalse(T.max.isMultiple(of: 10))
// Test that these do not crash.
expectTrue((0 as T).isMultiple(of: 0))
expectFalse((1 as T).isMultiple(of: 0))
expectTrue(T.min.isMultiple(of: 0 &- 1))
}
isMultipleTest(type: Int128.self)
isMultipleTest(type: UInt128.self)
}
dwTests.test("MultiplyMinByMinusOne") {
func f(_ x: Int1024) -> Int1024 {
return x * -1
}
expectCrashLater()
_ = f(Int1024.min)
}
typealias DWI16 = DoubleWidth<Int8>
typealias DWU16 = DoubleWidth<UInt8>
dwTests.test("Conversions") {
expectTrue(DWI16(1 << 15 - 1) == Int(1 << 15 - 1))
expectTrue(DWI16(-1 << 15) == Int(-1 << 15))
expectTrue(DWU16(1 << 16 - 1) == Int(1 << 16 - 1))
expectTrue(DWU16(0) == Int(0))
expectTrue(DWI16(Double(1 << 15 - 1)) == Int(1 << 15 - 1))
expectTrue(DWI16(Double(-1 << 15)) == Int(-1 << 15))