finitely 0.1.0

Arithemtic over finite polynomial rings
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
#![doc = include_str!("../readme.md")]
#![no_std]

use core::{
    fmt::{Debug, Display, Write},
    marker::PhantomData,
    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
};

use packet::Packet;

mod numerics;
mod packet;

/// A trait to configure the modulus and overflow behaviour of
/// an instance of a [`FinitePoly`].
///
/// Typically a user of this library will rarely interact with
/// this trait -- an impl for it is automatically generated by
/// the [`make_ring`] macro.
pub trait PolySettings<const SIZE: usize, const LOG2: usize>: Sized {
    /// The modulus of the base ring -- i.e. the `n` in `Z/nZ`
    ///
    /// Arithmetic in a `FinitePoly` will only ever be done in
    /// this modulus.
    const MODULO: u64;

    /// The degree of `x` which is equivalent to [`Self::OVERFLOW`].
    ///
    /// In mathematical terms, if we are building
    /// `(Z/nZ)[x]/(p(x))`, then this is `deg(p)`.
    const DEGREE: usize;

    /// This is equivalent to `x` raised to the power of
    /// [`Self::DEGREE`].
    ///
    /// In mathematical terms, if we are building
    /// `(Z/nZ)[x]/(p(x))` then:
    /// ```text
    /// p(x) = x^DEGREE - OVERFLOW(x)
    /// ```
    /// So that:
    /// ```text
    /// p(x) = 0 ==> x^DEGREE = OVERFLOW(x)
    /// ```
    const OVERFLOW: FinitePoly<Self, SIZE, LOG2>;
}

