forked from factor/factor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbignum.zig
More file actions
2359 lines (2014 loc) · 79.1 KB
/
Copy pathbignum.zig
File metadata and controls
2359 lines (2014 loc) · 79.1 KB
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
// bignum.zig - Arbitrary precision integers integrated with the Factor VM.
// Contains shared representation/helpers and VM-facing arithmetic/allocation.
const std = @import("std");
const builtin = @import("builtin");
const layouts = @import("layouts.zig");
const objects = @import("objects.zig");
const Cell = layouts.Cell;
const Fixnum = layouts.Fixnum;
// Native 128÷64 division using x86_64 divq instruction.
// On x86_64, hardware divq divides rdx:rax by a 64-bit operand.
pub fn divmod128by64(hi: u64, lo: u64, divisor: u64) struct { q: u64, r: u64 } {
if (comptime builtin.cpu.arch == .x86_64) {
var q: u64 = undefined;
var r: u64 = undefined;
asm ("divq %[divisor]"
: [q] "={rax}" (q),
[r] "={rdx}" (r),
: [lo] "{rax}" (lo),
[hi] "{rdx}" (hi),
[divisor] "r" (divisor),
);
return .{ .q = q, .r = r };
} else {
const combined: u128 = (@as(u128, hi) << 64) | lo;
return .{ .q = @intCast(combined / divisor), .r = @intCast(combined % divisor) };
}
}
// Digit type definitions.
pub const Digit = Cell;
pub const SignedDigit = Fixnum;
pub const TwoDigit = i128;
// Bit width constants.
pub const DIGIT_BITS: u6 = @bitSizeOf(Cell) - 2;
// Radix and masks.
pub const RADIX: Cell = @as(Cell, 1) << DIGIT_BITS;
pub const DIGIT_MASK: Cell = RADIX - 1;
// Half-digit constants for single-digit division specializations.
pub const HALF_DIGIT_BITS: u6 = DIGIT_BITS / 2;
pub const HALF_DIGIT_MASK: Cell = (@as(Cell, 1) << HALF_DIGIT_BITS) - 1;
pub const RADIX_ROOT: Cell = @as(Cell, 1) << HALF_DIGIT_BITS;
pub fn countDigitsUnsigned(value: anytype) Cell {
if (value == 0) return 0;
const T = @TypeOf(value);
const bitlen: Cell = @intCast(@bitSizeOf(T) - @clz(value));
return (bitlen + DIGIT_BITS - 1) / DIGIT_BITS;
}
pub const Comparison = enum {
less,
equal,
greater,
};
// Bignum structure: header + tagged capacity + sign slot + digits.
pub const Bignum = extern struct {
const Self = @This();
header: Cell,
capacity: Cell, // tagged fixnum = digit_count + 1
pub const type_number = layouts.TypeTag.bignum;
pub const element_size = @sizeOf(Cell);
pub fn rawData(self: *const Self) [*]Cell {
const base: [*]u8 = @ptrCast(@constCast(self));
return @ptrCast(@alignCast(base + @sizeOf(Bignum)));
}
pub fn length(self: *const Bignum) Cell {
return layouts.untagFixnumFast(self.capacity) -| 1;
}
pub fn rawCapacity(self: *const Bignum) Cell {
return layouts.untagFixnumFast(self.capacity);
}
pub fn isNegative(self: *const Bignum) bool {
std.debug.assert(self.rawCapacity() > 0);
return self.rawData()[0] != 0;
}
pub fn setNegative(self: *Bignum, negative: bool) void {
self.rawData()[0] = if (negative) 1 else 0;
}
pub fn isZero(self: *const Bignum) bool {
return self.length() == 0;
}
pub fn digits(self: *const Bignum) [*]Cell {
return self.rawData() + 1;
}
pub fn getDigit(self: *const Bignum, index: Cell) Cell {
std.debug.assert(index < self.length());
return self.digits()[index];
}
pub fn setDigit(self: *Bignum, index: Cell, value: Cell) void {
std.debug.assert(index < self.length());
self.digits()[index] = value;
}
pub fn initialize(self: *Bignum, len: Cell, negative: bool) void {
const obj: *layouts.Object = @ptrCast(self);
obj.initialize(.bignum);
self.capacity = layouts.tagFixnum(@intCast(len + 1));
self.setNegative(negative);
}
};
// Static bignum values (for common cases).
pub const BIGNUM_ZERO_DATA = [_]Cell{ 0, 0 };
pub const BIGNUM_ONE_POS_DATA = [_]Cell{ 0, 0, 1 };
pub const BIGNUM_ONE_NEG_DATA = [_]Cell{ 0, 1, 1 };
pub const DivisionResult = struct {
quotient: *Bignum,
remainder: *Bignum,
};
pub fn compareUnsigned(x: *const Bignum, y: *const Bignum) Comparison {
const x_len = x.length();
const y_len = y.length();
if (x_len < y_len) return .less;
if (x_len > y_len) return .greater;
const xd = x.digits();
const yd = y.digits();
var i: Cell = x_len;
while (i > 0) {
i -= 1;
if (xd[i] < yd[i]) return .less;
if (xd[i] > yd[i]) return .greater;
}
return .equal;
}
pub fn equal(x: *const Bignum, y: *const Bignum) bool {
if (x == y) return true;
if (x.isZero()) return y.isZero();
if (y.isZero()) return false;
if (x.isNegative() != y.isNegative()) return false;
return compareUnsigned(x, y) == .equal;
}
pub fn compare(x: *const Bignum, y: *const Bignum) Comparison {
if (x == y) return .equal;
if (x.isZero()) {
if (y.isZero()) return .equal;
return if (y.isNegative()) .greater else .less;
}
if (y.isZero()) {
return if (x.isNegative()) .less else .greater;
}
if (x.isNegative() and !y.isNegative()) return .less;
if (!x.isNegative() and y.isNegative()) return .greater;
const mag_cmp = compareUnsigned(x, y);
if (x.isNegative()) {
return switch (mag_cmp) {
.less => .greater,
.equal => .equal,
.greater => .less,
};
}
return mag_cmp;
}
// Integer length (number of significant bits).
pub fn integerLength(x: *const Bignum) Cell {
if (x.isZero()) return 0;
const len = x.length();
const top_digit = x.getDigit(len - 1);
if (top_digit == 0) return (len - 1) * DIGIT_BITS;
return (len - 1) * DIGIT_BITS + @as(Cell, (@bitSizeOf(Cell) - 1) - @clz(top_digit));
}
// VM integration helpers
const vm_mod = @import("vm.zig");
const FactorVM = vm_mod.FactorVM;
fn cachedBignum(vm: *FactorVM, which: objects.SpecialObject) ?*Bignum {
const tagged = vm.vm_asm.special_objects[@intFromEnum(which)];
if (tagged == layouts.false_object) return null;
return @ptrFromInt(layouts.UNTAG(tagged));
}
fn zeroBignum(vm: *FactorVM) !*Bignum {
if (cachedBignum(vm, .bignum_zero)) |z| return z;
return allocBignumZeroed(vm, 0, false);
}
// Convert bignum to fixnum
// Precondition: caller must verify fitsFixnum(bn) first
pub fn toFixnum(bn: *const Bignum) Fixnum {
if (bn.isZero()) return 0;
const len = bn.length();
if (len == 1) {
const result: Cell = bn.getDigit(0);
return if (bn.isNegative()) @bitCast(0 -% result) else @bitCast(result);
}
if (len == 2) {
const result: Cell = (bn.getDigit(1) << DIGIT_BITS) | bn.getDigit(0);
return if (bn.isNegative()) @bitCast(0 -% result) else @bitCast(result);
}
var result: Cell = 0;
// Accumulate from high to low order digits
var i: Cell = len;
while (i > 0) {
i -= 1;
result = (result << DIGIT_BITS) | bn.getDigit(i);
}
if (bn.isNegative()) {
return @bitCast(0 -% result);
}
return @bitCast(result);
}
// Check if bignum fits in a fixnum
pub fn fitsFixnum(bn: *const Bignum) bool {
const len = bn.length();
if (len == 0) return true;
if (len > 1) return false;
const digit = bn.getDigit(0);
const max_fixnum: Cell = @bitCast(@as(Fixnum, std.math.maxInt(Fixnum) >> @intCast(layouts.tag_bits)));
if (bn.isNegative()) {
// Min fixnum is -(max_fixnum + 1)
return digit <= max_fixnum + 1;
}
return digit <= max_fixnum;
}
// Returns a tagged value - either a fixnum if it fits, or the bignum pointer tagged
pub fn maybeToFixnum(bn: *const Bignum) Cell {
if (fitsFixnum(bn)) {
return layouts.tagFixnum(toFixnum(bn));
}
return layouts.tagBignum(@constCast(bn));
}
// Allocate bignum in VM nursery
pub fn allocBignum(vm: *FactorVM, len: Cell, negative: bool) !*Bignum {
const total_size = @sizeOf(Bignum) + (len + 1) * @sizeOf(Cell);
const tagged = vm.allotObject(.bignum, total_size) orelse return error.OutOfMemory;
const bn: *Bignum = @ptrFromInt(layouts.UNTAG(tagged));
bn.initialize(len, negative);
return bn;
}
// Allocate zeroed bignum in VM nursery
pub fn allocBignumZeroed(vm: *FactorVM, len: Cell, negative: bool) !*Bignum {
const bn = try allocBignum(vm, len, negative);
@memset(bn.digits()[0..len], 0);
return bn;
}
// Create bignum from signed 64-bit integer (VM version)
pub fn fromInt64(vm: *FactorVM, n: i64) !*Bignum {
if (n == 0) {
return zeroBignum(vm);
}
const negative = n < 0;
const abs_n: u64 = if (negative) @bitCast(-%n) else @bitCast(n);
if (abs_n < RADIX) {
const bn = try allocBignum(vm, 1, negative);
bn.setDigit(0, abs_n & DIGIT_MASK);
return bn;
}
const count: Cell = countDigitsUnsigned(abs_n);
const bn = try allocBignum(vm, count, negative);
var val = abs_n;
var i: Cell = 0;
while (val != 0) : (i += 1) {
bn.setDigit(i, val & DIGIT_MASK);
val >>= DIGIT_BITS;
}
return bn;
}
// Create bignum from unsigned 64-bit integer (VM version)
pub fn fromUint64(vm: *FactorVM, n: u64) !*Bignum {
if (n == 0) {
return zeroBignum(vm);
}
if (n < RADIX) {
const bn = try allocBignum(vm, 1, false);
bn.setDigit(0, n & DIGIT_MASK);
return bn;
}
const count: Cell = countDigitsUnsigned(n);
const bn = try allocBignum(vm, count, false);
var val = n;
var i: Cell = 0;
while (val != 0) : (i += 1) {
bn.setDigit(i, val & DIGIT_MASK);
val >>= DIGIT_BITS;
}
return bn;
}
// Convert bignum to signed 64-bit integer (may overflow)
pub fn toInt64(bn: *const Bignum) i64 {
if (bn.isZero()) return 0;
const len = bn.length();
if (len == 1) {
const result: u64 = @intCast(bn.getDigit(0));
return if (bn.isNegative()) -%@as(i64, @bitCast(result)) else @bitCast(result);
}
if (len == 2) {
const lo: u64 = @intCast(bn.getDigit(0));
const hi: u64 = @intCast(bn.getDigit(1));
const result: u64 = (hi << DIGIT_BITS) | lo;
return if (bn.isNegative()) -%@as(i64, @bitCast(result)) else @bitCast(result);
}
var result: u64 = 0;
var i: Cell = len;
while (i > 0) {
i -= 1;
result = (result << DIGIT_BITS) | bn.getDigit(i);
}
if (bn.isNegative()) {
return -%@as(i64, @bitCast(result));
}
return @bitCast(result);
}
// Convert bignum to unsigned 64-bit integer (may overflow)
pub fn toUint64(bn: *const Bignum) u64 {
if (bn.isZero()) return 0;
const len = bn.length();
if (len == 1) {
return @intCast(bn.getDigit(0));
}
if (len == 2) {
const lo: u64 = @intCast(bn.getDigit(0));
const hi: u64 = @intCast(bn.getDigit(1));
return (hi << DIGIT_BITS) | lo;
}
var result: u64 = 0;
var i: Cell = len;
while (i > 0) {
i -= 1;
result = (result << DIGIT_BITS) | bn.getDigit(i);
}
return result;
}
// Create bignum from fixnum using VM nursery
pub fn fromFixnum(vm: *FactorVM, n: Fixnum) !*Bignum {
if (n == 0) {
return zeroBignum(vm);
}
const negative = n < 0;
var abs_n: Cell = if (negative) @bitCast(-n) else @bitCast(n);
if (abs_n < RADIX) {
// Single digit
const bn = try allocBignum(vm, 1, negative);
bn.setDigit(0, abs_n & DIGIT_MASK);
return bn;
}
// Count digits needed
const count: Cell = countDigitsUnsigned(abs_n);
const bn = try allocBignum(vm, count, negative);
var i: Cell = 0;
while (abs_n != 0) : (i += 1) {
bn.setDigit(i, abs_n & DIGIT_MASK);
abs_n >>= DIGIT_BITS;
}
return bn;
}
// Create bignum from unsigned cell using VM nursery
pub fn fromCell(vm: *FactorVM, n: Cell) !*Bignum {
if (n == 0) {
return zeroBignum(vm);
}
if (n < RADIX) {
const bn = try allocBignum(vm, 1, false);
bn.setDigit(0, n & DIGIT_MASK);
return bn;
}
const count: Cell = countDigitsUnsigned(n);
const bn = try allocBignum(vm, count, false);
var val = n;
var i: Cell = 0;
while (val != 0) : (i += 1) {
bn.setDigit(i, val & DIGIT_MASK);
val >>= DIGIT_BITS;
}
return bn;
}
// Convert bignum to cell (unsigned, may overflow)
pub fn toCell(bn: *const Bignum) Cell {
if (bn.isZero()) return 0;
const len = bn.length();
if (len == 1) {
return bn.getDigit(0);
}
if (len == 2) {
return (bn.getDigit(1) << DIGIT_BITS) | bn.getDigit(0);
}
var result: Cell = 0;
var i: Cell = len;
while (i > 0) {
i -= 1;
result = (result << DIGIT_BITS) | bn.getDigit(i);
}
return result;
}
// Bignum arithmetic using VM nursery allocation
pub fn add(vm: *FactorVM, x: *const Bignum, y: *const Bignum) !*Bignum {
if (x.isZero()) return @constCast(y);
if (y.isZero()) return @constCast(x);
// Same sign: add magnitudes
if (x.isNegative() == y.isNegative()) {
return addUnsigned(vm, x, y, x.isNegative());
}
// Different signs: subtract magnitudes
const cmp = compareUnsigned(x, y);
return switch (cmp) {
.equal => zeroBignum(vm),
.less => subtractUnsigned(vm, y, x, y.isNegative()),
.greater => subtractUnsigned(vm, x, y, x.isNegative()),
};
}
pub fn subtract(vm: *FactorVM, x: *const Bignum, y: *const Bignum) !*Bignum {
if (y.isZero()) return @constCast(x);
if (x.isZero()) return negateBignum(vm, y);
// Different signs: add magnitudes
if (x.isNegative() != y.isNegative()) {
return addUnsigned(vm, x, y, x.isNegative());
}
// Same sign: subtract magnitudes
const cmp = compareUnsigned(x, y);
return switch (cmp) {
.equal => zeroBignum(vm),
.less => subtractUnsigned(vm, y, x, !x.isNegative()),
.greater => subtractUnsigned(vm, x, y, x.isNegative()),
};
}
pub fn multiply(vm: *FactorVM, x: *const Bignum, y: *const Bignum) !*Bignum {
if (x == y) {
return square(vm, x);
}
if (x.isZero() or y.isZero()) {
return zeroBignum(vm);
}
const x_len = x.length();
const y_len = y.length();
// Check for multiplication by 1 or -1
if (x_len == 1 and x.getDigit(0) == 1) {
if (x.isNegative()) {
return negateBignum(vm, y);
}
return @constCast(y);
}
if (y_len == 1 and y.getDigit(0) == 1) {
if (y.isNegative()) {
return negateBignum(vm, x);
}
return @constCast(x);
}
const result_negative = x.isNegative() != y.isNegative();
// Fast path: single-digit multiplier (O(n) instead of O(n²))
if (y_len == 1) {
return multiplyBySingleDigitVM(vm, x, y.getDigit(0), result_negative);
}
if (x_len == 1) {
return multiplyBySingleDigitVM(vm, y, x.getDigit(0), result_negative);
}
return try multiplyUnsigned(vm, x, y, result_negative);
}
// Square - optimized multiplication by self (VM version)
pub fn square(vm: *FactorVM, x_in: *const Bignum) !*Bignum {
if (x_in.isZero()) {
return zeroBignum(vm);
}
// Root x to protect from GC during allocation
var x_cell: Cell = layouts.tagBignum(@constCast(x_in));
std.debug.assert(vm.data_roots.items.len < vm.data_roots.capacity);
vm.data_roots.appendAssumeCapacity(&x_cell);
defer _ = vm.data_roots.pop();
const length = x_in.length();
const z = try allocBignumZeroed(vm, length + length, false);
// Re-derive x after potential GC
const x: *const Bignum = @ptrFromInt(layouts.UNTAG(x_cell));
const x_digits = x.digits()[0..length];
const z_digits = z.digits()[0 .. length + length];
const scratch_size = karatsubaScratchSize(length);
var empty = [_]Cell{};
const scratch = if (scratch_size > 0)
vm.allocator.alloc(Cell, scratch_size) catch return error.OutOfMemory
else
empty[0..];
defer if (scratch_size > 0) vm.allocator.free(scratch);
if (scratch_size > 0) @memset(scratch, 0);
squareDigits(x_digits, z_digits, scratch);
return trim(vm, z);
}
pub fn quotient(vm: *FactorVM, numerator: *const Bignum, denominator: *const Bignum) !*Bignum {
if (denominator.isZero()) {
return error.DivisionByZero;
}
if (numerator.isZero()) {
return zeroBignum(vm);
}
const q_negative = numerator.isNegative() != denominator.isNegative();
const cmp = compareUnsigned(numerator, denominator);
return switch (cmp) {
.equal => allocBignumWithDigit(vm, 1, q_negative, 1),
.less => zeroBignum(vm),
.greater => if (denominator.length() == 1)
// Single-digit: quotient-only path skips remainder allocation
divideBySingleDigitQuotientOnly(vm, numerator, denominator.getDigit(0), q_negative)
else
divideKnuthQuotientOnly(vm, numerator, denominator, q_negative),
};
}
pub fn divmod(vm: *FactorVM, numerator: *const Bignum, denominator: *const Bignum) !DivisionResult {
if (denominator.isZero()) {
return error.DivisionByZero;
}
if (numerator.isZero()) {
const q = try zeroBignum(vm);
var q_cell: Cell = layouts.tagBignum(q);
std.debug.assert(vm.data_roots.items.len < vm.data_roots.capacity);
vm.data_roots.appendAssumeCapacity(&q_cell);
defer _ = vm.data_roots.pop();
const r = try zeroBignum(vm);
return .{
.quotient = @ptrFromInt(layouts.UNTAG(q_cell)),
.remainder = r,
};
}
// Root inputs for the .less and .greater cases
var num_cell: Cell = layouts.tagBignum(@constCast(numerator));
var den_cell: Cell = layouts.tagBignum(@constCast(denominator));
std.debug.assert(vm.data_roots.capacity - vm.data_roots.items.len >= 2);
vm.data_roots.appendAssumeCapacity(&num_cell);
defer _ = vm.data_roots.pop();
vm.data_roots.appendAssumeCapacity(&den_cell);
defer _ = vm.data_roots.pop();
const q_negative = numerator.isNegative() != denominator.isNegative();
const r_negative = numerator.isNegative();
const cmp = compareUnsigned(numerator, denominator);
return switch (cmp) {
.equal => blk: {
const q = try allocBignumWithDigit(vm, 1, q_negative, 1);
var q_cell: Cell = layouts.tagBignum(q);
std.debug.assert(vm.data_roots.items.len < vm.data_roots.capacity);
vm.data_roots.appendAssumeCapacity(&q_cell);
defer _ = vm.data_roots.pop();
const r = try zeroBignum(vm);
break :blk .{
.quotient = @ptrFromInt(layouts.UNTAG(q_cell)),
.remainder = r,
};
},
.less => blk: {
const q = try zeroBignum(vm);
var q_cell: Cell = layouts.tagBignum(q);
std.debug.assert(vm.data_roots.items.len < vm.data_roots.capacity);
vm.data_roots.appendAssumeCapacity(&q_cell);
defer _ = vm.data_roots.pop();
const num: *const Bignum = @ptrFromInt(layouts.UNTAG(num_cell));
const r = try copyBignumWithSign(vm, num, r_negative);
break :blk .{
.quotient = @ptrFromInt(layouts.UNTAG(q_cell)),
.remainder = r,
};
},
.greater => blk: {
const num: *const Bignum = @ptrFromInt(layouts.UNTAG(num_cell));
const den: *const Bignum = @ptrFromInt(layouts.UNTAG(den_cell));
break :blk try divideUnsigned(vm, num, den, q_negative, r_negative);
},
};
}
pub fn shift(vm: *FactorVM, x: *const Bignum, shift_amt: Fixnum) !*Bignum {
if (x.isZero() or shift_amt == 0) {
return @constCast(x);
}
if (shift_amt > 0) {
return shiftLeft(vm, x, @intCast(shift_amt));
} else {
// Arithmetic right shift for negative numbers:
if (x.isNegative()) {
const not_x = try bitNot(vm, x);
const shifted = try shiftRight(vm, not_x, @intCast(-shift_amt));
return bitNot(vm, shifted);
}
return shiftRight(vm, x, @intCast(-shift_amt));
}
}
// Bignum bitwise operations. Sign-case routing is identical for all three
// ops, so we unify into a single comptime-parameterized entry point.
fn bitwiseOp(vm: *FactorVM, x: *const Bignum, y: *const Bignum, comptime op: BitwiseOp) !*Bignum {
if (!x.isNegative() and !y.isNegative()) {
return bignumPosPosOp(vm, x, y, op);
}
if (x.isNegative() and y.isNegative()) {
return bignumNegNegOp(vm, x, y, op);
}
// One positive, one negative — positive arg must be first
if (x.isNegative()) {
return bignumPosNegOp(vm, y, x, op);
}
return bignumPosNegOp(vm, x, y, op);
}
pub fn bitAnd(vm: *FactorVM, x: *const Bignum, y: *const Bignum) !*Bignum {
return bitwiseOp(vm, x, y, .and_op);
}
pub fn bitOr(vm: *FactorVM, x: *const Bignum, y: *const Bignum) !*Bignum {
return bitwiseOp(vm, x, y, .or_op);
}
pub fn bitXor(vm: *FactorVM, x: *const Bignum, y: *const Bignum) !*Bignum {
return bitwiseOp(vm, x, y, .xor_op);
}
const BitwiseOp = enum { and_op, or_op, xor_op };
// Positive-positive bitwise op with direct nursery allocation.
// does digit-wise operation in place. No malloc/free intermediate.
fn bignumPosPosOp(vm: *FactorVM, x_in: *const Bignum, y_in: *const Bignum, comptime op: BitwiseOp) !*Bignum {
if (x_in.isZero()) {
return switch (op) {
.and_op => zeroBignum(vm),
.or_op, .xor_op => copyBignum(vm, y_in),
};
}
if (y_in.isZero()) {
return switch (op) {
.and_op => zeroBignum(vm),
.or_op, .xor_op => copyBignum(vm, x_in),
};
}
// Root both inputs — allocBignum can trigger GC
var x_cell: Cell = layouts.tagBignum(@constCast(x_in));
var y_cell: Cell = layouts.tagBignum(@constCast(y_in));
std.debug.assert(vm.data_roots.capacity - vm.data_roots.items.len >= 2);
vm.data_roots.appendAssumeCapacity(&x_cell);
defer _ = vm.data_roots.pop();
vm.data_roots.appendAssumeCapacity(&y_cell);
defer _ = vm.data_roots.pop();
const x_len = x_in.length();
const y_len = y_in.length();
// AND result can't exceed the shorter operand; OR/XOR need the longer
const alloc_len = switch (op) {
.and_op => @min(x_len, y_len),
.or_op, .xor_op => @max(x_len, y_len),
};
// Allocate result directly in nursery (may trigger GC)
const bn = try allocBignum(vm, alloc_len, false);
// Re-derive pointers after potential GC, pre-compute digit slices
const x: *const Bignum = @ptrFromInt(layouts.UNTAG(x_cell));
const y: *const Bignum = @ptrFromInt(layouts.UNTAG(y_cell));
const xl = x.length();
const yl = y.length();
const x_digits = x.digits();
const y_digits = y.digits();
const r_digits = bn.digits();
const min_len = @min(xl, yl);
// Phase 1: both operands have digits
for (0..min_len) |i| {
r_digits[i] = switch (op) {
.and_op => x_digits[i] & y_digits[i],
.or_op => x_digits[i] | y_digits[i],
.xor_op => x_digits[i] ^ y_digits[i],
};
}
// Phase 2: only the longer operand has digits (AND doesn't need this)
if (op != .and_op) {
const max_len = @max(xl, yl);
if (xl > yl) {
@memcpy(r_digits[min_len..max_len], x_digits[min_len..max_len]);
} else if (yl > xl) {
@memcpy(r_digits[min_len..max_len], y_digits[min_len..max_len]);
}
}
// OR with trimmed inputs: top digit is at least the longer operand's
// top digit (non-zero), so no leading zeros possible.
if (op == .or_op) return bn;
// AND and XOR can produce leading zeros — trim needed
return trim(vm, bn);
}
// Positive-negative bitwise op with direct nursery allocation.
// Converts arg2 to two's complement on the fly, no intermediate malloc.
fn bignumPosNegOp(vm: *FactorVM, arg1_in: *const Bignum, arg2_in: *const Bignum, comptime op: BitwiseOp) !*Bignum {
std.debug.assert(!arg1_in.isNegative() and arg2_in.isNegative());
// Root both inputs
var arg1_cell: Cell = layouts.tagBignum(@constCast(arg1_in));
var arg2_cell: Cell = layouts.tagBignum(@constCast(arg2_in));
std.debug.assert(vm.data_roots.capacity - vm.data_roots.items.len >= 2);
vm.data_roots.appendAssumeCapacity(&arg1_cell);
defer _ = vm.data_roots.pop();
vm.data_roots.appendAssumeCapacity(&arg2_cell);
defer _ = vm.data_roots.pop();
const arg1_len = arg1_in.length();
const arg2_len = arg2_in.length();
const neg_p = (op == .or_op or op == .xor_op);
const max_len = if (arg1_len > arg2_len + 1) arg1_len else arg2_len + 1;
const bn = try allocBignum(vm, max_len, neg_p);
// Re-derive after potential GC, pre-compute digit slices
const arg1: *const Bignum = @ptrFromInt(layouts.UNTAG(arg1_cell));
const arg2: *const Bignum = @ptrFromInt(layouts.UNTAG(arg2_cell));
const a1_len = arg1.length();
const a2_len = arg2.length();
const a1_digits = arg1.digits();
const a2_digits = arg2.digits();
const r_digits = bn.digits();
// Convert arg2 from sign-magnitude to two's complement on the fly.
// Two's complement: ~digit & MASK + carry. Once carry drops to 0
// (typically after 1-2 digits), the conversion simplifies to just
// ~digit & MASK with no carry branch, so we split into two loops.
var i: usize = 0;
var carry2: Cell = 1;
// Phase 1: carry is live (typically 1-2 iterations)
while (i < max_len and carry2 != 0) : (i += 1) {
const digit1: Cell = if (i < a1_len) a1_digits[i] else 0;
const raw_digit2: Cell = if (i < a2_len) a2_digits[i] else 0;
var digit2: Cell = ((~raw_digit2) & DIGIT_MASK) +% 1;
if (digit2 < RADIX) {
carry2 = 0;
} else {
digit2 = digit2 -% RADIX;
}
r_digits[i] = switch (op) {
.and_op => digit1 & digit2,
.or_op => digit1 | digit2,
.xor_op => digit1 ^ digit2,
};
}
// Phase 2: carry is dead — branch-free inversion
while (i < max_len) : (i += 1) {
const digit1: Cell = if (i < a1_len) a1_digits[i] else 0;
const raw_digit2: Cell = if (i < a2_len) a2_digits[i] else 0;
const digit2: Cell = (~raw_digit2) & DIGIT_MASK;
r_digits[i] = switch (op) {
.and_op => digit1 & digit2,
.or_op => digit1 | digit2,
.xor_op => digit1 ^ digit2,
};
}
// If result is negative, convert back from two's complement to sign-magnitude
if (neg_p) {
negateMagnitude(bn);
}
return trim(vm, bn);
}
// Negative-negative bitwise op with direct nursery allocation.
fn bignumNegNegOp(vm: *FactorVM, arg1_in: *const Bignum, arg2_in: *const Bignum, comptime op: BitwiseOp) !*Bignum {
std.debug.assert(arg1_in.isNegative() and arg2_in.isNegative());
// Root both inputs
var arg1_cell: Cell = layouts.tagBignum(@constCast(arg1_in));
var arg2_cell: Cell = layouts.tagBignum(@constCast(arg2_in));
std.debug.assert(vm.data_roots.capacity - vm.data_roots.items.len >= 2);
vm.data_roots.appendAssumeCapacity(&arg1_cell);
defer _ = vm.data_roots.pop();
vm.data_roots.appendAssumeCapacity(&arg2_cell);
defer _ = vm.data_roots.pop();
const arg1_len = arg1_in.length();
const arg2_len = arg2_in.length();
const neg_p = (op == .and_op or op == .or_op);
const max_len = (if (arg1_len > arg2_len) arg1_len else arg2_len) + 1;
const bn = try allocBignum(vm, max_len, neg_p);
// Re-derive after potential GC, pre-compute digit slices
const arg1: *const Bignum = @ptrFromInt(layouts.UNTAG(arg1_cell));
const arg2: *const Bignum = @ptrFromInt(layouts.UNTAG(arg2_cell));
const a1_len = arg1.length();
const a2_len = arg2.length();
const a1_digits = arg1.digits();
const a2_digits = arg2.digits();
const r_digits = bn.digits();
var i: usize = 0;
var carry1: Cell = 1;
var carry2: Cell = 1;
// Phase 1: both carries live
while (i < max_len and (carry1 | carry2) != 0) : (i += 1) {
const raw_digit1: Cell = if (i < a1_len) a1_digits[i] else 0;
var digit1: Cell = ((~raw_digit1) & DIGIT_MASK) +% carry1;
if (digit1 < RADIX) {
carry1 = 0;
} else {
digit1 = digit1 -% RADIX;
}
const raw_digit2: Cell = if (i < a2_len) a2_digits[i] else 0;
var digit2: Cell = ((~raw_digit2) & DIGIT_MASK) +% carry2;
if (digit2 < RADIX) {
carry2 = 0;
} else {
digit2 = digit2 -% RADIX;
}
r_digits[i] = switch (op) {
.and_op => digit1 & digit2,
.or_op => digit1 | digit2,
.xor_op => digit1 ^ digit2,
};
}
// Phase 2: both carries dead — branch-free inversion
while (i < max_len) : (i += 1) {
const raw_digit1: Cell = if (i < a1_len) a1_digits[i] else 0;
const digit1: Cell = (~raw_digit1) & DIGIT_MASK;
const raw_digit2: Cell = if (i < a2_len) a2_digits[i] else 0;
const digit2: Cell = (~raw_digit2) & DIGIT_MASK;
r_digits[i] = switch (op) {
.and_op => digit1 & digit2,
.or_op => digit1 | digit2,
.xor_op => digit1 ^ digit2,
};
}
// If result is negative, convert back from two's complement to sign-magnitude
if (neg_p) {
negateMagnitude(bn);
}
return trim(vm, bn);
}
// Negate magnitude in place (two's complement conversion).
fn negateMagnitude(arg: *Bignum) void {
const len = arg.length();
const d = arg.digits();
var carry: Cell = 1;
for (0..len) |i| {
var digit: Cell = ((~d[i]) & DIGIT_MASK) +% carry;
if (digit < RADIX) {
carry = 0;
} else {
digit = digit -% RADIX;
carry = 1;
}
d[i] = digit;
}
}
// Bignum bitwise NOT: ~x = -(x+1)
// Direct nursery allocation, no BignumOps intermediate.
pub fn bitNot(vm: *FactorVM, x: *const Bignum) !*Bignum {
if (x.isZero()) {
// ~0 = -1
return allocBignumWithDigit(vm, 1, true, 1);
}
if (x.isNegative()) {
// ~(-n) = n - 1: subtract 1 from magnitude, result positive
return subtractOneMagnitude(vm, x, false);
} else {
// ~n = -(n + 1): add 1 to magnitude, result negative
return addOneMagnitude(vm, x, true);
}
}
// Add 1 to magnitude of x, set sign. Result allocated in nursery.
fn addOneMagnitude(vm: *FactorVM, x_in: *const Bignum, negative: bool) !*Bignum {
var x_cell: Cell = layouts.tagBignum(@constCast(x_in));
std.debug.assert(vm.data_roots.items.len < vm.data_roots.capacity);
vm.data_roots.appendAssumeCapacity(&x_cell);
defer _ = vm.data_roots.pop();
const x_len = x_in.length();
const r = try allocBignum(vm, x_len, negative);
const x: *const Bignum = @ptrFromInt(layouts.UNTAG(x_cell));
var carry: Cell = 1;
for (0..x_len) |i| {
const sum = x.getDigit(i) + carry;
r.setDigit(i, sum & DIGIT_MASK);
carry = sum >> DIGIT_BITS;
}
if (carry != 0) {
var r_cell: Cell = layouts.tagBignum(r);
std.debug.assert(vm.data_roots.items.len < vm.data_roots.capacity);
vm.data_roots.appendAssumeCapacity(&r_cell);
defer _ = vm.data_roots.pop();
const r2 = try allocBignum(vm, x_len + 1, negative);
const rr: *const Bignum = @ptrFromInt(layouts.UNTAG(r_cell));
@memcpy(r2.digits()[0..x_len], rr.digits()[0..x_len]);
r2.setDigit(x_len, carry);
return r2;
}
return r;
}
// Subtract 1 from magnitude of x, set sign. Result allocated in nursery.
// Precondition: x is not zero (caller must check).
fn subtractOneMagnitude(vm: *FactorVM, x_in: *const Bignum, negative: bool) !*Bignum {
var x_cell: Cell = layouts.tagBignum(@constCast(x_in));
std.debug.assert(vm.data_roots.items.len < vm.data_roots.capacity);
vm.data_roots.appendAssumeCapacity(&x_cell);
defer _ = vm.data_roots.pop();
const x_len = x_in.length();
const r = try allocBignum(vm, x_len, negative);
const x: *const Bignum = @ptrFromInt(layouts.UNTAG(x_cell));