-
-
Notifications
You must be signed in to change notification settings - Fork 700
/
bigint.d
2355 lines (2071 loc) · 69.3 KB
/
bigint.d
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
/** Arbitrary-precision ('bignum') arithmetic.
*
* Performance is optimized for numbers below ~1000 decimal digits.
* For X86 machines, highly optimised assembly routines are used.
*
* The following algorithms are currently implemented:
* $(UL
* $(LI Karatsuba multiplication)
* $(LI Squaring is optimized independently of multiplication)
* $(LI Divide-and-conquer division)
* $(LI Binary exponentiation)
* )
*
* For very large numbers, consider using the $(HTTP gmplib.org, GMP library) instead.
*
* License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: Don Clugston
* Source: $(PHOBOSSRC std/bigint.d)
*/
/* Copyright Don Clugston 2008 - 2010.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
module std.bigint;
import std.conv : ConvException;
import std.format.spec : FormatSpec;
import std.format : FormatException;
import std.internal.math.biguintcore;
import std.internal.math.biguintnoasm : BigDigit;
import std.range.primitives;
import std.traits;
/** A struct representing an arbitrary precision integer.
*
* All arithmetic operations are supported, except unsigned shift right (`>>>`).
* Bitwise operations (`|`, `&`, `^`, `~`) are supported, and behave as if BigInt was
* an infinite length 2's complement number.
*
* BigInt implements value semantics using copy-on-write. This means that
* assignment is cheap, but operations such as x++ will cause heap
* allocation. (But note that for most bigint operations, heap allocation is
* inevitable anyway.)
*/
struct BigInt
{
private:
BigUint data; // BigInt adds signed arithmetic to BigUint.
bool sign = false;
public:
/**
* Construct a `BigInt` from a decimal or hexadecimal string. The number must
* be in the form of a decimal or hex literal. It may have a leading `+`
* or `-` sign, followed by `0x` or `0X` if hexadecimal. Underscores are
* permitted in any location after the `0x` and/or the sign of the number.
*
* Params:
* s = a finite bidirectional range of any character type
*
* Throws:
* $(REF ConvException, std,conv) if the string doesn't represent a valid number
*/
this(Range)(Range s) if (
isBidirectionalRange!Range &&
isSomeChar!(ElementType!Range) &&
!isInfinite!Range &&
!isNarrowString!Range)
{
import std.algorithm.iteration : filterBidirectional;
import std.algorithm.searching : startsWith;
import std.conv : ConvException;
import std.exception : enforce;
import std.utf : byChar;
enforce!ConvException(!s.empty, "Can't initialize BigInt with an empty range");
bool neg = false;
bool ok;
data = 0UL;
// check for signs and if the string is a hex value
if (s.front == '+')
{
s.popFront(); // skip '+'
}
else if (s.front == '-')
{
neg = true;
s.popFront();
}
if (s.save.startsWith("0x".byChar) ||
s.save.startsWith("0X".byChar))
{
s.popFront;
s.popFront;
if (!s.empty)
ok = data.fromHexString(s.filterBidirectional!(a => a != '_'));
else
ok = false;
}
else
{
ok = data.fromDecimalString(s.filterBidirectional!(a => a != '_'));
}
enforce!ConvException(ok, "Not a valid numerical string");
if (isZero())
neg = false;
sign = neg;
}
/// ditto
this(Range)(Range s) pure
if (isNarrowString!Range)
{
import std.utf : byCodeUnit;
this(s.byCodeUnit);
}
@safe unittest
{
// system because of the dummy ranges eventually call std.array!string
import std.exception : assertThrown;
import std.internal.test.dummyrange;
auto r1 = new ReferenceBidirectionalRange!dchar("101");
auto big1 = BigInt(r1);
assert(big1 == BigInt(101));
auto r2 = new ReferenceBidirectionalRange!dchar("1_000");
auto big2 = BigInt(r2);
assert(big2 == BigInt(1000));
auto r3 = new ReferenceBidirectionalRange!dchar("0x0");
auto big3 = BigInt(r3);
assert(big3 == BigInt(0));
auto r4 = new ReferenceBidirectionalRange!dchar("0x");
assertThrown!ConvException(BigInt(r4));
}
/**
* Construct a `BigInt` from a sign and a magnitude.
*
* The magnitude is an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
* of unsigned integers that satisfies either $(REF hasLength, std,range,primitives)
* or $(REF isForwardRange, std,range,primitives). The first (leftmost)
* element of the magnitude is considered the most significant.
*
* Params:
* isNegative = true for negative, false for non-negative
* (ignored when magnitude is zero)
* magnitude = a finite range of unsigned integers
*/
this(Range)(bool isNegative, Range magnitude) if (
isInputRange!Range &&
isUnsigned!(ElementType!Range) &&
(hasLength!Range || isForwardRange!Range) &&
!isInfinite!Range)
{
data.fromMagnitude(magnitude);
sign = isNegative && !data.isZero;
}
///
pure @safe unittest
{
ubyte[] magnitude = [1, 2, 3, 4, 5, 6];
auto b1 = BigInt(false, magnitude);
assert(cast(long) b1 == 0x01_02_03_04_05_06L);
auto b2 = BigInt(true, magnitude);
assert(cast(long) b2 == -0x01_02_03_04_05_06L);
}
/// Construct a `BigInt` from a built-in integral type.
this(T)(T x) pure nothrow @safe if (isIntegral!T)
{
data = data.init; // @@@: Workaround for compiler bug
opAssign(x);
}
///
@safe unittest
{
ulong data = 1_000_000_000_000;
auto bigData = BigInt(data);
assert(bigData == BigInt("1_000_000_000_000"));
}
/// Construct a `BigInt` from another `BigInt`.
this(T)(T x) pure nothrow @safe if (is(immutable T == immutable BigInt))
{
opAssign(x);
}
///
@safe unittest
{
const(BigInt) b1 = BigInt("1_234_567_890");
BigInt b2 = BigInt(b1);
assert(b2 == BigInt("1_234_567_890"));
}
/// Assignment from built-in integer types.
BigInt opAssign(T)(T x) pure nothrow @safe if (isIntegral!T)
{
data = cast(ulong) absUnsign(x);
sign = (x < 0);
return this;
}
///
@safe unittest
{
auto b = BigInt("123");
b = 456;
assert(b == BigInt("456"));
}
/// Assignment from another BigInt.
BigInt opAssign(T:BigInt)(T x) pure @nogc @safe
{
data = x.data;
sign = x.sign;
return this;
}
///
@safe unittest
{
auto b1 = BigInt("123");
auto b2 = BigInt("456");
b2 = b1;
assert(b2 == BigInt("123"));
}
/**
* Implements assignment operators from built-in integers of the form
* `BigInt op= integer`.
*/
BigInt opOpAssign(string op, T)(T y) pure nothrow @safe
if ((op=="+" || op=="-" || op=="*" || op=="/" || op=="%"
|| op==">>" || op=="<<" || op=="^^" || op=="|" || op=="&" || op=="^") && isIntegral!T)
{
ulong u = absUnsign(y);
static if (op=="+")
{
data = BigUint.addOrSubInt(data, u, sign != (y<0), sign);
}
else static if (op=="-")
{
data = BigUint.addOrSubInt(data, u, sign == (y<0), sign);
}
else static if (op=="*")
{
if (y == 0)
{
sign = false;
data = 0UL;
}
else
{
sign = ( sign != (y<0) );
data = BigUint.mulInt(data, u);
}
}
else static if (op=="/")
{
assert(y != 0, "Division by zero");
static if (T.sizeof <= uint.sizeof)
{
data = BigUint.divInt(data, cast(uint) u);
}
else
{
data = BigUint.divInt(data, u);
}
sign = data.isZero() ? false : sign ^ (y < 0);
}
else static if (op=="%")
{
assert(y != 0, "Division by zero");
static if (is(immutable(T) == immutable(long)) || is( immutable(T) == immutable(ulong) ))
{
this %= BigInt(y);
}
else
{
data = cast(ulong) BigUint.modInt(data, cast(uint) u);
if (data.isZero())
sign = false;
}
// x%y always has the same sign as x.
// This is not the same as mathematical mod.
}
else static if (op==">>" || op=="<<")
{
// Do a left shift if y>0 and <<, or
// if y<0 and >>; else do a right shift.
if (y == 0)
return this;
else if ((y > 0) == (op=="<<"))
{
// Sign never changes during left shift
data = data.opBinary!(op)(u);
}
else
{
data = data.opBinary!(op)(u);
if (data.isZero())
sign = false;
}
}
else static if (op=="^^")
{
sign = (y & 1) ? sign : false;
data = BigUint.pow(data, u);
}
else static if (op=="&")
{
if (y >= 0 && (y <= 1 || !sign)) // In these cases we can avoid some allocation.
{
static if (T.sizeof <= uint.sizeof && BigDigit.sizeof <= uint.sizeof)
data = cast(ulong) data.peekUint(0) & y;
else
data = data.peekUlong(0) & y;
sign = false;
}
else
{
BigInt b = y;
opOpAssign!op(b);
}
}
else static if (op=="|" || op=="^")
{
BigInt b = y;
opOpAssign!op(b);
}
else static assert(0, "BigInt " ~ op[0..$-1] ~ "= " ~ T.stringof ~ " is not supported");
return this;
}
///
@safe unittest
{
auto b = BigInt("1_000_000_000");
b += 12345;
assert(b == BigInt("1_000_012_345"));
b /= 5;
assert(b == BigInt("200_002_469"));
}
// https://issues.dlang.org/show_bug.cgi?id=16264
@safe unittest
{
auto a = BigInt(
`335690982744637013564796917901053301979460129353374296317539383938630086938` ~
`465898213033510992292836631752875403891802201862860531801760096359705447768` ~
`957432600293361240407059207520920532482429912948952142341440301429494694368` ~
`264560802292927144211230021750155988283029753927847924288850436812178022006` ~
`408597793414273953252832688620479083497367463977081627995406363446761896298` ~
`967177607401918269561385622811274398143647535024987050366350585544531063531` ~
`7118554808325723941557169427279911052268935775`);
auto b = BigInt(
`207672245542926038535480439528441949928508406405023044025560363701392340829` ~
`852529131306106648201340460604257466180580583656068555417076345439694125326` ~
`843947164365500055567495554645796102453565953360564114634705366335703491527` ~
`429426780005741168078089657359833601261803592920462081364401456331489106355` ~
`199133982282631108670436696758342051198891939367812305559960349479160308314` ~
`068518200681530999860641597181672463704794566473241690395901768680673716414` ~
`243691584391572899147223065906633310537507956952626106509069491302359792769` ~
`378934570685117202046921464019396759638376362935855896435623442486036961070` ~
`534574698959398017332214518246531363445309522357827985468581166065335726996` ~
`711467464306784543112544076165391268106101754253962102479935962248302404638` ~
`21737237102628470475027851189594709504`);
BigInt c = a * b; // Crashes
assert(c == BigInt(
`697137001950904057507249234183127244116872349433141878383548259425589716813` ~
`135440660252012378417669596912108637127036044977634382385990472429604619344` ~
`738746224291111527200379708978133071390303850450970292020176369525401803474` ~
`998613408923490273129022167907826017408385746675184651576154302536663744109` ~
`111018961065316024005076097634601030334948684412785487182572502394847587887` ~
`507385831062796361152176364659197432600147716058873232435238712648552844428` ~
`058885217631715287816333209463171932255049134340904981280717725999710525214` ~
`161541960645335744430049558161514565159449390036287489478108344584188898872` ~
`434914159748515512161981956372737022393466624249130107254611846175580584736` ~
`276213025837422102290580044755202968610542057651282410252208599309841499843` ~
`672251048622223867183370008181364966502137725166782667358559333222947265344` ~
`524195551978394625568228658697170315141077913403482061673401937141405425042` ~
`283546509102861986303306729882186190883772633960389974665467972016939172303` ~
`653623175801495207204880400522581834672918935651426160175413277309985678579` ~
`830872397214091472424064274864210953551447463312267310436493480881235642109` ~
`668498742629676513172286703948381906930297135997498416573231570483993847269` ~
`479552708416124555462530834668011570929850407031109157206202741051573633443` ~
`58105600`
));
}
/**
* Implements assignment operators of the form `BigInt op= BigInt`.
*/
BigInt opOpAssign(string op, T)(T y) pure nothrow @safe
if ((op=="+" || op== "-" || op=="*" || op=="|" || op=="&" || op=="^" || op=="/" || op=="%")
&& is (T: BigInt))
{
static if (op == "+")
{
data = BigUint.addOrSub(data, y.data, sign != y.sign, &sign);
}
else static if (op == "-")
{
data = BigUint.addOrSub(data, y.data, sign == y.sign, &sign);
}
else static if (op == "*")
{
data = BigUint.mul(data, y.data);
sign = isZero() ? false : sign ^ y.sign;
}
else static if (op == "/")
{
y.checkDivByZero();
if (!isZero())
{
data = BigUint.div(data, y.data);
sign = isZero() ? false : sign ^ y.sign;
}
}
else static if (op == "%")
{
y.checkDivByZero();
if (!isZero())
{
data = BigUint.mod(data, y.data);
// x%y always has the same sign as x.
if (isZero())
sign = false;
}
}
else static if (op == "|" || op == "&" || op == "^")
{
data = BigUint.bitwiseOp!op(data, y.data, sign, y.sign, sign);
}
else static assert(0, "BigInt " ~ op[0..$-1] ~ "= " ~
T.stringof ~ " is not supported");
return this;
}
///
@safe unittest
{
auto x = BigInt("123");
auto y = BigInt("321");
x += y;
assert(x == BigInt("444"));
}
/**
* Implements binary operators between `BigInt`s.
*/
BigInt opBinary(string op, T)(T y) pure nothrow @safe const
if ((op=="+" || op == "*" || op=="-" || op=="|" || op=="&" || op=="^" ||
op=="/" || op=="%")
&& is (T: BigInt))
{
BigInt r = this;
return r.opOpAssign!(op)(y);
}
///
@safe unittest
{
auto x = BigInt("123");
auto y = BigInt("456");
BigInt z = x * y;
assert(z == BigInt("56088"));
}
/**
* Implements binary operators between `BigInt`'s and built-in integers.
*/
BigInt opBinary(string op, T)(T y) pure nothrow @safe const
if ((op=="+" || op == "*" || op=="-" || op=="/" || op=="|" || op=="&" ||
op=="^"|| op==">>" || op=="<<" || op=="^^")
&& isIntegral!T)
{
BigInt r = this;
return r.opOpAssign!(op)(y);
}
///
@safe unittest
{
auto x = BigInt("123");
x *= 300;
assert(x == BigInt("36900"));
}
/**
Implements a narrowing remainder operation with built-in integer types.
This binary operator returns a narrower, built-in integer type
where applicable, according to the following table.
$(TABLE ,
$(TR $(TD `BigInt`) $(TD $(CODE_PERCENT)) $(TD `uint`) $(TD $(RARR)) $(TD `long`))
$(TR $(TD `BigInt`) $(TD $(CODE_PERCENT)) $(TD `long`) $(TD $(RARR)) $(TD `long`))
$(TR $(TD `BigInt`) $(TD $(CODE_PERCENT)) $(TD `ulong`) $(TD $(RARR)) $(TD `BigInt`))
$(TR $(TD `BigInt`) $(TD $(CODE_PERCENT)) $(TD other type) $(TD $(RARR)) $(TD `int`))
)
*/
auto opBinary(string op, T)(T y) pure nothrow @safe const
if (op == "%" && isIntegral!T)
{
assert(y != 0, "% 0 not allowed");
// BigInt % uint => long
// BigInt % long => long
// BigInt % ulong => BigInt
// BigInt % other_type => int
static if (is(immutable T == immutable long) || is(immutable T == immutable ulong))
{
auto r = this % BigInt(y);
static if (is(immutable T == immutable long))
{
return r.toLong();
}
else
{
// return as-is to avoid overflow
return r;
}
}
else
{
immutable uint u = absUnsign(y);
static if (is(immutable T == immutable uint))
alias R = long;
else
alias R = int;
R rem = BigUint.modInt(data, u);
// x%y always has the same sign as x.
// This is not the same as mathematical mod.
return sign ? -rem : rem;
}
}
///
@safe unittest
{
auto x = BigInt("1_000_000_500");
long l = 1_000_000L;
ulong ul = 2_000_000UL;
int i = 500_000;
short s = 30_000;
assert(is(typeof(x % l) == long) && x % l == 500L);
assert(is(typeof(x % ul) == BigInt) && x % ul == BigInt(500));
assert(is(typeof(x % i) == int) && x % i == 500);
assert(is(typeof(x % s) == int) && x % s == 10500);
}
/**
Implements operators with built-in integers on the left-hand side and
`BigInt` on the right-hand side.
*/
BigInt opBinaryRight(string op, T)(T y) pure nothrow @safe const
if ((op=="+" || op=="*" || op=="|" || op=="&" || op=="^") && isIntegral!T)
{
return opBinary!(op)(y);
}
///
@safe unittest
{
auto x = BigInt("100");
BigInt y = 123 + x;
assert(y == BigInt("223"));
BigInt z = 123 - x;
assert(z == BigInt("23"));
// Dividing a built-in integer type by BigInt always results in
// something that fits in a built-in type, so the built-in type is
// returned, not BigInt.
assert(is(typeof(1000 / x) == int));
assert(1000 / x == 10);
}
// BigInt = integer op BigInt
/// ditto
BigInt opBinaryRight(string op, T)(T y) pure nothrow @safe const
if (op == "-" && isIntegral!T)
{
ulong u = absUnsign(y);
BigInt r;
static if (op == "-")
{
r.sign = sign;
r.data = BigUint.addOrSubInt(data, u, sign == (y<0), r.sign);
r.negate();
}
return r;
}
// integer = integer op BigInt
/// ditto
T opBinaryRight(string op, T)(T x) pure nothrow @safe const
if ((op=="%" || op=="/") && isIntegral!T)
{
checkDivByZero();
static if (op == "%")
{
// x%y always has the same sign as x.
if (data.ulongLength > 1)
return x;
immutable u = absUnsign(x);
immutable rem = u % data.peekUlong(0);
// x%y always has the same sign as x.
return cast(T)((x<0) ? -rem : rem);
}
else static if (op == "/")
{
if (data.ulongLength > 1)
return 0;
return cast(T)(x / data.peekUlong(0));
}
}
// const unary operations
/**
Implements `BigInt` unary operators.
*/
BigInt opUnary(string op)() pure nothrow @safe const if (op=="+" || op=="-" || op=="~")
{
static if (op=="-")
{
BigInt r = this;
r.negate();
return r;
}
else static if (op=="~")
{
return -(this+1);
}
else static if (op=="+")
return this;
}
// non-const unary operations
/// ditto
BigInt opUnary(string op)() pure nothrow @safe if (op=="++" || op=="--")
{
static if (op=="++")
{
data = BigUint.addOrSubInt(data, 1UL, sign, sign);
return this;
}
else static if (op=="--")
{
data = BigUint.addOrSubInt(data, 1UL, !sign, sign);
return this;
}
}
///
@safe unittest
{
auto x = BigInt("1234");
assert(-x == BigInt("-1234"));
++x;
assert(x == BigInt("1235"));
}
/**
Implements `BigInt` equality test with other `BigInt`'s and built-in
numeric types.
*/
bool opEquals()(auto ref const BigInt y) const pure @nogc @safe
{
return sign == y.sign && y.data == data;
}
/// ditto
bool opEquals(T)(const T y) const pure nothrow @nogc @safe if (isIntegral!T)
{
if (sign != (y<0))
return 0;
return data.opEquals(cast(ulong) absUnsign(y));
}
/// ditto
bool opEquals(T)(const T y) const pure nothrow @nogc if (isFloatingPoint!T)
{
return 0 == opCmp(y);
}
///
@safe unittest
{
// Note that when comparing a BigInt to a float or double the
// full precision of the BigInt is always considered, unlike
// when comparing an int to a float or a long to a double.
assert(BigInt(123456789) != cast(float) 123456789);
}
@safe unittest
{
auto x = BigInt("12345");
auto y = BigInt("12340");
int z = 12345;
int w = 54321;
assert(x == x);
assert(x != y);
assert(x == y + 5);
assert(x == z);
assert(x != w);
}
@safe unittest
{
import std.math.operations : nextDown, nextUp;
const x = BigInt("0x1abc_de80_0000_0000_0000_0000_0000_0000");
BigInt x1 = x + 1;
BigInt x2 = x - 1;
const d = 0x1.abcde8p124;
assert(x == d);
assert(x1 != d);
assert(x2 != d);
assert(x != nextUp(d));
assert(x != nextDown(d));
assert(x != double.nan);
const dL = 0x1.abcde8p124L;
assert(x == dL);
assert(x1 != dL);
assert(x2 != dL);
assert(x != nextUp(dL));
assert(x != nextDown(dL));
assert(x != real.nan);
assert(BigInt(0) == 0.0f);
assert(BigInt(0) == 0.0);
assert(BigInt(0) == 0.0L);
assert(BigInt(0) == -0.0f);
assert(BigInt(0) == -0.0);
assert(BigInt(0) == -0.0L);
assert(BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999") != float.infinity);
}
/**
Implements casting to `bool`.
*/
T opCast(T:bool)() pure nothrow @nogc @safe const
{
return !isZero();
}
///
@safe unittest
{
// Non-zero values are regarded as true
auto x = BigInt("1");
auto y = BigInt("10");
assert(x);
assert(y);
// Zero value is regarded as false
auto z = BigInt("0");
assert(!z);
}
/**
Implements casting to integer types.
Throws: $(REF ConvOverflowException, std,conv) if the number exceeds
the target type's range.
*/
T opCast(T:ulong)() pure @safe const
{
if (isUnsigned!T && sign)
{ /* throw */ }
else
if (data.ulongLength == 1)
{
ulong l = data.peekUlong(0);
if (isUnsigned!T || !sign)
{
if (l <= T.max)
return cast(T) l;
}
else
{
if (l <= ulong(T.max)+1)
return cast(T)-long(l); // -long.min == long.min
}
}
import std.conv : ConvOverflowException;
import std.string : format;
throw new ConvOverflowException(
"BigInt(%s) cannot be represented as a %s"
.format(this.toDecimalString, T.stringof));
}
///
@safe unittest
{
import std.conv : to, ConvOverflowException;
import std.exception : assertThrown;
assert(BigInt("0").to!int == 0);
assert(BigInt("0").to!ubyte == 0);
assert(BigInt("255").to!ubyte == 255);
assertThrown!ConvOverflowException(BigInt("256").to!ubyte);
assertThrown!ConvOverflowException(BigInt("-1").to!ubyte);
}
@safe unittest
{
import std.conv : to, ConvOverflowException;
import std.exception : assertThrown;
assert(BigInt("-1").to!byte == -1);
assert(BigInt("-128").to!byte == -128);
assert(BigInt("127").to!byte == 127);
assertThrown!ConvOverflowException(BigInt("-129").to!byte);
assertThrown!ConvOverflowException(BigInt("128").to!byte);
assert(BigInt("0").to!uint == 0);
assert(BigInt("4294967295").to!uint == uint.max);
assertThrown!ConvOverflowException(BigInt("4294967296").to!uint);
assertThrown!ConvOverflowException(BigInt("-1").to!uint);
assert(BigInt("-1").to!int == -1);
assert(BigInt("-2147483648").to!int == int.min);
assert(BigInt("2147483647").to!int == int.max);
assertThrown!ConvOverflowException(BigInt("-2147483649").to!int);
assertThrown!ConvOverflowException(BigInt("2147483648").to!int);
assert(BigInt("0").to!ulong == 0);
assert(BigInt("18446744073709551615").to!ulong == ulong.max);
assertThrown!ConvOverflowException(BigInt("18446744073709551616").to!ulong);
assertThrown!ConvOverflowException(BigInt("-1").to!ulong);
assert(BigInt("-1").to!long == -1);
assert(BigInt("-9223372036854775808").to!long == long.min);
assert(BigInt("9223372036854775807").to!long == long.max);
assertThrown!ConvOverflowException(BigInt("-9223372036854775809").to!long);
assertThrown!ConvOverflowException(BigInt("9223372036854775808").to!long);
}
/**
Implements casting to floating point types.
*/
T opCast(T)() @safe nothrow @nogc const if (isFloatingPoint!T)
{
return toFloat!(T, "nearest");
}
///
@system unittest
{
assert(cast(float) BigInt("35540592535949172786332045140593475584")
== 35540592535949172786332045140593475584.0f);
assert(cast(double) BigInt("35540601499647381470685035515422441472")
== 35540601499647381470685035515422441472.0);
assert(cast(real) BigInt("35540601499647381470685035515422441472")
== 35540601499647381470685035515422441472.0L);
assert(cast(float) BigInt("-0x1345_6780_0000_0000_0000_0000_0000") == -0x1.3456_78p+108f );
assert(cast(double) BigInt("-0x1345_678a_bcde_f000_0000_0000_0000") == -0x1.3456_78ab_cdefp+108 );
assert(cast(real) BigInt("-0x1345_678a_bcde_f000_0000_0000_0000") == -0x1.3456_78ab_cdefp+108L);
}
/// Rounding when casting to floating point
@system unittest
{
// BigInts whose values cannot be exactly represented as float/double/real
// are rounded when cast to float/double/real. When cast to float or
// double or 64-bit real the rounding is strictly defined. When cast
// to extended-precision real the rounding rules vary by environment.
// BigInts that fall somewhere between two non-infinite floats/doubles
// are rounded to the closer value when cast to float/double.
assert(cast(float) BigInt(0x1aaa_aae7) == 0x1.aaa_aaep+28f);
assert(cast(float) BigInt(0x1aaa_aaff) == 0x1.aaa_ab0p+28f);
assert(cast(float) BigInt(-0x1aaa_aae7) == -0x1.aaaaaep+28f);
assert(cast(float) BigInt(-0x1aaa_aaff) == -0x1.aaaab0p+28f);
assert(cast(double) BigInt(0x1aaa_aaaa_aaaa_aa77) == 0x1.aaa_aaaa_aaaa_aa00p+60);
assert(cast(double) BigInt(0x1aaa_aaaa_aaaa_aaff) == 0x1.aaa_aaaa_aaaa_ab00p+60);
assert(cast(double) BigInt(-0x1aaa_aaaa_aaaa_aa77) == -0x1.aaa_aaaa_aaaa_aa00p+60);
assert(cast(double) BigInt(-0x1aaa_aaaa_aaaa_aaff) == -0x1.aaa_aaaa_aaaa_ab00p+60);
// BigInts that fall exactly between two non-infinite floats/doubles
// are rounded away from zero when cast to float/double. (Note that
// in most environments this is NOT the same rounding rule rule used
// when casting int/long to float/double.)
assert(cast(float) BigInt(0x1aaa_aaf0) == 0x1.aaa_ab0p+28f);
assert(cast(float) BigInt(-0x1aaa_aaf0) == -0x1.aaaab0p+28f);
assert(cast(double) BigInt(0x1aaa_aaaa_aaaa_aa80) == 0x1.aaa_aaaa_aaaa_ab00p+60);
assert(cast(double) BigInt(-0x1aaa_aaaa_aaaa_aa80) == -0x1.aaa_aaaa_aaaa_ab00p+60);
// BigInts that are bounded on one side by the largest positive or
// most negative finite float/double and on the other side by infinity
// or -infinity are rounded as if in place of infinity was the value
// `2^^(T.max_exp)` when cast to float/double.
assert(cast(float) BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999") == float.infinity);
assert(cast(float) BigInt("-999_999_999_999_999_999_999_999_999_999_999_999_999") == -float.infinity);
assert(cast(double) BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999") < double.infinity);
assert(cast(real) BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999") < real.infinity);
}
@safe unittest
{
// Test exponent overflow is correct.
assert(cast(float) BigInt(0x1fffffff) == 0x1.000000p+29f);
assert(cast(double) BigInt(0x1fff_ffff_ffff_fff0) == 0x1.000000p+61);
}
private T toFloat(T, string roundingMode)() @safe nothrow @nogc const
if (__traits(isFloating, T) && (roundingMode == "nearest" || roundingMode == "truncate"))
{
import core.bitop : bsr;
enum performRounding = (roundingMode == "nearest");
enum performTruncation = (roundingMode == "truncate");
static assert(performRounding || performTruncation, "unrecognized rounding mode");
enum int totalNeededBits = T.mant_dig + int(performRounding);
static if (totalNeededBits <= 64)
{
// We need to examine the top two 64-bit words, not just the top one,
// since the top word could have just a single significant bit.
const ulongLength = data.ulongLength;
const ulong w1 = data.peekUlong(ulongLength - 1);
if (w1 == 0)
return T(0); // Special: exponent should be all zero bits, plus bsr(w1) is undefined.
const ulong w2 = ulongLength < 2 ? 0 : data.peekUlong(ulongLength - 2);
const uint w1BitCount = bsr(w1) + 1;
ulong sansExponent = (w1 << (64 - w1BitCount)) | (w2 >>> (w1BitCount));
size_t exponent = (ulongLength - 1) * 64 + w1BitCount + 1;
static if (performRounding)
{
sansExponent += 1UL << (64 - totalNeededBits);
if (0 <= cast(long) sansExponent) // Use high bit to detect overflow.
{
// Do not bother filling in the high bit of sansExponent
// with 1. It will be discarded by float and double and 80
// bit real cannot be on this path with rounding enabled.
exponent += 1;
}
}
static if (T.mant_dig == float.mant_dig)
{
if (exponent >= T.max_exp)
return isNegative ? -T.infinity : T.infinity;
uint resultBits = (uint(isNegative) << 31) | // sign bit
((0xFF & (exponent - float.min_exp)) << 23) | // exponent
cast(uint) ((sansExponent << 1) >>> (64 - 23)); // mantissa.
// TODO: remove @trusted lambda after DIP 1000 is enabled by default.
return (() @trusted => *cast(float*) &resultBits)();
}
else static if (T.mant_dig == double.mant_dig)
{
if (exponent >= T.max_exp)
return isNegative ? -T.infinity : T.infinity;
ulong resultBits = (ulong(isNegative) << 63) | // sign bit
((0x7FFUL & (exponent - double.min_exp)) << 52) | // exponent
((sansExponent << 1) >>> (64 - 52)); // mantissa.
// TODO: remove @trusted lambda after DIP 1000 is enabled by default.
return (() @trusted => *cast(double*) &resultBits)();
}
else
{
import core.math : ldexp;
return ldexp(isNegative ? -cast(real) sansExponent : cast(real) sansExponent,
cast(int) exponent - 65);