-
-
Notifications
You must be signed in to change notification settings - Fork 289
/
dec.zig
1604 lines (1285 loc) · 48.3 KB
/
dec.zig
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
const std = @import("std");
const str = @import("str.zig");
const num_ = @import("num.zig");
const utils = @import("utils.zig");
const math = std.math;
const RocStr = str.RocStr;
const WithOverflow = utils.WithOverflow;
const roc_panic = @import("panic.zig").panic_help;
const U256 = num_.U256;
const mul_u128 = num_.mul_u128;
pub const RocDec = extern struct {
num: i128,
pub const decimal_places: u5 = 18;
pub const whole_number_places: u5 = 21;
const max_digits: u6 = 39;
const max_str_length: u6 = max_digits + 2; // + 2 here to account for the sign & decimal dot
pub const min: RocDec = .{ .num = math.minInt(i128) };
pub const max: RocDec = .{ .num = math.maxInt(i128) };
pub const one_point_zero_i128: i128 = math.pow(i128, 10, RocDec.decimal_places);
pub const one_point_zero: RocDec = .{ .num = one_point_zero_i128 };
pub const two_point_zero: RocDec = RocDec.add(RocDec.one_point_zero, RocDec.one_point_zero);
pub const zero_point_five: RocDec = RocDec.div(RocDec.one_point_zero, RocDec.two_point_zero);
pub fn fromU64(num: u64) RocDec {
return .{ .num = num * one_point_zero_i128 };
}
pub fn fromF64(num: f64) ?RocDec {
var result: f64 = num * comptime @as(f64, @floatFromInt(one_point_zero_i128));
if (result > comptime @as(f64, @floatFromInt(math.maxInt(i128)))) {
return null;
}
if (result < comptime @as(f64, @floatFromInt(math.minInt(i128)))) {
return null;
}
var ret: RocDec = .{ .num = @as(i128, @intFromFloat(result)) };
return ret;
}
pub fn toF64(dec: RocDec) f64 {
return @as(f64, @floatFromInt(dec.num)) / comptime @as(f64, @floatFromInt(one_point_zero_i128));
}
// TODO: If Str.toDec eventually supports more error types, return errors here.
// For now, just return null which will give the default error.
pub fn fromStr(roc_str: RocStr) ?RocDec {
if (roc_str.isEmpty()) {
return null;
}
const length = roc_str.len();
const roc_str_slice = roc_str.asSlice();
var is_negative: bool = roc_str_slice[0] == '-';
var initial_index: usize = if (is_negative) 1 else 0;
var point_index: ?usize = null;
var index: usize = initial_index;
while (index < length) {
var byte: u8 = roc_str_slice[index];
if (byte == '.' and point_index == null) {
point_index = index;
index += 1;
continue;
}
if (!isDigit(byte)) {
return null;
}
index += 1;
}
var before_str_length = length;
var after_val_i128: ?i128 = null;
if (point_index) |pi| {
before_str_length = pi;
var after_str_len = (length - 1) - pi;
if (after_str_len > decimal_places) {
// TODO: runtime exception for too many decimal places!
return null;
}
var diff_decimal_places = decimal_places - after_str_len;
var after_str = roc_str_slice[pi + 1 .. length];
var after_u64 = std.fmt.parseUnsigned(u64, after_str, 10) catch null;
after_val_i128 = if (after_u64) |f| @as(i128, @intCast(f)) * math.pow(i128, 10, diff_decimal_places) else null;
}
var before_str = roc_str_slice[initial_index..before_str_length];
var before_val_not_adjusted = std.fmt.parseUnsigned(i128, before_str, 10) catch null;
var before_val_i128: ?i128 = null;
if (before_val_not_adjusted) |before| {
const answer = @mulWithOverflow(before, one_point_zero_i128);
const result = answer[0];
const overflowed = answer[1];
if (overflowed == 1) {
// TODO: runtime exception for overflow!
return null;
}
before_val_i128 = result;
}
const dec: RocDec = blk: {
if (before_val_i128) |before| {
if (after_val_i128) |after| {
var answer = @addWithOverflow(before, after);
const result = answer[0];
const overflowed = answer[1];
if (overflowed == 1) {
// TODO: runtime exception for overflow!
return null;
}
break :blk .{ .num = result };
} else {
break :blk .{ .num = before };
}
} else if (after_val_i128) |after| {
break :blk .{ .num = after };
} else {
return null;
}
};
if (is_negative) {
return dec.negate();
} else {
return dec;
}
}
inline fn isDigit(c: u8) bool {
return (c -% 48) <= 9;
}
pub fn toStr(self: RocDec) RocStr {
// Special case
if (self.num == 0) {
return RocStr.init("0.0", 3);
}
const num = self.num;
const is_negative = num < 0;
// Format the backing i128 into an array of digit (ascii) characters (u8s)
var digit_bytes_storage: [max_digits + 1]u8 = undefined;
var num_digits = std.fmt.formatIntBuf(digit_bytes_storage[0..], num, 10, .lower, .{});
var digit_bytes: [*]u8 = digit_bytes_storage[0..];
// space where we assemble all the characters that make up the final string
var str_bytes: [max_str_length]u8 = undefined;
var position: usize = 0;
// if negative, the first character is a negating minus
if (is_negative) {
str_bytes[position] = '-';
position += 1;
// but also, we have one fewer digit than we have characters
num_digits -= 1;
// and we drop the minus to make later arithmetic correct
digit_bytes += 1;
}
// Get the slice for before the decimal point
var before_digits_offset: usize = 0;
if (num_digits > decimal_places) {
// we have more digits than fit after the decimal point,
// so we must have digits before the decimal point
before_digits_offset = num_digits - decimal_places;
for (digit_bytes[0..before_digits_offset]) |c| {
str_bytes[position] = c;
position += 1;
}
} else {
// otherwise there are no actual digits before the decimal point
// but we format it with a '0'
str_bytes[position] = '0';
position += 1;
}
// we've done everything before the decimal point, so now we can put the decimal point in
str_bytes[position] = '.';
position += 1;
const trailing_zeros: u6 = count_trailing_zeros_base10(num);
if (trailing_zeros >= decimal_places) {
// add just a single zero if all decimal digits are zero
str_bytes[position] = '0';
position += 1;
} else {
// Figure out if we need to prepend any zeros to the after decimal point
// For example, for the number 0.000123 we need to prepend 3 zeros after the decimal point
const after_zeros_num = if (num_digits < decimal_places) decimal_places - num_digits else 0;
var i: usize = 0;
while (i < after_zeros_num) : (i += 1) {
str_bytes[position] = '0';
position += 1;
}
// otherwise append the decimal digits except the trailing zeros
for (digit_bytes[before_digits_offset .. num_digits - trailing_zeros]) |c| {
str_bytes[position] = c;
position += 1;
}
}
return RocStr.init(&str_bytes, position);
}
pub fn toI128(self: RocDec) i128 {
return self.num;
}
pub fn fromI128(num: i128) RocDec {
return .{ .num = num };
}
pub fn eq(self: RocDec, other: RocDec) bool {
return self.num == other.num;
}
pub fn neq(self: RocDec, other: RocDec) bool {
return self.num != other.num;
}
pub fn negate(self: RocDec) ?RocDec {
var negated = math.negate(self.num) catch null;
return if (negated) |n| .{ .num = n } else null;
}
pub fn abs(self: RocDec) !RocDec {
const absolute = try math.absInt(self.num);
return RocDec{ .num = absolute };
}
pub fn addWithOverflow(self: RocDec, other: RocDec) WithOverflow(RocDec) {
const answer = @addWithOverflow(self.num, other.num);
return .{ .value = RocDec{ .num = answer[0] }, .has_overflowed = answer[1] == 1 };
}
pub fn add(self: RocDec, other: RocDec) RocDec {
const answer = RocDec.addWithOverflow(self, other);
if (answer.has_overflowed) {
roc_panic("Decimal addition overflowed!", 0);
} else {
return answer.value;
}
}
pub fn addSaturated(self: RocDec, other: RocDec) RocDec {
const answer = RocDec.addWithOverflow(self, other);
if (answer.has_overflowed) {
// We can unambiguously tell which way it wrapped, because we have 129 bits including the overflow bit
if (answer.value.num < 0) {
return RocDec.max;
} else {
return RocDec.min;
}
} else {
return answer.value;
}
}
pub fn subWithOverflow(self: RocDec, other: RocDec) WithOverflow(RocDec) {
const answer = @subWithOverflow(self.num, other.num);
return .{ .value = RocDec{ .num = answer[0] }, .has_overflowed = answer[1] == 1 };
}
pub fn sub(self: RocDec, other: RocDec) RocDec {
const answer = RocDec.subWithOverflow(self, other);
if (answer.has_overflowed) {
roc_panic("Decimal subtraction overflowed!", 0);
} else {
return answer.value;
}
}
pub fn subSaturated(self: RocDec, other: RocDec) RocDec {
const answer = RocDec.subWithOverflow(self, other);
if (answer.has_overflowed) {
if (answer.value.num < 0) {
return RocDec.max;
} else {
return RocDec.min;
}
} else {
return answer.value;
}
}
pub fn mulWithOverflow(self: RocDec, other: RocDec) WithOverflow(RocDec) {
const self_i128 = self.num;
const other_i128 = other.num;
// const answer = 0; //self_i256 * other_i256;
const is_answer_negative = (self_i128 < 0) != (other_i128 < 0);
const self_u128 = @as(u128, @intCast(math.absInt(self_i128) catch {
if (other_i128 == 0) {
return .{ .value = RocDec{ .num = 0 }, .has_overflowed = false };
} else if (other_i128 == RocDec.one_point_zero.num) {
return .{ .value = self, .has_overflowed = false };
} else if (is_answer_negative) {
return .{ .value = RocDec.min, .has_overflowed = true };
} else {
return .{ .value = RocDec.max, .has_overflowed = true };
}
}));
const other_u128 = @as(u128, @intCast(math.absInt(other_i128) catch {
if (self_i128 == 0) {
return .{ .value = RocDec{ .num = 0 }, .has_overflowed = false };
} else if (self_i128 == RocDec.one_point_zero.num) {
return .{ .value = other, .has_overflowed = false };
} else if (is_answer_negative) {
return .{ .value = RocDec.min, .has_overflowed = true };
} else {
return .{ .value = RocDec.max, .has_overflowed = true };
}
}));
const unsigned_answer: i128 = mul_and_decimalize(self_u128, other_u128);
if (is_answer_negative) {
return .{ .value = RocDec{ .num = -unsigned_answer }, .has_overflowed = false };
} else {
return .{ .value = RocDec{ .num = unsigned_answer }, .has_overflowed = false };
}
}
fn trunc(self: RocDec) RocDec {
return RocDec.sub(self, self.fract());
}
fn fract(self: RocDec) RocDec {
const sign = std.math.sign(self.num);
const digits = @mod(sign * self.num, RocDec.one_point_zero.num);
return RocDec{ .num = sign * digits };
}
// Returns the nearest integer to self. If a value is half-way between two integers, round away from 0.0.
fn round(arg1: RocDec) RocDec {
// this rounds towards zero
const tmp = arg1.trunc();
const sign = std.math.sign(arg1.num);
const abs_fract = sign * arg1.fract().num;
if (abs_fract >= RocDec.zero_point_five.num) {
return RocDec.add(tmp, RocDec{ .num = sign * RocDec.one_point_zero.num });
} else {
return tmp;
}
}
// Returns the largest integer less than or equal to itself
fn floor(arg1: RocDec) RocDec {
const tmp = arg1.trunc();
if (arg1.num < 0 and arg1.fract().num != 0) {
return RocDec.sub(tmp, RocDec.one_point_zero);
} else {
return tmp;
}
}
// Returns the smallest integer greater than or equal to itself
fn ceiling(arg1: RocDec) RocDec {
const tmp = arg1.trunc();
if (arg1.num > 0 and arg1.fract().num != 0) {
return RocDec.add(tmp, RocDec.one_point_zero);
} else {
return tmp;
}
}
fn powInt(base: RocDec, exponent: i128) RocDec {
if (exponent == 0) {
return RocDec.one_point_zero;
} else if (exponent > 0) {
if (@mod(exponent, 2) == 0) {
const half_power = RocDec.powInt(base, exponent >> 1); // `>> 1` == `/ 2`
return RocDec.mul(half_power, half_power);
} else {
return RocDec.mul(base, RocDec.powInt(base, exponent - 1));
}
} else {
return RocDec.div(RocDec.one_point_zero, RocDec.powInt(base, -exponent));
}
}
fn pow(base: RocDec, exponent: RocDec) RocDec {
if (exponent.trunc().num == exponent.num) {
return base.powInt(@divTrunc(exponent.num, RocDec.one_point_zero_i128));
} else {
return fromF64(std.math.pow(f64, base.toF64(), exponent.toF64())).?;
}
}
pub fn mul(self: RocDec, other: RocDec) RocDec {
const answer = RocDec.mulWithOverflow(self, other);
if (answer.has_overflowed) {
roc_panic("Decimal multiplication overflowed!", 0);
} else {
return answer.value;
}
}
pub fn mulSaturated(self: RocDec, other: RocDec) RocDec {
const answer = RocDec.mulWithOverflow(self, other);
return answer.value;
}
pub fn div(self: RocDec, other: RocDec) RocDec {
const numerator_i128 = self.num;
const denominator_i128 = other.num;
// (0 / n) is always 0
if (numerator_i128 == 0) {
return RocDec{ .num = 0 };
}
// (n / 0) is an error
if (denominator_i128 == 0) {
roc_panic("Decimal division by 0!", 0);
}
// If they're both negative, or if neither is negative, the final answer
// is positive or zero. If one is negative and the denominator isn't, the
// final answer is negative (or zero, in which case final sign won't matter).
//
// It's important that we do this in terms of negatives, because doing
// it in terms of positives can cause bugs when one is zero.
const is_answer_negative = (numerator_i128 < 0) != (denominator_i128 < 0);
// Break the two i128s into two { hi: u64, lo: u64 } tuples, discarding
// the sign for now.
//
// We'll multiply all 4 combinations of these (hi1 x lo1, hi2 x lo2,
// hi1 x lo2, hi2 x lo1) and add them as appropriate, then apply the
// appropriate sign at the very end.
//
// We do checked_abs because if we had -i128::MAX before, this will overflow.
const numerator_abs_i128 = math.absInt(numerator_i128) catch {
// Currently, if you try to do multiplication on i64::MIN, panic
// unless you're specifically multiplying by 0 or 1.
//
// Maybe we could support more cases in the future
if (denominator_i128 == one_point_zero_i128) {
return self;
} else {
roc_panic("Decimal division overflow in numerator!", 0);
}
};
const numerator_u128 = @as(u128, @intCast(numerator_abs_i128));
const denominator_abs_i128 = math.absInt(denominator_i128) catch {
// Currently, if you try to do multiplication on i64::MIN, panic
// unless you're specifically multiplying by 0 or 1.
//
// Maybe we could support more cases in the future
if (numerator_i128 == one_point_zero_i128) {
return other;
} else {
roc_panic("Decimal division overflow in denominator!", 0);
}
};
const denominator_u128 = @as(u128, @intCast(denominator_abs_i128));
const numerator_u256: U256 = mul_u128(numerator_u128, math.pow(u128, 10, decimal_places));
const answer = div_u256_by_u128(numerator_u256, denominator_u128);
var unsigned_answer: i128 = undefined;
if (answer.hi == 0 and answer.lo <= math.maxInt(i128)) {
unsigned_answer = @as(i128, @intCast(answer.lo));
} else {
roc_panic("Decimal division overflow!", 0);
}
return RocDec{ .num = if (is_answer_negative) -unsigned_answer else unsigned_answer };
}
fn mod2pi(self: RocDec) RocDec {
// This is made to be used before calling trig functions that work on the range 0 to 2*pi.
// It should be reasonable fast (much faster than calling @mod) and much more accurate as well.
// b is 2*pi as a dec. which is 6.2831853071795864769252867665590057684
// as dec is times 10^18 so 6283185307179586476.9252867665590057684
const b0: u64 = 6283185307179586476;
// Fraction that reprensents 64 bits of precision past what dec normally supports.
// 0.9252867665590057684 as binary to 64 places.
const b1: u64 = 0b1110110011011111100101111111000111001010111000100101011111110111;
// This is dec/(b0+1), but as a multiplication.
// So dec * (1/(b0+1)). This is way faster.
const dec = self.num;
const tmp = @as(i128, @intCast(num_.mul_u128(math.absCast(dec), 249757942369376157886101012127821356963).hi >> (190 - 128)));
const q0 = if (dec < 0) -tmp else tmp;
const upper = q0 * b0;
const answer = @mulWithOverflow(q0, b1);
const lower = answer[0];
const overflowed = answer[1];
// TODO: maybe write this out branchlessly.
// Currently is is probably cmovs, but could be just math?
const q0_sign: i128 =
if (q0 > 0) 1 else -1;
const overflowed_val: i128 = if (overflowed == 1) q0_sign << 64 else 0;
const full = upper + @as(i128, @intCast(lower >> 64)) + overflowed_val;
var out = dec - full;
if (out < 0) {
out += b0;
}
return RocDec{ .num = out };
}
pub fn log(self: RocDec) RocDec {
return fromF64(@log(self.toF64())).?;
}
// I belive the output of the trig functions is always in range of Dec.
// If not, we probably should just make it saturate the Dec.
// I don't think this should crash or return errors.
pub fn sin(self: RocDec) RocDec {
return fromF64(math.sin(self.mod2pi().toF64())).?;
}
pub fn cos(self: RocDec) RocDec {
return fromF64(math.cos(self.mod2pi().toF64())).?;
}
pub fn tan(self: RocDec) RocDec {
return fromF64(math.tan(self.mod2pi().toF64())).?;
}
pub fn asin(self: RocDec) RocDec {
return fromF64(math.asin(self.toF64())).?;
}
pub fn acos(self: RocDec) RocDec {
return fromF64(math.acos(self.toF64())).?;
}
pub fn atan(self: RocDec) RocDec {
return fromF64(math.atan(self.toF64())).?;
}
};
// A number has `k` trailling zeros if `10^k` divides into it cleanly
inline fn count_trailing_zeros_base10(input: i128) u6 {
if (input == 0) {
// this should not happen in practice
return 0;
}
var count: u6 = 0;
var k: i128 = 1;
while (true) {
if (@mod(input, std.math.pow(i128, 10, k)) == 0) {
count += 1;
k += 1;
} else {
break;
}
}
return count;
}
fn mul_and_decimalize(a: u128, b: u128) i128 {
const answer_u256 = mul_u128(a, b);
var lhs_hi = answer_u256.hi;
var lhs_lo = answer_u256.lo;
// Divide - or just add 1, multiply by floor(2^315/10^18), then right shift 315 times.
// floor(2^315/10^18) is 66749594872528440074844428317798503581334516323645399060845050244444366430645
// Add 1.
// This can't overflow because the initial numbers are only 127bit due to removing the sign bit.
var answer = @addWithOverflow(lhs_lo, 1);
lhs_lo = answer[0];
var overflowed = answer[1];
lhs_hi = blk: {
if (overflowed == 1) {
break :blk lhs_hi + 1;
} else {
break :blk lhs_hi + 0;
}
};
// This needs to do multiplication in a way that expands,
// since we throw away 315 bits we care only about the higher end, not lower.
// So like need to do high low mult with 2 U256's and then bitshift.
// I bet this has a lot of room for multiplication optimization.
const rhs_hi: u128 = 0x9392ee8e921d5d073aff322e62439fcf;
const rhs_lo: u128 = 0x32d7f344649470f90cac0c573bf9e1b5;
const ea = mul_u128(lhs_lo, rhs_lo);
const gf = mul_u128(lhs_hi, rhs_lo);
const jh = mul_u128(lhs_lo, rhs_hi);
const lk = mul_u128(lhs_hi, rhs_hi);
const e = ea.hi;
// const _a = ea.lo;
const g = gf.hi;
const f = gf.lo;
const j = jh.hi;
const h = jh.lo;
const l = lk.hi;
const k = lk.lo;
// b = e + f + h
answer = @addWithOverflow(e, f);
const e_plus_f = answer[0];
overflowed = answer[1];
var b_carry1: u128 = undefined;
if (overflowed == 1) {
b_carry1 = 1;
} else {
b_carry1 = 0;
}
answer = @addWithOverflow(e_plus_f, h);
overflowed = answer[1];
var b_carry2: u128 = undefined;
if (overflowed == 1) {
b_carry2 = 1;
} else {
b_carry2 = 0;
}
// c = carry + g + j + k // it doesn't say +k but I think it should be?
answer = @addWithOverflow(g, j);
const g_plus_j = answer[0];
overflowed = answer[1];
var c_carry1: u128 = undefined;
if (overflowed == 1) {
c_carry1 = 1;
} else {
c_carry1 = 0;
}
answer = @addWithOverflow(g_plus_j, k);
const g_plus_j_plus_k = answer[0];
overflowed = answer[1];
var c_carry2: u128 = undefined;
if (overflowed == 1) {
c_carry2 = 1;
} else {
c_carry2 = 0;
}
answer = @addWithOverflow(g_plus_j_plus_k, b_carry1);
const c_without_bcarry2 = answer[0];
overflowed = answer[1];
var c_carry3: u128 = undefined;
if (overflowed == 1) {
c_carry3 = 1;
} else {
c_carry3 = 0;
}
answer = @addWithOverflow(c_without_bcarry2, b_carry2);
const c = answer[0];
overflowed = answer[1];
var c_carry4: u128 = undefined;
if (overflowed == 1) {
c_carry4 = 1;
} else {
c_carry4 = 0;
}
// d = carry + l
answer = @addWithOverflow(l, c_carry1);
overflowed = answer[1];
answer = @addWithOverflow(answer[0], c_carry2);
overflowed = overflowed | answer[1];
answer = @addWithOverflow(answer[0], c_carry3);
overflowed = overflowed | answer[1];
answer = @addWithOverflow(answer[0], c_carry4);
overflowed = overflowed | answer[1];
const d = answer[0];
if (overflowed == 1) {
roc_panic("Decimal multiplication overflow!", 0);
}
// Final 512bit value is d, c, b, a
// need to left shift 321 times
// 315 - 256 is 59. So left shift d, c 59 times.
return @as(i128, @intCast(c >> 59 | (d << (128 - 59))));
}
// Multiply two 128-bit ints and divide the result by 10^DECIMAL_PLACES
//
// Adapted from https://github.com/nlordell/ethnum-rs/blob/c9ed57e131bffde7bcc8274f376e5becf62ef9ac/src/intrinsics/native/divmod.rs
// Copyright (c) 2020 Nicholas Rodrigues Lordello
// Licensed under the Apache License version 2.0
//
// When translating this to Zig, we often have to use math.shr/shl instead of >>/<<
// This is because casting to the right types for Zig can be kind of tricky.
// See https://github.com/ziglang/zig/issues/7605
fn div_u256_by_u128(numer: U256, denom: u128) U256 {
const N_UDWORD_BITS: u8 = 128;
const N_UTWORD_BITS: u9 = 256;
var q: U256 = undefined;
var r: U256 = undefined;
var sr: u8 = undefined;
// special case
if (numer.hi == 0) {
// 0 X
// ---
// 0 X
return .{
.hi = 0,
.lo = numer.lo / denom,
};
}
// numer.hi != 0
if (denom == 0) {
// K X
// ---
// 0 0
return .{
.hi = 0,
.lo = numer.hi / denom,
};
} else {
// K X
// ---
// 0 K
// NOTE: Modified from `if (d.low() & (d.low() - 1)) == 0`.
if (math.isPowerOfTwo(denom)) {
// if d is a power of 2
if (denom == 1) {
return numer;
}
sr = @ctz(denom);
return .{
.hi = math.shr(u128, numer.hi, sr),
.lo = math.shl(u128, numer.hi, N_UDWORD_BITS - sr) | math.shr(u128, numer.lo, sr),
};
}
// K X
// ---
// 0 K
var denom_leading_zeros = @clz(denom);
var numer_hi_leading_zeros = @clz(numer.hi);
sr = 1 + N_UDWORD_BITS + denom_leading_zeros - numer_hi_leading_zeros;
// 2 <= sr <= N_UTWORD_BITS - 1
// q.all = n.all << (N_UTWORD_BITS - sr);
// r.all = n.all >> sr;
// #[allow(clippy::comparison_chain)]
if (sr == N_UDWORD_BITS) {
q = .{
.hi = numer.lo,
.lo = 0,
};
r = .{
.hi = 0,
.lo = numer.hi,
};
} else if (sr < N_UDWORD_BITS) {
// 2 <= sr <= N_UDWORD_BITS - 1
q = .{
.hi = math.shl(u128, numer.lo, N_UDWORD_BITS - sr),
.lo = 0,
};
r = .{
.hi = math.shr(u128, numer.hi, sr),
.lo = math.shl(u128, numer.hi, N_UDWORD_BITS - sr) | math.shr(u128, numer.lo, sr),
};
} else {
// N_UDWORD_BITS + 1 <= sr <= N_UTWORD_BITS - 1
q = .{
.hi = math.shl(u128, numer.hi, N_UTWORD_BITS - sr) | math.shr(u128, numer.lo, sr - N_UDWORD_BITS),
.lo = math.shl(u128, numer.lo, N_UTWORD_BITS - sr),
};
r = .{
.hi = 0,
.lo = math.shr(u128, numer.hi, sr - N_UDWORD_BITS),
};
}
}
// Not a special case
// q and r are initialized with:
// q.all = n.all << (N_UTWORD_BITS - sr);
// r.all = n.all >> sr;
// 1 <= sr <= N_UTWORD_BITS - 1
var carry: u128 = 0;
while (sr > 0) {
// r:q = ((r:q) << 1) | carry
r.hi = (r.hi << 1) | (r.lo >> (N_UDWORD_BITS - 1));
r.lo = (r.lo << 1) | (q.hi >> (N_UDWORD_BITS - 1));
q.hi = (q.hi << 1) | (q.lo >> (N_UDWORD_BITS - 1));
q.lo = (q.lo << 1) | carry;
// carry = 0;
// if (r.all >= d.all)
// {
// r.all -= d.all;
// carry = 1;
// }
// NOTE: Modified from `(d - r - 1) >> (N_UTWORD_BITS - 1)` to be an
// **arithmetic** shift.
var answer = @subWithOverflow(denom, r.lo);
var lo = answer[0];
var lo_overflowed = answer[1];
var hi = 0 -% @as(u128, @intCast(@as(u1, @bitCast(lo_overflowed)))) -% r.hi;
answer = @subWithOverflow(lo, 1);
lo = answer[0];
lo_overflowed = answer[1];
hi = hi -% @as(u128, @intCast(@as(u1, @bitCast(lo_overflowed))));
// NOTE: this U256 was originally created by:
//
// ((hi as i128) >> 127).as_u256()
//
// As an implementation of `as_u256`, we wrap a negative value around to the maximum value of U256.
var s_u128 = math.shr(u128, hi, 127);
var s_hi: u128 = undefined;
var s_lo: u128 = undefined;
if (s_u128 == 1) {
s_hi = math.maxInt(u128);
s_lo = math.maxInt(u128);
} else {
s_hi = 0;
s_lo = 0;
}
var s = .{
.hi = s_hi,
.lo = s_lo,
};
carry = s.lo & 1;
// var (lo, carry) = r.lo.overflowing_sub(denom & s.lo);
answer = @subWithOverflow(r.lo, (denom & s.lo));
lo = answer[0];
lo_overflowed = answer[1];
hi = r.hi -% @as(u128, @intCast(@as(u1, @bitCast(lo_overflowed))));
r = .{ .hi = hi, .lo = lo };
sr -= 1;
}
var hi = (q.hi << 1) | (q.lo >> (127));
var lo = (q.lo << 1) | carry;
return .{ .hi = hi, .lo = lo };
}
const testing = std.testing;
const expectEqual = testing.expectEqual;
const expectError = testing.expectError;
const expectEqualSlices = testing.expectEqualSlices;
const expect = testing.expect;
test "fromU64" {
var dec = RocDec.fromU64(25);
try expectEqual(RocDec{ .num = 25000000000000000000 }, dec);
}
test "fromF64" {
var dec = RocDec.fromF64(25.5);
try expectEqual(RocDec{ .num = 25500000000000000000 }, dec.?);
}
test "fromF64 overflow" {
var dec = RocDec.fromF64(1e308);
try expectEqual(dec, null);
}
test "fromStr: empty" {
var roc_str = RocStr.init("", 0);
var dec = RocDec.fromStr(roc_str);
try expectEqual(dec, null);
}
test "fromStr: 0" {
var roc_str = RocStr.init("0", 1);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec{ .num = 0 }, dec.?);
}
test "fromStr: 1" {
var roc_str = RocStr.init("1", 1);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec.one_point_zero, dec.?);
}
test "fromStr: 123.45" {
var roc_str = RocStr.init("123.45", 6);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec{ .num = 123450000000000000000 }, dec.?);
}
test "fromStr: .45" {
var roc_str = RocStr.init(".45", 3);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec{ .num = 450000000000000000 }, dec.?);
}
test "fromStr: 0.45" {
var roc_str = RocStr.init("0.45", 4);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec{ .num = 450000000000000000 }, dec.?);
}
test "fromStr: 123" {
var roc_str = RocStr.init("123", 3);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec{ .num = 123000000000000000000 }, dec.?);
}
test "fromStr: -.45" {
var roc_str = RocStr.init("-.45", 4);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec{ .num = -450000000000000000 }, dec.?);
}
test "fromStr: -0.45" {
var roc_str = RocStr.init("-0.45", 5);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec{ .num = -450000000000000000 }, dec.?);
}
test "fromStr: -123" {
var roc_str = RocStr.init("-123", 4);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec{ .num = -123000000000000000000 }, dec.?);
}
test "fromStr: -123.45" {
var roc_str = RocStr.init("-123.45", 7);
var dec = RocDec.fromStr(roc_str);
try expectEqual(RocDec{ .num = -123450000000000000000 }, dec.?);
}
test "fromStr: abc" {
var roc_str = RocStr.init("abc", 3);
var dec = RocDec.fromStr(roc_str);
try expectEqual(dec, null);
}
test "fromStr: 123.abc" {