-
Notifications
You must be signed in to change notification settings - Fork 6
/
z.d
3965 lines (3482 loc) · 100 KB
/
z.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
/// Multiple precision integers (Z).
module gmp.z;
debug import std.stdio : writeln;
import std.exception : enforce;
import core.lifetime : move;
import std.traits : Unsigned, Unqual, isIntegral, isUnsigned; // used by expression templates
import gmp.traits;
/// Call version(gmp_test) unittests taking long to execute.
// version = version(gmp_test) unittestLong;
/// Is `true` if type `T` can be evaluated to a `MpZ` value.
enum isMpZExpr(T) = (is(Unqual!(typeof(T.eval())) == MpZ) ||
is(Unqual!(typeof(T.eval())) == CopyableMpZ)); // which returns an `MpZ`
/// Is `true` if type `T` is lazy (not yet evaluated) `MpZ`-expression.
enum isLazyMpZExpr(T) = (!is(Unqual!T == MpZ) && // exclude direct value
isMpZExpr!T);
/** WordEndianess of serialization in `MpZ.serialize` and
unserialization-construction from integer array.
*/
enum WordEndianess
{
host,
bigEndian,
littleEndian,
}
/** Word-order of serialization in `MpZ.serialize` and
unserialization-construction from integer array.
*/
enum WordOrder
{
mostSignificantWordFirst,
leastSignificantWordFirst,
}
/** Rounding used in division variants `cdiv`, `fdiv` and `tdiv`.
TODO: Make use of.
*/
enum Rounding
{
ceiling, ///< Used by functions named `..._cdiv_...`
floor, ///< Used by functions named `..._fdiv_...`
truncate ///< Used by functions named `..._tdiv_...`
}
// TODO: use these imports instead of the ones below
// import deimos.gmp.gmp;
// import deimos.gmp.integer;
/** Arbitrary (multi) precision signed integer (Z).
Wrapper for GNU MP (GMP)'s type `mpz_t` and functions `__gmpz_.*`.
If `cow` is `false` copying (via assignment and parameter passing by value)
is only possible explicitly via `.dup` (Rust-style) otherwise copying is
automatic and does copy-on-write (CoW) of the internal data via reference
counting (ARC) (Swift-style).
*/
private struct _Z(bool cow)
{
/// Put `string` to sink in base `base`.
void toString(scope void delegate(scope const(char)[]) @safe sink,
in uint base = defaultBase,
in bool upperCaseDigits = false) const @trusted
in(-2 <= base && base <= -36 ||
+2 <= base && base <= +62)
{
import core.memory : pureMalloc;
if (isZero) { return sink(`0`); }
if (isOne) { return sink(`1`); }
const size = sizeInBase(base); // NOTE: one too much for some values
scope char[] str = (cast(char*)pureMalloc(size + 1))[0 .. size + 1]; // one extra for minus sign
scope(exit) qualifiedFree(str.ptr);
sink(fillChars(str, base, upperCaseDigits));
}
pure:
/** Needed below because `mpz_init_set_str` is currently the only way to
* construct from an array of characters.
*/
private enum smallBufSize = 1024;
/** Construct from `value` in base `base`.
If `base` is 0 it's guessed from contents of `value`.
*/
this(scope const(char)[] value, uint base = 0) @trusted // TODO: Use Optional/Nullable when value is nan, or inf
in(base == 0 ||
(+2 <= base && base <= +62))
{
if (value.length >= 2 &&
value[0] == '0' &&
((base == 16 &&
(value[1] == 'x' ||
value[1] == 'X')) ||
(base == 2 &&
(value[1] == 'b' ||
value[1] == 'B')) ||
(base == 8 &&
(value[1] == 'o' ||
value[1] == 'O'))))
{
value = value[2 .. $]; // __gmpz_init_set_str doesn’t allow `"0x"` prefix if `base` given
}
char[smallBufSize] buf;
char* stringz;
import std.algorithm.searching : canFind;
if (value.length + 1 <= smallBufSize &&
value[0] != '-' && // TODO: support minus sign
!value.canFind('_')) // TODO: support underscore
{
buf[0 .. value.length] = value;
buf[value.length] = '\0'; // null terminator
stringz = buf.ptr;
}
else
{
stringz = _allocStringzCopyOf(value); // TODO: append inline trailing zero if possible otherwise make this stack allocated
}
scope(exit)
{
if (stringz != buf.ptr)
qualifiedFree(stringz);
}
immutable int status = __gmpz_init_set_str(_ptr, stringz, base);
enforce(status == 0, "Parameter `value` does not contain an integer");
}
static typeof(this) fromBinaryString(scope const(char)[] value) pure @safe
{
return typeof(return)(value, 2);
}
static typeof(this) fromHexString(scope const(char)[] value) pure @safe
{
return typeof(return)(value, 16);
}
nothrow:
/// Convert to `string` in base `base`.
string toString(in uint base = defaultBase,
in bool upperCaseDigits = false) scope const @trusted
in(-2 <= base && base <= -36 ||
+2 <= base && base <= +62)
{
if (isZero) { return `0`; }
if (isOne) { return `1`; }
const size = sizeInBase(base); // NOTE: one too much for some values
char[] str = new char[](size + 1); // one extra for minus sign
__gmpz_get_str(str.ptr, base, _ptr); // fill it
return fillChars(str, base, upperCaseDigits);
}
/** Convert in base `base` into `chars` of length `length`.
Returns: char[] which must be freed manually with `pureFree` thereby
making this `@system`.
*/
char[] toChars(in uint base = defaultBase,
in bool upperCaseDigits = false) scope const @system @nogc
in(-2 <= base && base <= -36 ||
+2 <= base && base <= +62)
{
import core.memory : pureMalloc;
if (isZero ||
isOne)
{
char[] chars = (cast(char*)pureMalloc(1))[0 .. 1];
if (isZero)
chars[0] = '0';
else if (isOne)
chars[0] = '1';
return chars;
}
const size = sizeInBase(base); // NOTE: one too much for some values
char[] chars = (cast(char*)pureMalloc(size + 1))[0 .. size + 1]; // one extra for minus sign
return fillChars(chars, base, upperCaseDigits);
}
private char[] fillChars(char[] chars,
in uint base = defaultBase,
in bool upperCaseDigits = false) const @system @nogc
in(-2 <= base && base <= -36 ||
+2 <= base && base <= +62)
{
__gmpz_get_str(chars.ptr, base, _ptr); // fill it
import std.ascii : isAlphaNum, isLower, toUpper;
while (chars.length &&
!chars[$ - 1].isAlphaNum)
chars = chars[0 .. $ - 1]; // skip trailing garbage
if (upperCaseDigits)
foreach (ref e; chars)
if (e.isLower)
e = e.toUpper;
return chars;
}
void toString(Writer)(ref Writer writer, // `mir.appender` compliant
in uint base = defaultBase,
in bool upperCaseDigits = false) const @nogc @trusted
if (is(typeof(writer.put((const(char)[]).init))))
{
import core.memory : pureFree;
if (isZero) { return writer.put("0"); }
if (isOne) { return writer.put("1"); }
auto chars = toChars(base, upperCaseDigits);
scope(exit) pureFree(chars.ptr);
writer.put(chars);
}
/// Get the unique hash of the `_Z` value suitable for use in a hash table.
size_t toHash() const @trusted
{
import core.internal.hash : hashOf;
typeof(return) hash = limbCount;
foreach (immutable i; 0 .. limbCount)
hash ^= _limbs[i].hashOf;
return hash;
}
/** Serialize `this` into a new GC-allocated slice of words, each word of
type `Word`.
It's format defined by:
- `order`: the most significant word `first` or `last` for least significant first
- `endian` can be `bigEndian`, `littleEndian` or `host` default
- the most significant `nails` bits of each word are unused and set to zero, this can be 0 to produce full words
Returns: a new GC-allocated slice containing the words produced.
*/
Word[] serialize(Word)(WordOrder order, WordEndianess endian, size_t nails) const @trusted
if (isUnsigned!Word)
{
const numb = 8 * Word.sizeof - nails;
size_t count = (__gmpz_sizeinbase(_ptr, 2) + numb-1) / numb;
return serialize(new Word[count], order, Word.sizeof, endian, nails);
}
@nogc:
/** No default construction for now, because `mpz_init` initialize
`__mpz_struct`-fields to non-zero values.
TODO: Allow default construction by delaying call to initialize().
*/
// @disable this();
/// Construct empty (undefined) from explicit `null`.
this(typeof(null)) @trusted
{
pragma(inline, true);
initialize(); // TODO: is there a faster way?
assert(this == _Z.init); // if this is same as default
}
/// Construct from expression `expr`.
this(Expr)(Expr expr)
if (isLazyMpZExpr!Expr)
{
version(LDC) pragma(inline, true);
// TODO: ok to just assume zero-initialized contents at `_z` before...
this = expr; // ...calling this.opAssign ?x
}
/** Construct from `value`. */
this(T)(T value) @trusted
if (isArithmetic!T)
{
// TODO: add support for static initialization
// if (!__ctfe)
// {
pragma(inline, true);
static if (isUnsigned!T) __gmpz_init_set_ui(_ptr, value);
else static if (isFloating!T) __gmpz_init_set_d(_ptr, value);
else __gmpz_init_set_si(_ptr, value); // isSigned integral
// }
// else
// {
// if (value == 0)
// {
// reinterpret_to_size_if_sizeof_and_zero();
// }
// else
// {
// assert(0, "Cannot set non-zero value at ctfe");
// }
// }
}
/** Constucts number from serialized binary array.
Arguments:
- `rop` : array of unsinged values
- `order`: the most significant word `first` or `last` for least significant first
- `size` in bytes of each word
- `endian` can be `bigEndian`, `littleEndian` or `host` default
- the most significant `nails` bits of each word are unused and set to zero, this can be 0 to produce full words
*/
this(T)(const T[] rop, WordOrder order, size_t size, WordEndianess endian, size_t nails)
if (isUnsigned!T)
{
int realOrder;
final switch(order)
{
case WordOrder.mostSignificantWordFirst: realOrder = 1; break;
case WordOrder.leastSignificantWordFirst: realOrder = -1; break;
}
int realEndian;
final switch(endian)
{
case WordEndianess.littleEndian: realEndian = -1; break;
case WordEndianess.bigEndian: realEndian = 1; break;
case WordEndianess.host: realEndian = 0; break;
}
__gmpz_init(_ptr);
__gmpz_import(_ptr, rop.length, realOrder, size, realEndian, nails, rop.ptr);
}
/// Mersenne prime, M(p) = 2 ^^ p - 1
static _Z mersennePrime(Integral)(Integral p)
if (isIntegral!Integral)
{
version(LDC) pragma(inline, true);
return typeof(this).pow(2UL, p) - 1;
}
// /// Construct copy of `value`.
// this(ref const _Z value) @trusted
// {
// __gmpz_init_set(_ptr, value._ptr);
// }
// /// Construct copy of `value`.
// this(_Z value) @trusted
// {
// import core.lifetime : moveEmplace;
// moveEmplace(value, this); // fast
// }
static if (cow)
{
void selfdupIfAliased() scope pure nothrow @nogc @safe {
pragma(inline, true);
if (_refCountCopies >= 1)
this = this.dup();
}
this(this) scope pure nothrow @nogc @safe
{
pragma(inline, true);
_refCountCopies += 1;
}
}
else
{
@disable this(this);
}
/// Swap content of `this` with `rhs`.
void swap()(ref _Z rhs) scope pure nothrow @nogc @safe
{
pragma(inline, true);
import std.algorithm.mutation : swap;
swap(this, rhs); // faster than __gmpz_swap(_ptr, rhs._ptr);
}
/// (Duplicate) Copy `this`.
_Z dup() scope const pure nothrow @trusted
{
version(LDC) pragma(inline, true);
typeof(return) y = void;
__gmpz_init_set(y._ptr, _ptr);
static if (cow) { y._refCountCopies = 0; }
return y;
}
/// Assign from `rhs`.
ref _Z opAssign()(auto ref scope const _Z rhs) scope return @trusted
{
version(LDC) pragma(inline, true);
static if (cow) { selfdupIfAliased(); }
__gmpz_set(_ptr, rhs._ptr);
return this;
}
/// ditto
ref _Z opAssign(Expr)(auto ref Expr rhs) scope return @trusted
if (isLazyMpZExpr!Expr)
{
version(LDC) pragma(inline, true);
rhs.evalTo(this);
return this;
}
/// ditto
ref _Z opAssign(T)(T rhs) scope return @trusted
if (isArithmetic!T)
{
version(LDC) pragma(inline, true);
assertInitialized();
static if (cow) { selfdupIfAliased(); }
static if (isUnsigned!T) __gmpz_set_ui(_ptr, rhs);
else static if (isFloating!T) __gmpz_set_d(_ptr, rhs);
else static if (isSigned!T) __gmpz_set_si(_ptr, rhs);
else static assert(0);
return this;
}
/** Assign `this` from `string` `rhs` interpreted in base `base`.
If `base` is 0 it's guessed from contents of `value`.
*/
ref _Z fromString(scope const(char)[] rhs, uint base = 0) scope return @trusted
{
assert(base == 0 || (base >= 2 && base <= 62));
static if (cow) { selfdupIfAliased(); }
char* stringz = _allocStringzCopyOf(rhs);
immutable int status = __gmpz_set_str(_ptr, stringz, base);
qualifiedFree(stringz);
assert(status == 0, "Parameter `rhs` does not contain an integer");
return this;
}
/// Destruct `this`.
~this() scope @nogc @trusted
{
version(LDC) pragma(inline, true);
if (_z._mp_d)
{
static if (cow)
{
if (_refCountCopies >= 1)
{
_z._mp_d = null; // prevent GC from scanning this memory
return;
}
}
__gmpz_clear(_ptr);
_z._mp_d = null; // prevent GC from scanning this memory
}
}
/// Returns: `true` iff `this` equals `rhs`.
bool opEquals()(auto ref scope const _Z rhs) const @trusted
{
version(LDC) pragma(inline, true);
if (_ptr == rhs._ptr) // fast equality
return true; // fast bailout
return __gmpz_cmp(_ptr, rhs._ptr) == 0;
}
/// ditto
bool opEquals(Rhs)(Rhs rhs) const @trusted
if (isArithmetic!Rhs)
{
version(LDC) pragma(inline, true);
if (rhs == 0)
return isZero; // optimization
if (rhs == 1)
return isOne; // optimization
static if (isUnsigned!Rhs) return __gmpz_cmp_ui(_ptr, cast(ulong)rhs) == 0;
else static if (isFloating!Rhs) return __gmpz_cmp_d(_ptr, cast(double)rhs) == 0; // TODO: correct to do this cast here?
else return __gmpz_cmp_si(_ptr, cast(long)rhs) == 0; // isSigned integral
}
/// Compare `this` to `rhs`.
int opCmp()(auto ref scope const _Z rhs) const @trusted
{
version(LDC) pragma(inline, true);
if (rhs == 0)
return sgn(); // optimization
return __gmpz_cmp(_ptr, rhs._ptr);
}
/// ditto
int opCmp(T)(T rhs) const @trusted
if (isArithmetic!T)
{
pragma(inline, true);
if (rhs == 0)
return sgn(); // optimization
static if (isUnsigned!T) return __gmpz_cmp_ui(_ptr, rhs);
else static if (isFloating!T) return __gmpz_cmp_d(_ptr, rhs);
else return __gmpz_cmp_si(_ptr, rhs); // isSigned integral
}
/// Cast to `bool`.
bool opCast(T : bool)() scope const
{
pragma(inline, true);
return !isZero;
}
/// Cast to arithmetic type `T`.
T opCast(T)() scope const @trusted
if (isArithmetic!T)
{
pragma(inline, true);
static if (isUnsigned!T) return cast(T)__gmpz_get_ui(_ptr);
else static if (isFloating!T) return cast(T)__gmpz_get_d(_ptr);
else return cast(T)__gmpz_get_si(_ptr); // isSigned integral
}
/** Get the value of this as a `long`, or +/- `long.max` if outside the
representable range. */
long toLong() scope const @trusted
{
version(LDC) pragma(inline, true);
// TODO: can probably be optimized
if (this <= long.min)
return long.min;
else if (this >= long.max)
return long.max;
else
return cast(long)__gmpz_get_si(_ptr);
}
/** Get the value of this as a `int`, or +/- `int.max` if outside the
representable range.
*/
int toInt() const @trusted
{
version(LDC) pragma(inline, true);
// TODO: can probably be optimized
if (this <= int.min)
return int.min;
else if (this >= int.max)
return int.max;
else
return cast(int)__gmpz_get_si(_ptr);
}
/** Get `this` `s` `rhs`. */
_Z opBinary(string s)(auto ref scope const _Z rhs) const @trusted // direct value
if ((s == "+" || s == "-" ||
s == "*" || s == "/" || s == "%" ||
s == "&" || s == "|" || s == "^" ||
s == "<<" || s == ">>"))
{
version(LDC) pragma(inline, true);
static if (!__traits(isRef, rhs)) // r-value `rhs`
{
_Z* mut_rhs = (cast(_Z*)(&rhs)); // @trusted because `_Z` has no aliased indirections
static if (s == "+") __gmpz_add(mut_rhs._ptr, _ptr, rhs._ptr);
else static if (s == "-") __gmpz_sub(mut_rhs._ptr, _ptr, rhs._ptr);
else static if (s == "*") __gmpz_mul(mut_rhs._ptr, _ptr, rhs._ptr);
else static if (s == "/")
{
assert(rhs != 0, "Divison by zero");
__gmpz_tdiv_q(mut_rhs._ptr, _ptr, rhs._ptr);
}
else static if (s == "%")
{
assert(rhs != 0, "Divison by zero");
const neg = rhs.isNegative;
__gmpz_mod(mut_rhs._ptr, _ptr, rhs._ptr);
if (neg)
mut_rhs.negate();
}
else static if (s == "&") __gmpz_and(mut_rhs._ptr, _ptr, rhs._ptr);
else static if (s == "|") __gmpz_ior(mut_rhs._ptr, _ptr, rhs._ptr);
else static if (s == "^") __gmpz_xor(mut_rhs._ptr, _ptr, rhs._ptr);
else static if (s == "<<")
{
if (rhs.isPositive())
__gmpz_mul_2exp(mut_rhs._ptr, _ptr, cast(mp_bitcnt_t)rhs);
else
__gmpz_tdiv_q_2exp(mut_rhs._ptr, _ptr, cast(mp_bitcnt_t)-rhs); // `z << -1` becomes `z >> 1`
}
else static if (s == ">>")
{
if (rhs.isPositive())
__gmpz_tdiv_q_2exp(mut_rhs._ptr, _ptr, cast(mp_bitcnt_t)rhs);
else
__gmpz_mul_2exp(mut_rhs._ptr, _ptr, cast(mp_bitcnt_t)-rhs); // `z >> -1` becomes `z << 1`
}
else static assert(0);
return move(*mut_rhs); // TODO: shouldn't have to call `move` here
}
else
{
typeof(return) y = null;
static if (s == "+") __gmpz_add(y._ptr, _ptr, rhs._ptr);
else static if (s == "-") __gmpz_sub(y._ptr, _ptr, rhs._ptr);
else static if (s == "*") __gmpz_mul(y._ptr, _ptr, rhs._ptr);
else static if (s == "/")
{
assert(rhs != 0, "Divison by zero");
__gmpz_tdiv_q(y._ptr, _ptr, rhs._ptr);
}
else static if (s == "%")
{
assert(rhs != 0, "Divison by zero");
const neg = rhs.isNegative;
__gmpz_mod(y._ptr, _ptr, rhs._ptr);
if (neg)
y.negate();
}
else static if (s == "&") __gmpz_and(y._ptr, _ptr, rhs._ptr);
else static if (s == "|") __gmpz_ior(y._ptr, _ptr, rhs._ptr);
else static if (s == "^") __gmpz_xor(y._ptr, _ptr, rhs._ptr);
else static if (s == "<<")
{
if (rhs.isPositive())
__gmpz_mul_2exp(y._ptr, _ptr, cast(mp_bitcnt_t)rhs);
else
__gmpz_tdiv_q_2exp(y._ptr, _ptr, cast(mp_bitcnt_t)-rhs); // `z << -1` becomes `z >> 1`
}
else static if (s == ">>")
{
if (rhs.isPositive())
__gmpz_tdiv_q_2exp(y._ptr, _ptr, cast(mp_bitcnt_t)rhs);
else
__gmpz_mul_2exp(y._ptr, _ptr, cast(mp_bitcnt_t)-rhs); // `z >> -1` becomes `z << 1`
}
else static assert(0);
return y;
}
}
/// ditto
_Z opBinary(string s, Rhs)(auto ref const Rhs rhs) const
if (isLazyMpZExpr!Rhs && // lazy value
(s == "+" || s == "-" || s == "*" || s == "/" || s == "%"))
{
pragma(inline, true);
static assert(false, "TODO");
}
/// ditto
_Z opBinary(string s, Rhs)(Rhs rhs) const @trusted
if ((s == "+" || s == "-" || s == "*" || s == "/" /* || s == "%"*/ || s == "^^" || s == "<<" || s == ">>") &&
isUnsigned!Rhs)
{
version(LDC) pragma(inline, true);
typeof(return) y = null;
static if (s == "+") __gmpz_add_ui(y._ptr, _ptr, rhs);
else static if (s == "-") __gmpz_sub_ui(y._ptr, _ptr, rhs);
else static if (s == "*") __gmpz_mul_ui(y._ptr, _ptr, rhs);
else static if (s == "/")
{
assert(rhs != 0, "Divison by zero");
__gmpz_tdiv_q_ui(y._ptr, _ptr, rhs);
}
// NOTE: handled by call to `mpz_tdiv_r_ui` below
// else static if (s == "%")
// {
// assert(rhs != 0, "Divison by zero");
// __gmpz_mod_ui(y._ptr, _ptr, rhs);
// }
else static if (s == "^^") __gmpz_pow_ui(y._ptr, _ptr, rhs);
else static if (s == "<<") __gmpz_mul_2exp(y._ptr, _ptr, rhs);
else static if (s == ">>") __gmpz_tdiv_q_2exp(y._ptr, _ptr, rhs);
else static assert(0);
return y;
}
/// ditto
_Z opBinary(string s, Rhs)(Rhs rhs) const @trusted
if ((s == "+" || s == "-" || s == "*" || s == "/" || s == "^^" || s == "<<" || s == ">>") &&
isSigned!Rhs)
{
version(LDC) pragma(inline, true);
typeof(return) y = null;
static if (s == "+")
{
if (rhs < 0) // TODO: handle `rhs == rhs.min`
{
immutable ulong pos_rhs = -rhs; // make it positive
__gmpz_sub_ui(y._ptr, _ptr, pos_rhs);
}
else
__gmpz_add_ui(y._ptr, _ptr, rhs);
}
else static if (s == "-")
{
if (rhs < 0) // TODO: handle `rhs == rhs.min`
__gmpz_add_ui(y._ptr, _ptr, -rhs); // x - (-y) == x + y
else
__gmpz_sub_ui(y._ptr, _ptr, rhs); // rhs is positive
}
else static if (s == "*")
{
__gmpz_mul_si(y._ptr, _ptr, rhs);
}
else static if (s == "/")
{
assert(rhs != 0, "Divison by zero");
if (rhs < 0) // TODO: handle `rhs == rhs.min`
{
immutable ulong pos_rhs = -rhs; // make it positive
__gmpz_tdiv_q_ui(y._ptr, _ptr, pos_rhs);
y.negate(); // negate result
}
else
__gmpz_tdiv_q_ui(y._ptr, _ptr, rhs);
}
else static if (s == "^^")
{
assert(rhs >= 0, "TODO: Negative power exponent needs MpQ return");
__gmpz_pow_ui(y._ptr, _ptr, rhs);
}
else static if (s == "<<")
{
if (rhs >= 0)
__gmpz_mul_2exp(y._ptr, _ptr, rhs);
else
__gmpz_tdiv_q_2exp(y._ptr, _ptr, -rhs); // `z << -1` becomes `z >> 1`
}
else static if (s == ">>")
{
if (rhs >= 0)
__gmpz_tdiv_q_2exp(y._ptr, _ptr, rhs);
else
__gmpz_mul_2exp(y._ptr, _ptr, -rhs); // `z >> -1` becomes `z << 1`
}
else static assert(0);
return y;
}
/// Remainer propagates modulus type.
Unqual!Rhs opBinary(string s, Rhs)(Rhs rhs) const @trusted
if ((s == "%") &&
isIntegral!Rhs)
{
version(LDC) pragma(inline, true);
assert(rhs != 0, "Divison by zero");
_Z y = null;
static if (isSigned!Rhs)
{
if (rhs < 0) // TODO: handle `rhs == rhs.min`
{
immutable ulong pos_rhs = -cast(int)rhs; // make it positive
return cast(typeof(return))-__gmpz_tdiv_r_ui(y._ptr, _ptr, pos_rhs);
}
else
return cast(typeof(return))__gmpz_tdiv_r_ui(y._ptr, _ptr, rhs);
}
else static if (isUnsigned!Rhs)
return cast(typeof(return))__gmpz_tdiv_r_ui(y._ptr, _ptr, rhs);
else
static assert(0);
}
/// Get an unsigned type `lhs` divided by `this`.
_Z opBinaryRight(string s, Lhs)(Lhs lhs) const @trusted
if ((s == "+" || s == "-" || s == "*" || s == "%") &&
isUnsigned!Lhs)
{
version(LDC) pragma(inline, true);
typeof(return) y = null;
static if (s == "+")
__gmpz_add_ui(y._ptr, _ptr, lhs); // commutative
else static if (s == "-")
__gmpz_ui_sub(y._ptr, lhs, _ptr);
else static if (s == "*")
__gmpz_mul_ui(y._ptr, _ptr, lhs); // commutative
else static if (s == "%")
{
assert(this != 0, "Divison by zero");
__gmpz_tdiv_r(y._ptr, _Z(lhs)._ptr, _ptr); // convert `lhs` to _Z
}
else
static assert(0);
return y;
}
/// Get a signed type `lhs` divided by `this`.
_Z opBinaryRight(string s, Lhs)(Lhs lhs) const @trusted
if ((s == "+" || s == "-" || s == "*" || s == "%") &&
isSigned!Lhs)
{
version(LDC) pragma(inline, true);
static if (s == "+" ||
s == "*")
{
return opBinary!s(lhs); // commutative reuse
}
else static if (s == "-")
{
typeof(return) y = null;
if (lhs < 0) // TODO: handle `lhs == lhs.min`
{
immutable ulong pos_rhs = -lhs; // make it positive
__gmpz_add_ui(y._ptr, _ptr, pos_rhs);
}
else
__gmpz_sub_ui(y._ptr, _ptr, lhs);
y.negate();
return y;
}
else static if (s == "%")
{
typeof(return) y = null;
assert(this != 0, "Divison by zero");
__gmpz_tdiv_r(y._ptr, _Z(lhs)._ptr, _ptr); // convert `lhs` to _Z
return y;
}
else
static assert(0);
}
/// Dividend propagates quotient type to signed.
Unqual!Lhs opBinaryRight(string s, Lhs)(Lhs lhs) const @trusted
if ((s == "/") &&
isIntegral!Lhs)
{
version(LDC) pragma(inline, true);
_Z y = null; // TODO: avoid if !__traits(isRef, this)
assert(this != 0, "Divison by zero");
__gmpz_tdiv_q(y._ptr, _Z(lhs)._ptr, _ptr);
static if (isSigned!Lhs)
return cast(typeof(return))y;
else static if (isUnsigned!Lhs)
{
import std.traits : Signed;
return cast(Signed!(typeof(return)))y;
}
else
static assert(0);
}
/// Exponentation.
_Z opBinaryRight(string s, Base)(Base base) const
if ((s == "^^") &&
isIntegral!Base)
{
pragma(inline, true);
static assert(false, "Convert `this _Z` exponent to `ulong` and calculate power via static method `pow()`");
// _Z exp = null;
// __gmpz_pow();
// return exp;
}
/// Operate-assign to `this` from `rhs`.
ref _Z opOpAssign(string s)(auto ref scope const _Z rhs) scope return @trusted
if ((s == "+" || s == "-" ||
s == "*" || s == "/" || s == "%" ||
s == "&" || s == "|" || s == "^" ||
s == "<<" || s == ">>"))
{
version(LDC) pragma(inline, true);
static if (s == "+")
__gmpz_add(_ptr, _ptr, rhs._ptr);
else static if (s == "-")
__gmpz_sub(_ptr, _ptr, rhs._ptr);
else static if (s == "*")
{
if (rhs == -1)
negate();
else
__gmpz_mul(_ptr, _ptr, rhs._ptr);
}
else static if (s == "/")
{
assert(rhs != 0, "Divison by zero");
if (rhs == -1)
negate();
else
__gmpz_tdiv_q(_ptr, _ptr, rhs._ptr);
}
else static if (s == "%")
{
assert(rhs != 0, "Divison by zero");
__gmpz_tdiv_r(_ptr, _ptr, rhs._ptr);
}
else static if (s == "&")
__gmpz_and(_ptr, _ptr, rhs._ptr);
else static if (s == "|")
__gmpz_ior(_ptr, _ptr, rhs._ptr);
else static if (s == "^")
__gmpz_xor(_ptr, _ptr, rhs._ptr);
else static if (s == "<<")
{
if (rhs.isPositive())
__gmpz_mul_2exp(_ptr, _ptr, cast(mp_bitcnt_t)rhs);
else
__gmpz_tdiv_q_2exp(_ptr, _ptr, cast(mp_bitcnt_t)rhs); // `z << -1` becomes `z >> 1`
}
else static if (s == ">>")
{
if (rhs.isPositive())
__gmpz_tdiv_q_2exp(_ptr, _ptr, cast(mp_bitcnt_t)rhs);
else
__gmpz_mul_2exp(_ptr, _ptr, cast(mp_bitcnt_t)rhs); // `z >> -1` becomes `z << 1`
}
else
static assert(0);
return this;
}
/// ditto
ref _Z opOpAssign(string s, Rhs)(Rhs rhs) scope return @trusted
if ((s == "+" || s == "-" || s == "*" || s == "/" || s == "%" || s == "^^" || s == "<<" || s == ">>") &&
isUnsigned!Rhs)
{
version(LDC) pragma(inline, true);
static if (s == "+")
__gmpz_add_ui(_ptr, _ptr, rhs);
else static if (s == "-")
__gmpz_sub_ui(_ptr, _ptr, rhs);
else static if (s == "*")
__gmpz_mul_ui(_ptr, _ptr, rhs);
else static if (s == "/")
{
assert(rhs != 0, "Divison by zero");
__gmpz_tdiv_q_ui(_ptr, _ptr, rhs);
}
else static if (s == "%")
{
assert(rhs != 0, "Divison by zero");
__gmpz_tdiv_r_ui(_ptr, _ptr, rhs);
}
else static if (s == "^^")
__gmpz_pow_ui(_ptr, _ptr, rhs);
else static if (s == "<<")
__gmpz_mul_2exp(_ptr, _ptr, rhs);
else static if (s == ">>")
__gmpz_tdiv_q_2exp(_ptr, _ptr, rhs);
else
static assert(0);
return this;
}
/// ditto
ref _Z opOpAssign(string s, Rhs)(Rhs rhs) scope return @trusted
if ((s == "+" || s == "-" || s == "*" || s == "/" || s == "%" || s == "^^" || s == "<<" || s == ">>") &&
isSigned!Rhs)
{
version(LDC) pragma(inline, true);
static if (s == "+")
{
if (rhs < 0) // TODO: handle `rhs == rhs.min`
{
assert(rhs != rhs.min);
immutable ulong pos_rhs = -rhs; // make it positive
__gmpz_sub_ui(_ptr, _ptr, pos_rhs);
}
else
__gmpz_add_ui(_ptr, _ptr, rhs);
}
else static if (s == "-")
{
if (rhs < 0) // TODO: handle `rhs == rhs.min`
{
assert(rhs != rhs.min);
immutable ulong pos_rhs = -rhs; // make it positive
__gmpz_add_ui(_ptr, _ptr, pos_rhs);
}
else
__gmpz_sub_ui(_ptr, _ptr, rhs);
}
else static if (s == "*")
{
if (rhs == -1)
negate(); // optimization
else
__gmpz_mul_si(_ptr, _ptr, rhs);
}
else static if (s == "/")
{
assert(rhs != 0, "Divison by zero");
if (rhs < 0) // TODO: handle `rhs == rhs.min`
{
immutable ulong pos_rhs = -rhs; // make it positive
__gmpz_tdiv_q_ui(_ptr, _ptr, pos_rhs);
negate();
}
else
__gmpz_tdiv_q_ui(_ptr, _ptr, rhs);
}
else static if (s == "%")
{
assert(rhs != 0, "Divison by zero");
__gmpz_tdiv_r_ui(_ptr, _ptr, rhs);
}
else static if (s == "^^")
{
assert(rhs >= 0, "Negative exponent");
__gmpz_pow_ui(_ptr, _ptr, rhs);
}
else static if (s == "<<")
{
if (rhs >= 0)
__gmpz_mul_2exp(_ptr, _ptr, rhs);
else
__gmpz_tdiv_q_2exp(_ptr, _ptr, -rhs); // `z << -1` becomes `z >> 1`
}
else static if (s == ">>")
{