/// An element of a Quotient Ring Of a Polynomial Ring
///
/// This structure implements arithmetic in the ring:
/// `(Z/nZ)[x]/(p(x))`. Precisely what this means is covered
/// in the crate docs, written in plain and accessible language.
///
/// Generic Parameters:
/// - `T` is a type which controls the Modulus of coefficients
///   and Overflow behaviour on `x`.
/// - `SIZE` is the number of `u64`s required to represent the
///   first bit of every coefficient in any polynomial. This
///   value should be `T::DEGREE.div_ceil(64)`.
/// - `LOG2` is the number of bits required to represent any
///   coefficient in the polynomial. For example, if the modulus
///   is 5, `LOG2` is 3, since 4 is a possible coefficient and
///   is represented as 100 in binary.
///
/// Example usage:
/// ```
/// use finitely::make_ring;
/// make_ring! {
///     F9 = { Z % 3, x^2 = [2] };
/// }    
///
/// let value = F9::from_coeffs(&[1, 2]);
/// assert_eq!(format!("{value}"), String::from("x + 2"));
///
/// // (x + 2) + (x + 2) = 2x + 4 = 2x + 1 (mod 3).
/// assert_eq!(value + value, F9::from_coeffs(&[2, 1]));
///
/// // (x + 2) * (x + 2) = x^2 + 4x + 4 = x^2 + x + 1 (mod 3).
/// // Since x^2 = 2, we get x + 1 + 2 = x (mod 3).
/// assert_eq!(value * value, F9::from_coeffs(&[1, 0]));
/// ```
pub struct FinitePoly<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> {
    pub(crate) internal: [Packet<LOG2>; SIZE],
    pub(crate) _phantom: PhantomData<T>,
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Eq
    for FinitePoly<T, SIZE, LOG2>
{
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> PartialEq
    for FinitePoly<T, SIZE, LOG2>
{
    fn eq(&self, other: &Self) -> bool {
        Self::eq(*self, *other)
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> PartialEq<u64>
    for FinitePoly<T, SIZE, LOG2>
{
    fn eq(&self, other: &u64) -> bool {
        self.degree() == 0 && (self.get_nth_coeff(0) % T::MODULO) == *other
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Copy
    for FinitePoly<T, SIZE, LOG2>
{
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Clone
    for FinitePoly<T, SIZE, LOG2>
{
    fn clone(&self) -> Self {
        *self
    }
}

/// Throughout the examples in this implementation block,
/// we will be using the example ring:
/// ```
/// use finitely::make_ring;
/// make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
/// ```
impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> FinitePoly<T, SIZE, LOG2> {
    /// The zero polynomial.
    pub const ZERO: Self = Self {
        internal: [Packet::<LOG2>::new(); SIZE],
        _phantom: PhantomData,
    };

    const FALSE_ZERO: Packet<LOG2> = Packet::splat(T::MODULO as u64 % (1u64 << LOG2));
    const OVERFLOW: Packet<LOG2> = Packet::splat((1u64 << LOG2) % T::MODULO as u64);
    const DEGREE_OVERFLOW_BIT: usize = T::DEGREE - 1 - Self::DEGREE_OVERFLOW_U64 * 64;
    const DEGREE_OVERFLOW_U64: usize = (T::DEGREE - 1) / 64;
    const FILTER_EXCESS_BITS: u64 =
        (1 << Self::DEGREE_OVERFLOW_BIT) | ((1 << Self::DEGREE_OVERFLOW_BIT) - 1);

    /// The one polynomial.
    pub const ONE: Self = Self::from_int(1);

    /// Creates a polynomial where every coefficient
    /// is `value`. I.e. `value + value x + value x^2 + ...`.
    ///
    /// This runs in *`O(LOG2 * SIZE)`*
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// ```
    pub const fn splat(value: u64) -> Self {
        Self {
            internal: [Packet::splat(value); SIZE],
            _phantom: PhantomData,
        }
    }

    /// Is equivalent to representing `value` as a degree-0
    /// polynomial. Mathematically speaking, this is equivalent
    /// to adding 1 a total of `value` times.
    ///
    /// Note that this is _not_ implemented by adding 1 a total
    /// of `value` times.
    ///
    /// This runs in *`O(LOG2 * SIZE)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(F25::from_int(2), F25::ONE + F25::ONE);
    /// assert_eq!(F25::from_int(5), F25::ZERO);
    /// ```
    pub const fn from_int(value: u64) -> Self {
        let mut me = Self::ZERO;
        me.internal[0] = Packet::from_int(value % T::MODULO);

        me
    }

    /// A useful function when debugging the internals of this
    /// library. Unlikely to be useful to a user, if all methods
    /// on this type have been implemented correctly.
    ///
    /// Removes "false zeros" -- coefficients which are equal
    /// to our modulus and are not zero as a result of arithmetic.
    ///
    /// For example, if we are working modulo 5, then we need
    /// 3 bits. If you ask `finite` to compute `1 + 1 + 1 + 1 + 1`
    /// modulo 5, then it will represent the coefficient internally
    /// as `101`, as reduction modulo the modulus is done
    /// as lazily as possible in the space given. When acquiring
    /// the coefficient through `get_nth_coeff`, it will
    /// automatically be reduced modulo the modulus.
    const fn remove_false_zeros(mut self) -> Self {
        let mut done = 0;

        while done < SIZE {
            let temp = self.internal[done];

            // xor detects any differences with a false zero.
            // or reduction accumulates any differences into a single u64.
            // where there was a difference is now a 1, where there was
            // not (i.e. it is a false zero) is now a 0.
            let zeros_detect = temp.xor(Self::FALSE_ZERO).or_reduce();

            // and-ing will remove elements where zeros_detect is 0
            // which are places where we have a false zero.
            self.internal[done] = temp.and_u64(zeros_detect);

            done += 1;
        }

        self
    }

    /// Computes the degree of this polynomial.
    ///
    /// Mathematically speaking, it computes the smallest degree
    /// of any representative of the equivalence class after reducing
    /// modulo `p`.
    ///
    /// This runs in *`O(LOG2 * SIZE)`*
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(F25::ZERO.degree(), 0);
    /// assert_eq!(F25::ONE.degree(), 0);
    /// assert_eq!(F25::from_coeffs(&[1, 2]).degree(), 1);
    /// ```
    pub const fn degree(mut self) -> usize {
        self = self.remove_false_zeros();

        let mut done = 1;

        while done <= SIZE {
            let mut to_detect = self.internal[SIZE - done];

            if done == SIZE {
                to_detect = to_detect.and_u64(Self::FILTER_EXCESS_BITS);
            }

            let leading = to_detect.leading_zeros();
            let first_one_idx = 64 - leading;

            if first_one_idx != 0 {
                let degree_total = first_one_idx + (SIZE - done) as u64 * 64;

                return degree_total as usize - 1;
            }

            done += 1;
        }

        0
    }

    /// Computes whether `self` is equivalent to `other`.
    ///
    /// This runs in *`O(?)`*
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// let value_1 = F25::from_coeffs(&[2, 1]);
    /// let value_2 = F25::from_coeffs(&[1, 0]);
    /// let product = F25::from_coeffs(&[3, 1]);
    /// assert!((value_1 * value_2).eq(product));
    /// ```
    pub const fn eq(self, other: Self) -> bool {
        let diff = self.sub(other);

        diff.is_zero()
    }

    /// Computes whether `self` is the zero polynomial.
    ///
    /// This runs in *`O(LOG2 * SIZE)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert!(F25::ZERO.is_zero());
    /// assert!(!F25::ONE.is_zero());
    /// let fake_5 = F25::ONE + F25::ONE + F25::ONE + F25::ONE + F25::ONE;
    /// assert!(fake_5.is_zero());
    /// ```
    pub const fn is_zero(mut self) -> bool {
        self = self.remove_false_zeros();
        let mut done = 0;

        while done < SIZE - 1 {
            if self.internal[done].or_reduce() != 0 {
                return false;
            }

            done += 1;
        }

        if self.internal[SIZE - 1].or_reduce() << (64 - T::DEGREE % 64) != 0 {
            return false;
        }

        true
    }

    /// Runs in at most *`O(LOG2^2)`*.
    ///
    /// I need to verify that is the lowest upper bound.
    const fn add_within(n: Packet<LOG2>, m: Packet<LOG2>) -> Packet<LOG2> {
        let mut result = n;
        let mut carry = m;
        let mut overflow_carry = Packet::new();

        while !carry.is_zero() || !overflow_carry.is_zero() {
            let add = result.xor(carry).xor(overflow_carry);
            // new_carry = (result & carry) | (result & overflow_carry) | (carry & overflow_carry).
            // That simplifies to this:
            let new_carry = result
                .and(carry.or(overflow_carry))
                .or(carry.and(overflow_carry));

            let (bumped, new_carry) = new_carry.left_shift_horizontal();

            let new_overflow = Self::OVERFLOW.and_u64(bumped);

            result = add;
            carry = new_carry;
            overflow_carry = new_overflow;
        }

        result
    }

    /// Computes the sum of `self` with `other`.
    ///
    /// Note: this type implements [`std::ops::Add`].
    ///
    /// This adds coefficient-wise.
    ///
    /// This runs in *`O(LOG2^2 * SIZE)`*
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(F25::ONE.add(F25::ONE), F25::from_int(2));
    /// assert_eq!(F25::from_int(4).add(F25::ONE), 0);
    /// ```
    pub const fn add(mut self, other: Self) -> Self {
        let mut i = 0;
        while i < SIZE {
            self.internal[i] = Self::add_within(self.internal[i], other.internal[i]);
            i += 1;
        }

        self
    }

    /// Essentially the same thing as add_within.
    /// This has the same time complexity.
    const fn sub_within(n: Packet<LOG2>, m: Packet<LOG2>) -> Packet<LOG2> {
        let mut result = n;
        let mut carry = m;
        let mut underflow_carry = Packet::new();

        while !carry.is_zero() || !underflow_carry.is_zero() {
            let sub = result.xor(carry).xor(underflow_carry);

            let new_carry = result
                .not()
                .and(carry.or(underflow_carry))
                .or(carry.and(underflow_carry));

            let (bumped, new_carry) = new_carry.left_shift_horizontal();

            let new_underflow = Self::OVERFLOW.and_u64(bumped);

            result = sub;
            carry = new_carry;
            underflow_carry = new_underflow;
        }

        result
    }

    /// Computes the difference between `self` and `other`.
    ///
    /// Note: this type implements [`std::ops::Sub`].
    ///
    /// This subtracts component-wise.
    ///
    /// This runs in *`O(LOG2^2 * SIZE)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(F25::from_int(3) - 1, 2);
    /// assert_eq!(F25::ZERO - F25::ONE, 4);
    /// ```
    pub const fn sub(mut self, other: Self) -> Self {
        let mut i = 0;
        while i < SIZE {
            self.internal[i] = Self::sub_within(self.internal[i], other.internal[i]);
            i += 1;
        }

        self
    }

    /// Essentially computes `0 - n`.
    /// This runs in O(LOG2^2) at worst.
    const fn neg_within(n: Packet<LOG2>) -> Packet<LOG2> {
        let mut result = n;
        let mut carry = n;
        let bumped;

        (bumped, carry) = carry.left_shift_horizontal();

        let mut underflow_carry = Self::OVERFLOW.and_u64(bumped);

        while !carry.is_zero() || !underflow_carry.is_zero() {
            let sub = result.xor(carry).xor(underflow_carry);

            let new_carry = result
                .not()
                .and(carry.or(underflow_carry))
                .or(carry.and(underflow_carry));

            let (bumped, new_carry) = new_carry.left_shift_horizontal();

            let new_underflow = Self::OVERFLOW.and_u64(bumped);

            result = sub;
            carry = new_carry;
            underflow_carry = new_underflow;
        }

        result
    }

    /// Computes the negation modulo the modulus of the polynomial.
    ///
    /// Note: this type implements [`std::ops::Neg`].
    ///
    /// Since all coefficients are positive, a coefficient `c` is
    /// transformed into `MODULO - c`, which is equivalent to `-c`
    /// modulo `MODULO`.
    ///
    /// This runs in *`O(LOG2^2 * SIZE)`*
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(F25::from_coeffs(&[2, 3]).neg(), F25::from_coeffs(&[3, 2]));
    /// ```
    pub const fn neg(mut self) -> Self {
        let mut i = 0;

        while i < SIZE {
            self.internal[i] = Self::neg_within(self.internal[i]);

            i += 1;
        }

        self
    }

    /// Computes `self` times a constant coefficient.
    ///
    /// Note: this type implements [`std::ops::Mul`].
    ///
    /// This is faster than multiplying by `FinitePoly::make_int(by)`
    /// since this can take advantage that the degree of the polynomial
    /// will not change (unless you set `by = 0`, but that doesn't change
    /// anything).
    ///
    /// This runs in *`O(LOG2^3 * SIZE)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(
    ///     F25::from_coeffs(&[2, 4]).mul_modulo(2),
    ///     F25::from_coeffs(&[4, 3])
    /// );
    /// ```
    pub const fn mul_modulo(self, by: u64) -> Self {
        let mut by = by % T::MODULO as u64;

        let mut acc = Self::ZERO;
        let mut power_2 = self;

        while by != 0 {
            if by & 1 == 1 {
                acc = acc.add(power_2);
            }

            by >>= 1;
            power_2 = power_2.add(power_2);
        }

        acc
    }

    /// Computes `self` times `x` and reduces.
    ///
    /// This runs in *`O(LOG2^3 * SIZE)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(F25::ONE.mul_x(), F25::from_coeffs(&[1, 0]));
    /// assert_eq!(F25::ONE.mul_x().mul_x(), F25::from_coeffs(&[1, 3]));
    /// assert_eq!(F25::from_coeffs(&[4, 2]).mul_x(), F25::from_coeffs(&[1, 2]));
    /// ```
    pub const fn mul_x(mut self) -> Self {
        let extracted_overflow =
            self.internal[Self::DEGREE_OVERFLOW_U64].extract_coefficient(Self::DEGREE_OVERFLOW_BIT);

        let overflow = T::OVERFLOW.mul_modulo(extracted_overflow);

        self = self.unchecked_mulx(1);

        self.add(overflow)
    }

    /// Multiplies `self` by `x` without doing overflow.
    ///
    /// This runs in *`O(LOG2 * SIZE)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(F25::ONE.unchecked_mulx(2), 0);
    /// ```
    pub const fn unchecked_mulx(mut self, power: usize) -> Self {
        if power == 0 {
            return self;
        }
        let mut done = 0;

        let mut carry = Packet::new();

        while done != SIZE {
            let new_carry = self.internal[done].rsh(64 - power);
            self.internal[done] = self.internal[done].lsh(power).or(carry);

            carry = new_carry;
            done += 1;
        }

        self
    }

    /// Acquires the nth coefficient of the polynomial.
    ///
    /// This runs in *`O(LOG2)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// let value = F25::from_coeffs(&[2, 3]);
    /// assert_eq!(value.get_nth_coeff(0), 3);
    /// assert_eq!(value.get_nth_coeff(1), 2);
    /// ```
    pub const fn get_nth_coeff(self, coeff: usize) -> u64 {
        if coeff >= T::DEGREE {
            return 0;
        }

        let u64_idx = coeff / 64;
        let within_u64_idx = coeff % 64;

        self.internal[u64_idx].extract_coefficient(within_u64_idx)
    }

    /// Sets a coefficient in the polynomial.
    ///
    /// This runs in *`O(LOG2)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// let value = F25::ZERO.set_coeff(0, 3).set_coeff(1, 2);
    /// assert_eq!(value.get_nth_coeff(0), 3);
    /// assert_eq!(value.get_nth_coeff(1), 2);
    /// ```
    #[must_use = "Since this method is const and cannot take &mut, you must assign it to a new variable."]
    pub const fn set_coeff(mut self, idx: usize, coeff: u64) -> Self {
        if idx >= T::DEGREE {
            return self;
        }

        let u64_idx = idx / 64;
        let within_u64_idx = idx % 64;

        self.internal[u64_idx] = self.internal[u64_idx].set_coeff(within_u64_idx, coeff);

        self
    }

    /// Computes the multiplication of `self` with `other`, reducing
    /// modulo `p(x)` (the overflow is applied), and of course reducing
    /// modulo `MODULO`.
    ///
    /// This runs in *`O(SIZE^2 * LOG2^3)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// let value_1 = F25::from_coeffs(&[1, 4]);
    /// let value_2 = F25::from_coeffs(&[2, 3]);
    /// assert_eq!(value_1 * value_2, value_2 * value_1);
    /// assert_eq!(value_1 * value_2, F25::from_coeffs(&[3, 3]));
    /// ```
    pub const fn mul(self, other: Self) -> Self {
        let mut acc = Self::ZERO;
        let mut power_x = self;

        let mut powers_done = 0;

        while powers_done < T::DEGREE {
            let coeff = other.get_nth_coeff(powers_done);

            if coeff != 0 {
                if coeff == 1 {
                    acc = acc.add(power_x);
                } else {
                    acc = acc.add(power_x.mul_modulo(coeff));
                }
            }

            power_x = power_x.mul_x();

            powers_done += 1;
        }

        acc
    }

    /// If possible, returns self/other, self - other * self/other.
    ///
    /// This is sometimes possible if `MODULO` is not prime.
    ///
    /// This runs in *`O(SIZE^2 * LOG2^3)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// let numerator = F25::from_coeffs(&[1, 2]);
    /// let denominator = F25::from_coeffs(&[1, 4]);
    ///
    /// let (division, remainder) = numerator.divide_remainder(denominator).unwrap();
    /// assert_eq!(division, 1);  
    /// assert_eq!(remainder, 3);  
    /// // x + 2 == 1 * (x + 4) + 3
    /// ```
    pub const fn divide_remainder(self, other: Self) -> Option<(Self, Self)> {
        let other_degree = other.degree();

        let mut quotient = Self::ZERO;
        let mut remainder = self;

        let mut remainder_degree = remainder.degree();

        while other_degree <= remainder_degree && !remainder.is_zero() {
            let difference_in_degree = remainder_degree - other_degree;
            // println!("Quotient: {quotient}, Remainder: {remainder}, diff: {difference_in_degree}, self: {self}, other: {other}");
            let my_coeff = remainder.get_nth_coeff(remainder_degree);
            let other_coeff = other.get_nth_coeff(other_degree);

            let Some(inverse) = numerics::divide_modulo(T::MODULO, my_coeff, other_coeff) else {
                return None;
            };

            let division = Self::from_int(inverse).unchecked_mulx(difference_in_degree);
            quotient = quotient.add(division);

            let product = other
                .mul_modulo(inverse)
                .unchecked_mulx(difference_in_degree);

            remainder = remainder.sub(product);

            remainder_degree = remainder.degree();
        }

        Some((quotient, remainder))
    }

    /// Computes the same thing as [`Self::divide_remainder`], however
    /// the parameters are `(p(x), self)`. Since you cannot represent
    /// `p(x)` using this ring (it will reduce to `OVERFLOW`), this
    /// specialized function is necessary.
    ///
    /// This runs in *`O(SIZE^2 * LOG2^3)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// // Our quotient poly is x^2 + 4x + 2.
    /// let denominator = F25::from_coeffs(&[1, 3]);     // x + 3
    ///
    /// let (quotient, remainder) = denominator.divide_quotient_poly_by_self().unwrap();
    /// assert_eq!(quotient, F25::from_coeffs(&[1, 1])); // x + 1
    /// assert_eq!(remainder, F25::from_coeffs(&[4]));   // 4
    ///
    /// // See: (x + 1)(x + 3) + 4 == x^2 + 4x + 2.
    /// ```
    pub const fn divide_quotient_poly_by_self(self) -> Option<(Self, Self)> {
        let my_degree = T::DEGREE;
        let other_degree = self.degree();

        let difference_in_degree = my_degree - other_degree;
        let other_coeff = self.get_nth_coeff(other_degree);

        let Some(inverse) = numerics::invert_in_modulo(T::MODULO, other_coeff) else {
            return None;
        };

        let division = if difference_in_degree == T::DEGREE {
            return Some((Self::ZERO.sub(T::OVERFLOW).mul_modulo(inverse), Self::ZERO));
        } else {
            Self::from_int(inverse).unchecked_mulx(difference_in_degree)
        };

        let to_remove = self.set_coeff(other_degree, 0);

        let product = to_remove.mul(division);

        let remainder = Self::ZERO.sub(T::OVERFLOW).sub(product);

        let Some((new_division, remainder)) = remainder.divide_remainder(self) else {
            return None;
        };

        Some((division.add(new_division), remainder))
    }

    /// Tries to find a multiplicative inverse in the ring.
    ///
    /// That is, it will (try to) find an element `x` such
    /// that `self.mul(x) == Self::ONE`.
    ///
    /// This will always succeed if `self` is a nonzero element
    /// of `Self` and `Self` is a field. That is, if `MODULO` is
    /// a prime number, and `p(x) = x^DEGREE - OVERFLOW(x)` is
    /// irreducible modulo `MODULO`.
    ///
    /// If you are not over a field, this is only guaranteed to work
    /// for constants, and the results for non-constant members of
    /// the a non-field is unspecified.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(F25::from_int(3).invert().unwrap(), 2);
    /// assert_eq!(F25::ONE.mul_x().invert().unwrap(), F25::from_coeffs(&[2, 3]));
    /// // Notice: x(2x + 3) = 1.
    /// ```
    pub const fn invert(self) -> Option<Self> {
        let mut t = Self::ZERO;
        let mut r;
        let mut new_t = Self::ONE;
        let mut new_r = self;

        // `r` should actually be x^degree - T::OVERFLOW = p(x).
        // However, we cannot represent that number, so instead
        // we use the special case function to compute p(x)/self.

        let Some((quotient, remainder)) = self.divide_quotient_poly_by_self() else {
            return None;
        };

        (r, new_r) = (new_r, remainder);
        (t, new_t) = (new_t, t.sub(quotient.mul(new_t)));

        while !new_r.is_zero() {
            let Some((quotient, remainder)) = Self::divide_remainder(r, new_r) else {
                return None;
            };

            (r, new_r) = (new_r, remainder);
            (t, new_t) = (new_t, t.sub(quotient.mul(new_t)));
        }

        if r.degree() > 0 {
            return None;
        }

        let r_as_integer = r.get_nth_coeff(0);
        let Some(inverse) = numerics::invert_in_modulo(T::MODULO, r_as_integer) else {
            return None;
        };

        Some(t.mul_modulo(inverse))
    }

    /// Constructs a polynomial given the specified coefficients.
    ///
    /// This runs in *`O(SIZE * LOG2)`*.
    ///
    /// Example usage:
    /// ```
    /// # use finitely::make_ring;
    /// # make_ring! { F25 = { Z % 5, x^2 = [1, 3] }; }
    /// assert_eq!(F25::from_coeffs(&[2, 1]), F25::from_coeffs(&[7, 6]));
    /// ```
    pub const fn from_coeffs(mut coeffs: &[u64]) -> Self {
        let to_do = if coeffs.len() > T::DEGREE {
            T::DEGREE
        } else {
            coeffs.len()
        };

        (_, coeffs) = coeffs.split_at(coeffs.len() - to_do);

        let last_block_length = coeffs.len() % 64;

        let (last_block, mut coeffs) = coeffs.split_at(last_block_length);

        let last_block = Packet::from_coeffs(last_block);

        let mut acc = Self::ZERO;

        let mut insertion_idx = 0;

        while coeffs.len() != 0 {
            let (rest, last) = coeffs.split_at(coeffs.len() - 64);

            coeffs = rest;

            acc.internal[insertion_idx] = Packet::from_coeffs(last);

            insertion_idx += 1;
        }

        acc.internal[insertion_idx] = last_block;

        acc
    }

    /// Writes a debug version of `self` to `w`.
    pub fn format_full(self, mut w: impl Write) -> core::fmt::Result {
        for i in (1..T::DEGREE).rev() {
            let coeff = self.get_nth_coeff(i) % T::MODULO as u64;

            write!(w, "{coeff}x^{i} + ")?;
        }

        write!(w, "{}", self.get_nth_coeff(0) % T::MODULO as u64)
    }

    /// Writes a display version of `self` to `w`.
    pub fn format_filtered(self, mut w: impl Write) -> core::fmt::Result {
        if self == Self::ZERO {
            return write!(w, "0");
        }

        let mut seen_first = false;

        for i in (1..T::DEGREE).rev() {
            let coeff = self.get_nth_coeff(i) % T::MODULO as u64;

            if coeff != 0 {
                if seen_first {
                    write!(w, " + ")?;
                } else {
                    seen_first = true;
                }

                if coeff != 1 {
                    write!(w, "{coeff}")?;
                }

                write!(w, "x")?;

                if i != 1 {
                    write!(w, "^{i}")?;
                }
            }
        }

        let zeroth = self.get_nth_coeff(0) % T::MODULO as u64;

        if zeroth != 0 {
            if seen_first {
                write!(w, " + {zeroth}")?;
            } else {
                write!(w, "{zeroth}")?;
            }
        }

        Ok(())
    }

    /// Returns an iterator over all members of the field.
    pub fn iter() -> FinitePolyIterator<T, SIZE, LOG2> {
        FinitePolyIterator {
            coeffs: Some(Self::ZERO),
            _item: PhantomData,
        }
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Debug
    for FinitePoly<T, SIZE, LOG2>
{
    fn fmt(&self, mut f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.format_full(&mut f)?;
        write!(f, " [")?;
        for val in self.internal[1..].iter().rev() {
            write!(f, "{val}, ")?;
        }
        write!(f, "{}", self.internal[0])?;
        write!(f, "]")
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Display
    for FinitePoly<T, SIZE, LOG2>
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.format_filtered(f)
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Mul<Self>
    for FinitePoly<T, SIZE, LOG2>
{
    type Output = Self;

    fn mul(self, rhs: Self) -> Self {
        self.mul(rhs)
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Mul<u64>
    for FinitePoly<T, SIZE, LOG2>
{
    type Output = Self;

    fn mul(self, rhs: u64) -> Self {
        self.mul_modulo(rhs)
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Div<Self>
    for FinitePoly<T, SIZE, LOG2>
{
    type Output = Self;

    fn div(self, rhs: Self) -> Self {
        self * rhs.invert().unwrap()
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Div<u64>
    for FinitePoly<T, SIZE, LOG2>
{
    type Output = Self;

    fn div(self, rhs: u64) -> Self {
        self * Self::from_int(rhs).invert().unwrap()
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Add<Self>
    for FinitePoly<T, SIZE, LOG2>
{
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        self.add(rhs)
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Add<u64>
    for FinitePoly<T, SIZE, LOG2>
{
    type Output = Self;

    fn add(self, rhs: u64) -> Self {
        self.add(Self::from_int(rhs))
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Neg
    for FinitePoly<T, SIZE, LOG2>
{
    type Output = Self;

    fn neg(self) -> Self {
        self.neg()
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Sub<Self>
    for FinitePoly<T, SIZE, LOG2>
{
    type Output = Self;

    fn sub(self, rhs: Self) -> Self {
        self.sub(rhs)
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Sub<u64>
    for FinitePoly<T, SIZE, LOG2>
{
    type Output = Self;

    fn sub(self, rhs: u64) -> Self {
        self.sub(Self::from_int(rhs))
    }
}

impl<T: PolySettings<SIZE, LOG2>, U, const SIZE: usize, const LOG2: usize> AddAssign<U>
    for FinitePoly<T, SIZE, LOG2>
where
    Self: Add<U, Output = Self>,
{
    fn add_assign(&mut self, rhs: U) {
        *self = *self + rhs;
    }
}

impl<T: PolySettings<SIZE, LOG2>, U, const SIZE: usize, const LOG2: usize> SubAssign<U>
    for FinitePoly<T, SIZE, LOG2>
where
    Self: Sub<U, Output = Self>,
{
    fn sub_assign(&mut self, rhs: U) {
        *self = *self - rhs;
    }
}

impl<T: PolySettings<SIZE, LOG2>, U, const SIZE: usize, const LOG2: usize> MulAssign<U>
    for FinitePoly<T, SIZE, LOG2>
where
    Self: Mul<U, Output = Self>,
{
    fn mul_assign(&mut self, rhs: U) {
        *self = *self * rhs;
    }
}

impl<T: PolySettings<SIZE, LOG2>, U, const SIZE: usize, const LOG2: usize> DivAssign<U>
    for FinitePoly<T, SIZE, LOG2>
where
    Self: Div<U, Output = Self>,
{
    fn div_assign(&mut self, rhs: U) {
        *self = *self / rhs;
    }
}

/// Iterates over all of the elements of the finite ring.
///
/// Created by calling [`FinitePoly::iter`].
pub struct FinitePolyIterator<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> {
    coeffs: Option<FinitePoly<T, SIZE, LOG2>>,
    _item: PhantomData<FinitePoly<T, SIZE, LOG2>>,
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> Iterator
    for FinitePolyIterator<T, SIZE, LOG2>
{
    type Item = FinitePoly<T, SIZE, LOG2>;

    fn next(&mut self) -> Option<Self::Item> {
        let coeffs = self.coeffs?;
        let mut new_coeffs = coeffs;

        let mut is_zero = true;

        for i in 0..T::DEGREE {
            let elem = new_coeffs.get_nth_coeff(i);

            let mut new_val = elem + 1;

            let carry = new_val / T::MODULO as u64;
            new_val -= carry * T::MODULO as u64;

            new_coeffs = new_coeffs.set_coeff(i, new_val);

            is_zero &= new_val == 0;

            if carry == 0 {
                break;
            }
        }

        if is_zero {
            self.coeffs = None;
        } else {
            self.coeffs = Some(new_coeffs);
        }

        Some(coeffs)
    }
}

impl<T: PolySettings<SIZE, LOG2>, const SIZE: usize, const LOG2: usize> From<u64>
    for FinitePoly<T, SIZE, LOG2>
{
    fn from(value: u64) -> Self {
        Self::from_int(value)
    }
}

const fn log2(x: u64) -> usize {
    (64 - (x - 1).leading_zeros()) as _
}

/// Returns the number of `u64`-width packets to represent the
/// polynomials given by `T::DEGREE`.
pub const fn get_size<T: PolySettings<0, 0>>() -> usize {
    T::DEGREE.div_ceil(64)
}

/// Returns the number of bits required to represent coefficients
/// modulo `T::MODULO`.
pub const fn get_log2<T: PolySettings<0, 0>>() -> usize {
    log2(T::MODULO)
}

#[doc(hidden)]
#[macro_export]
#[allow(unused_macros)]
macro_rules! forward_const {
    (
        $view:vis, ($t:ty) :
        $(
            fn $name:ident($($param_name:ident $(* $idx:literal)? $(: $param_ty:ty)?),*) -> $ret_ty:ident$(<$generics:ident>)?;
        )*
    ) => {
        $(
            #[allow(dead_code)]
            $view const fn $name($($param_name $(: $param_ty)?),*) -> $ret_ty$(<$generics>)? {
                $crate::forward_const!(@result : ($ret_ty) : (<$t>::$name($($crate::forward_const!(@param: $param_name $(* $idx)?)),*)))
            }
        )*
    };

    (@param: $n:ident * $idx:literal) => {$n.0};
    (@param: $($t:tt)*) => {$($t)*};
    (@result: (Self) : ($($t:tt)*)) => {Self($($t)*)};
    (@result: (Option) : ($($t:tt)*)) => {match $($t)* { Some(x) => Some(Self(x)), None => None }};
    (@result: ($($t0:tt)*) : ($($t:tt)*)) => {$($t)*};
}

#[doc(hidden)]
#[macro_export]
#[allow(unused_macros)]
macro_rules! forward_op_impl {
    (@basic: $on:ty: $($name:ident -- $method:ident ($op:tt) $other:ident $(*$lit:literal)?),*) => {
        
$(
        
    $crate::forward_op_impl!{@basic_inner: $on ; $name ; $method ; ($op) ; $other $(*$lit)?}
        
)*
    };
    (@basic_inner: $on:ty ; $name:ident ; $method:ident ; ($op:tt) ; $other:ident $(* $lit:literal)?) => {
        impl ::core::ops::$name<$other> for $on {
            type Output = Self;

            fn $method(self, other: $other) -> Self {
                Self(self.0 $op $crate::forward_const!(@param: other $(* $lit)?))
            }
        }
    };

    (@assign: $on:ty: $($name:ident -- $method:ident $other:ident $(*$lit:literal)?),*) => {
        $(
            $crate::forward_op_impl!{@assign_inner: $on ; $name ; $method ; $other $(*$lit)?}
        )*
    };
    (@assign_inner: $on:ty ; $name:ident ; $method:ident ; $other:ident $(* $lit:literal)?) => {
        impl ::core::ops::$name<$other> for $on {
            fn $method(&mut self, other: $other) {
                self.0.$method($crate::forward_const!(@param: other $(* $lit)?))
            }
        }
    };
}

/// Creates a newtype with the necessary trait forwards for ease-of-use.
///
/// Example usage:
/// ```
/// use finitely::make_ring;
///
/// make_ring! {
///     // Attributes are supported:
///
///     #[allow(dead_code)]
///     /// The field with 25 elements.
///     pub(crate) F25 = { Z % 5, x^2 = [3] };
///
///     WeirdRing = { Z % 3500, x^5 = [12, 3, 4, 56] };
/// }
/// ```
#[allow(unused_macros)]
#[macro_export]
macro_rules! make_ring {
    ($($(#[$at:meta])* $view:vis $name:ident = { Z % $modulo:literal, x^ $degree:literal = [$($coefficients:literal),+] };)+) => {$(
        $(#[$at])*
        #[derive(PartialEq, Copy, Clone)]
        $view struct $name($crate::FinitePoly<Self, {$crate::get_size::<Self>()}, {$crate::get_log2::<Self>()}>);

        impl<const SIZE: usize, const LOG2: usize> $crate::PolySettings<SIZE, LOG2> for $name {
            const DEGREE: usize = $degree;
            const MODULO: u64 = $modulo;

            const OVERFLOW: $crate::FinitePoly<Self, SIZE, LOG2> = $crate::FinitePoly::<Self, SIZE, LOG2>::from_coeffs(&[$($coefficients),+]);
        }

        impl $name {
            #[allow(dead_code)]
            $view const LOG2: usize = $crate::get_size::<Self>();
            #[allow(dead_code)]
            $view const SIZE: usize = $crate::get_log2::<Self>();
            #[allow(dead_code)]
            $view const OVERFLOW: Self = Self(<Self as $crate::PolySettings<{Self::LOG2}, {Self::SIZE}>>::OVERFLOW);

            $view const ZERO: Self = Self($crate::FinitePoly::<Self, {$crate::get_size::<Self>()}, {$crate::get_log2::<Self>()}>::ZERO);
            $view const ONE: Self = Self($crate::FinitePoly::<Self, {$crate::get_size::<Self>()}, {$crate::get_log2::<Self>()}>::ONE);

            $crate::forward_const! {
                $view, ($crate::FinitePoly<Self, {$crate::get_size::<Self>()}, {$crate::get_log2::<Self>()}>) :
                fn splat(value: u64) -> Self;
                fn from_int(value: u64) -> Self;
                fn degree(self*0) -> usize;
                fn eq(self*0, other*0: Self) -> bool;
                fn is_zero(self*0) -> bool;
                fn add(self*0, other*0: Self) -> Self;
                fn sub(self*0, other*0: Self) -> Self;
                fn mul(self*0, other*0: Self) -> Self;
                fn neg(self*0) -> Self;
                fn mul_modulo(self*0, by: u64) -> Self;
                fn mul_x(self*0) -> Self;
                fn unchecked_mulx(self*0, power: usize) -> Self;
                fn get_nth_coeff(self*0, coeff: usize) -> u64;
                fn set_coeff(self*0, idx: usize, coeff: u64) -> Self;
                fn invert(self*0) -> Option<Self>;
                fn from_coeffs(coeffs: &[u64]) -> Self;
            }

            #[allow(dead_code)]
            $view const fn divide_remainder(self, other: Self) -> Option<(Self, Self)> {
                match self.0.divide_remainder(other.0) {
                    Some((x, y)) => Some((Self(x), Self(y))),
                    None => None
                }
            }

            #[allow(dead_code)]
            $view const fn divide_quotient_poly_by_self(self) -> Option<(Self, Self)> {
                match self.0.divide_quotient_poly_by_self() {
                    Some((x, y)) => Some((Self(x), Self(y))),
                    None => None
                }
            }

            $view fn iter() -> impl Iterator<Item = Self> {
                $crate::FinitePoly::<Self, {$crate::get_size::<Self>()}, {$crate::get_log2::<Self>()}>::iter().map(|x| Self(x))
            }
        }

        const _: () = {
            type Poly = $crate::FinitePoly<$name, {$crate::get_size::<$name>()}, {$crate::get_log2::<$name>()}>;
            impl From<$name> for Poly {
                fn from(other: $name) -> Self {
                    other.0
                }
            }

            impl From<Poly> for $name {
                fn from(other: Poly) -> Self {
                    Self(other)
                }
            }

            impl ::core::fmt::Debug for $name {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    <Poly as ::core::fmt::Debug>::fmt(&self.0, f)
                }
            }

            impl ::core::fmt::Display for $name {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    <Poly as ::core::fmt::Display>::fmt(&self.0, f)
                }
            }

            impl ::core::cmp::Eq for $name {}

            impl<T> ::core::cmp::PartialEq<T> for $name
            where Poly: PartialEq<T> {
                fn eq(&self, other: &T) -> bool {
                    self.0 == *other
                }
            }

            $crate::forward_op_impl! {
                @basic: $name:
                Add -- add (+) u64,
                Add -- add (+) Poly,
                Add -- add (+) $name * 0,
                Sub -- sub (-) u64,
                Sub -- sub (-) Poly,
                Sub -- sub (-) $name * 0,
                Mul -- mul (*) u64,
                Mul -- mul (*) Poly,
                Mul -- mul (*) $name * 0,
                Div -- div (/) u64,
                Div -- div (/) Poly,
                Div -- div (/) $name * 0
            }

            $crate::forward_op_impl! {
                @assign: $name:
                AddAssign -- add_assign u64,
                AddAssign -- add_assign Poly,
                AddAssign -- add_assign $name * 0,
                SubAssign -- sub_assign u64,
                SubAssign -- sub_assign Poly,
                SubAssign -- sub_assign $name * 0,
                MulAssign -- mul_assign u64,
                MulAssign -- mul_assign Poly,
                MulAssign -- mul_assign $name * 0,
                DivAssign -- div_assign u64,
                DivAssign -- div_assign Poly,
                DivAssign -- div_assign $name * 0
            }
        };
    )+};
}

#[cfg(test)]
mod tests {
    macro_rules! make_ring_tests {
        ($name:ident, $coeffs:literal, $modulo:literal) => {
            #[test]
            fn integer_to_poly() {
                let one_const = $name::ONE;
                let one_phi = $name::from_int(1);

                assert_eq!(one_const, one_phi);

                for i in 0..20 {
                    let pre_reduced = i % $modulo;

                    let value_1 = $name::from_int(i);
                    let value_2 = $name::from_int(pre_reduced);
                    let mut value_3 = $name::ZERO;

                    for _ in 0..i {
                        value_3 = value_3 + $name::ONE;
                    }

                    let mut value_4 = $name::ZERO;

                    for _ in 0..pre_reduced {
                        value_4 = value_4 + $name::ONE;
                    }

                    assert_eq!(value_1, value_2);
                    assert_eq!(value_2, value_3);
                    assert_eq!(value_3, value_4);
                }
            }

            #[test]
            fn coeff_equality() {
                for lhs in $name::iter() {
                    for rhs in $name::iter() {
                        let mut equal = true;
                        for power in 0..$coeffs {
                            let coeff_left = lhs.get_nth_coeff(power) % $modulo;
                            let coeff_right = rhs.get_nth_coeff(power) % $modulo;

                            equal &= coeff_left == coeff_right;
                        }

                        assert_eq!(equal, lhs == rhs, "Lhs: {lhs}, Rhs: {rhs}");
                    }
                }
            }

            #[test]
            fn equality_is_equality() {
                // An equivalence relation ~ satisfies:
                // 1. x ~ x
                // 2. x ~ y ==> y ~ x
                // 3. x ~ y and y ~ z ==> x ~ z

                // Test identity.
                for x in $name::iter() {
                    assert_eq!(x, x);
                }

                // Test reflexivity.
                for x in $name::iter() {
                    for y in $name::iter() {
                        assert_eq!(x == y, y == x);
                    }
                }

                // Test transitivity.
                for x in $name::iter() {
                    for y in $name::iter() {
                        for z in $name::iter() {
                            if x == y && y == z {
                                assert_eq!(x, z);
                            }
                        }
                    }
                }
            }

            // We happen to have a field. The field axioms are:
            // 1.  Exists `+: F x F -> F` (done.)
            // 2.  Exists `*: F x F -> F` (done.)
            // 3.  For all: `x + y = y + x`.
            // 4.  For all: `x * y = y * x`.
            // 5.  For all: `x + (y + z) = (x + y) + z`
            // 6.  For all: `x * (y * z) = (x * y) * z`
            // 7.  Exists `0 in F`: For all: `x + 0 = x`.
            // 8.  Exists `1 in F`: For all: `x * 1 = x`.
            // 9.  For all: `x * (y + z) = x * y + x * z`.
            // 10. For all `x in F`: Exists `y in F`: `x + y = 0`
            // The previous 10 give us a Commutative Unital Ring
            // (from now on, this is just a ring). These two extra
            // axioms make it a field:
            // 11. `0 != 1`.
            // 12. For all `x in F`: `x != y` implies Exists `y in F`: `x * y = 1`

            #[test]
            fn addition_commutes() {
                for x in $name::iter() {
                    for y in $name::iter() {
                        assert_eq!(x + y, y + x);
                    }
                }
            }

            #[test]
            fn multiplication_commutes() {
                for x in $name::iter() {
                    for y in $name::iter() {
                        assert_eq!(x * y, y * x);
                    }
                }
            }

            #[test]
            fn addition_associates() {
                for x in $name::iter() {
                    for y in $name::iter() {
                        for z in $name::iter() {
                            assert_eq!(x + (y + z), (x + y) + z);
                        }
                    }
                }
            }

            #[test]
            fn multiplication_associates() {
                for x in $name::iter() {
                    for y in $name::iter() {
                        for z in $name::iter() {
                            assert_eq!(x * (y * z), (x * y) * z);
                        }
                    }
                }
            }

            #[test]
            fn zero_is_zero() {
                for x in $name::iter() {
                    assert_eq!(x + $name::ZERO, x);
                }
            }

            #[test]
            fn one_is_one() {
                for x in $name::iter() {
                    assert_eq!(x * $name::ONE, x);
                }
            }

            #[test]
            fn multiplication_distributes() {
                for x in $name::iter() {
                    for y in $name::iter() {
                        for z in $name::iter() {
                            assert_eq!(x * (y + z), (x * y) + (x * z));
                        }
                    }
                }
            }

            #[test]
            fn additive_inverses() {
                'a: for x in $name::iter() {
                    for y in $name::iter() {
                        if x + y == $name::ZERO {
                            continue 'a;
                        }
                    }

                    panic!("Additive inverse for {x} not found!");
                }
            }

            #[test]
            fn zero_is_not_one() {
                assert_ne!($name::ZERO, $name::ONE);
            }
        };
    }

    make_ring! {
        F125 = { Z % 5, x^3 = [2, 2] };
        BadRingSmall = { Z % 6, x^1 = [0] };
        BadRing = { Z % 6, x^2 = [3, 2] };
        BadPoly = { Z % 5, x^2 = [4] };
    }

    mod field {
        use super::F125;
        make_ring_tests! {F125, 3, 5}

        #[test]
        fn multiplicative_inverse() {
            for x in F125::iter() {
                let computed_inverse = x.invert();

                let mut found_inverse = None;
                for y in F125::iter() {
                    if x * y == F125::ONE {
                        found_inverse = Some(y);
                        break;
                    }
                }

                assert_eq!(computed_inverse, found_inverse, "Poly: {x}");

                if !x.is_zero() && computed_inverse.is_none() {
                    panic!("Multiplicative inverse for {x} not found!");
                }
            }
        }
    }

    mod integers_bad {
        use super::BadRingSmall;
        make_ring_tests! {BadRingSmall, 1, 6}

        #[test]
        fn integers_mod_bad() {
            for (i, val) in BadRingSmall::iter().enumerate() {
                assert_eq!(val, BadRingSmall::from_int(i as u64));
            }
        }
    }

    mod integers_bad_poly_bad {
        use super::BadRing;
        make_ring_tests! {BadRing, 2, 6}
    }

    mod poly_bad {
        use super::BadPoly;
        make_ring_tests! {BadPoly, 2, 5}
    }
}