feanor-math 3.5.18

A library for number theory, providing implementations for arithmetic in various rings and algorithms working on them.
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
use std::fmt::{Debug, Display};

use crate::algorithms::linsolve::LinSolveRing;
use crate::algorithms::miller_rabin::is_prime;
use crate::algorithms::poly_factor::FactorPolyField;
use crate::algorithms::poly_gcd::PolyTFracGCDRing;
use crate::computation::no_error;
use crate::delegate::*;
use crate::divisibility::*;
use crate::field::Field;
use crate::homomorphism::*;
use crate::integer::*;
use crate::ordered::OrderedRing;
use crate::ring::*;
use crate::rings::field::{AsField, AsFieldBase};
use crate::rings::finite::FiniteRing;
use crate::rings::zn::*;
use crate::seq::*;
use crate::specialization::FiniteRingSpecializable;

/// Trait for rings that support lifting partial factorizations of polynomials modulo a prime
/// to the ring. For infinite fields, this is the most important approach to computing gcd's,
/// and also factorizations (with some caveats...).
///
/// Note that here (and in `feanor-math` generally), the term "local" is used to refer to algorithms
/// that work modulo prime ideals (or their powers), which is different from the mathematical
/// concept of localization.
///
/// The general philosophy is similar to [`crate::reduce_lift::poly_eval::EvalPolyLocallyRing`].
/// However, when working with factorizations, it is usually better to compute modulo the
/// factorization modulo an ideal `I`, and use Hensel lifting to derive the factorization modulo
/// `I^e`. `EvalPolyLocallyRing` on the other hand is designed to allow computations modulo multiple
/// different maximal ideals.
///
/// I am currently not yet completely sure what the exact requirements of this trait would be,
/// but conceptually, we want that for a random ideal `I` taken from some set of ideals (e.g.
/// maximal ideals, prime ideals, ... depending on the context), the quotient `R / I` should be
/// "nice", so that we can compute the desired factorization (or gcd etc.) over `R / I`.
/// Furthermore there should be a power `e` such that we can derive the factorization (or gcd etc.)
/// over `R` from the factorization over `R / I^e`. Note that we don't assume that this `e` can be
/// computed, except possibly in special cases (like the integers). Also, we cannot always assume
/// that `I` is a maximal ideal (unfortunately - it was a nasty surprise when I realized this after
/// running my first implementation), however I believe we can choose it such that we know its
/// decomposition into maximal ideals `a = m1 ∩ ... ∩ mr`.
///
/// Note also that I want this to work even when going to algebraic extensions or even the algebraic
/// closure. This however seems to follow naturally in most cases.
///
/// # Mathematical examples
///
/// There are three main classes of rings that this trait is designed for
///  - The integers `ZZ`. By Gauss' lemma, we know that any factor of an integral polynomial is
///    again integral, and we can bound its size (using the absolute value `|.|` of the real
///    numbers) in terms of size and degree of the original polynomial. This motivates the main
///    algorithm for factoring over `Z`: Reduce modulo a prime `p`, lift the factorization to `p^e`
///    for a large enough `p`, and (more or less) read of the factors over `Z`.
///  - Multivariate polynomial rings `R[X1, ..., Xm]` where `R` is a finite field (or another ring
///    where we can efficiently compute polynomial factorizations, e.g. another
///    [`PolyGCDLocallyDomain`]). For simplicity, let's focus on the finite field case, i.e. `R =
///    k`. Then we can take a maximal ideal `m` of `k[X1, ..., Xm]`, and reduce a polynomial `f in
///    k[X1, ..., Xm][Y]` modulo `m`, compute its factorization there (i.e. over `k`), lift it to
///    `k[X1, ..., Xm]/m^e` and (more or less) read of the factors over `R[X1, ..., Xm]`. Note that
///    if the base ring is not a field, the ideals will only be prime and not maximal. Also, the
///    polynomial coefficients of the result might only live in the fraction field of `R`, similar
///    to the algebraic number field case.
///  - Orders in algebraic number fields. This case is much more complicated, since (in general) we
///    don't have a UFD anymore. In particular, this is the case where we cannot generally choose `a
///    = m` to be a maximal ideal, and also need rational reconstruction when lifting the
///    factorization back to the number field. More concretely, the factors of a polynomial with
///    coefficients in an order `R` don't necessarily have coefficients in `R`. Example: `X^2 -
///    sqrt(3) X - 1` over `Z[sqrt(3), sqrt(7)]` has the factor `X - (sqrt(3) + sqrt(7)) / 2`.
///    However, it turns out that if the original polynomial is monic, then its factors have
///    coefficients in the maximal order `O` of `R ⊗ QQ`. In particular, if we scale the factor by
///    `[R : O] | disc(R)`, then we do end up with coefficients in `R`. Unfortunately, the
///    discriminant can become really huge, which is why in the literature, rational reconstruction
///    is used, to elements from `R / p^e` to "small" fractions in `Frac(R)`.
///
/// I cannot think of any other good examples (these were the ones I had in mind when writing this
/// trait), but who knows, maybe there are other rings that satisfy this and which we can thus do
/// polynomial factorization in.
///
/// # Type-level recursion
///
/// This trait and related functionality use type-level recursion, as explained in
/// [`crate::reduce_lift::poly_eval::EvalPolyLocallyRing`].
#[stability::unstable(feature = "enable")]
pub trait PolyGCDLocallyDomain: Domain + DivisibilityRing + FiniteRingSpecializable {
    /// The type of the local ring once we quotiented out a power of a prime ideal.
    type LocalRingBase<'ring>: ?Sized + LinSolveRing
    where
        Self: 'ring;

    type LocalRing<'ring>: RingStore<Type = Self::LocalRingBase<'ring>> + Clone
    where
        Self: 'ring;

    /// The type of the field we get by quotienting out a power of a prime ideal.
    ///
    /// For the reason why there are so many quite specific trait bounds here:
    /// See the doc of [`crate::reduce_lift::poly_eval::EvalPolyLocallyRing::LocalRingBase`].
    type LocalFieldBase<'ring>: ?Sized + PolyTFracGCDRing + FactorPolyField + Field + SelfIso + FiniteRingSpecializable
    where
        Self: 'ring;

    type LocalField<'ring>: RingStore<Type = Self::LocalFieldBase<'ring>> + Clone
    where
        Self: 'ring;

    /// An ideal of the ring for which we know a decomposition into maximal ideals, and
    /// can use Hensel lifting to lift values to higher powers of this ideal.
    type SuitableIdeal<'ring>
    where
        Self: 'ring;

    /// Returns an exponent `e` such that we hope that the factors of a polynomial of given degree,
    /// involving the given coefficient can already be read of (via
    /// [`PolyGCDLocallyDomain::reconstruct_ring_el()`]) their reductions modulo `I^e`. Note
    /// that this is just a heuristic, and if it does not work, the implementation will
    /// gradually try larger `e`. Thus, even if this function returns constant 1, correctness
    /// will not be affected, but giving a good guess can improve performance
    fn heuristic_exponent<'ring, 'a, I>(
        &self,
        _ideal: &Self::SuitableIdeal<'ring>,
        _poly_deg: usize,
        _coefficients: I,
    ) -> usize
    where
        I: Iterator<Item = &'a Self::Element>,
        Self: 'a,
        Self: 'ring;

    /// Returns an ideal sampled at random from the interval of all supported ideals.
    fn random_suitable_ideal<'ring, F>(&'ring self, rng: F) -> Self::SuitableIdeal<'ring>
    where
        F: FnMut() -> u64;

    /// Returns the number of maximal ideals in the primary decomposition of `ideal`.
    fn maximal_ideal_factor_count<'ring>(&self, ideal: &Self::SuitableIdeal<'ring>) -> usize
    where
        Self: 'ring;

    /// Returns `R / mi`, where `mi` is the `i`-th maximal ideal over `I`.
    ///
    /// This will always be a field, since `mi` is a maximal ideal.
    fn local_field_at<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        max_ideal_idx: usize,
    ) -> Self::LocalField<'ring>
    where
        Self: 'ring;

    /// Returns `R / mi^e`, where `mi` is the `i`-th maximal ideal over `I`.
    fn local_ring_at<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        e: usize,
        max_ideal_idx: usize,
    ) -> Self::LocalRing<'ring>
    where
        Self: 'ring;

    /// Computes the reduction map
    /// ```text
    ///   R -> R / mi^e
    /// ```
    /// where `mi` is the `i`-th maximal ideal over `I`.
    fn reduce_ring_el<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        to: (&Self::LocalRingBase<'ring>, usize),
        max_ideal_idx: usize,
        x: Self::Element,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring;

    /// Computes the reduction map
    /// ```text
    ///   R / mi^e1 -> R / mi^e2
    /// ```
    /// where `e1 >= e2` and `mi` is the `i`-th maximal ideal over `I`.
    fn reduce_partial<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        from: (&Self::LocalRingBase<'ring>, usize),
        to: (&Self::LocalRingBase<'ring>, usize),
        max_ideal_idx: usize,
        x: El<Self::LocalRing<'ring>>,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring;

    /// Computes the isomorphism between the ring and field representations of `R / mi`
    fn base_ring_to_field<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        from: &Self::LocalRingBase<'ring>,
        to: &Self::LocalFieldBase<'ring>,
        max_ideal_idx: usize,
        x: El<Self::LocalRing<'ring>>,
    ) -> El<Self::LocalField<'ring>>
    where
        Self: 'ring;

    /// Computes the isomorphism between the ring and field representations of `R / mi`
    fn field_to_base_ring<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        from: &Self::LocalFieldBase<'ring>,
        to: &Self::LocalRingBase<'ring>,
        max_ideal_idx: usize,
        x: El<Self::LocalField<'ring>>,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring;

    /// Computes any element `y` in `R / mi^to_e` such that `y = x mod mi^from_e`.
    /// In particular, `y` does not have to be "short" in any sense, but any lift
    /// is a valid result.
    fn lift_partial<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        from: (&Self::LocalRingBase<'ring>, usize),
        to: (&Self::LocalRingBase<'ring>, usize),
        max_ideal_idx: usize,
        x: El<Self::LocalRing<'ring>>,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring;

    /// Computes a "small" element `x in R` such that `x mod mi^e` is equal to the given value,
    /// for every maximal ideal `mi` over `I`.
    /// In cases where the factors of polynomials in `R[X]` do not necessarily have coefficients
    /// in `R`, this function might have to do rational reconstruction.
    fn reconstruct_ring_el<'local, 'element, 'ring, V1, V2>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        from: V1,
        e: usize,
        x: V2,
    ) -> Self::Element
    where
        Self: 'ring,
        V1: VectorFn<&'local Self::LocalRing<'ring>>,
        V2: VectorFn<&'element El<Self::LocalRing<'ring>>>,
        Self::LocalRing<'ring>: 'local,
        El<Self::LocalRing<'ring>>: 'element,
        'ring: 'local + 'element;

    fn dbg_ideal<'ring>(&self, ideal: &Self::SuitableIdeal<'ring>, out: &mut std::fmt::Formatter) -> std::fmt::Result
    where
        Self: 'ring;
}

/// Subtrait of [`PolyGCDLocallyDomain`] that restricts the local rings to be [`ZnRing`],
/// which is necessary when implementing some base cases.
#[stability::unstable(feature = "enable")]
pub trait IntegerPolyGCDRing: PolyGCDLocallyDomain {
    /// It would be much preferrable if we could restrict associated types from supertraits,
    /// this is just a workaround (and an ugly one at that)
    type LocalRingAsZnBase<'ring>: ?Sized + CanIsoFromTo<Self::LocalRingBase<'ring>> + ZnRing + SelfIso
    where
        Self: 'ring;

    type LocalRingAsZn<'ring>: RingStore<Type = Self::LocalRingAsZnBase<'ring>> + Clone
    where
        Self: 'ring;

    fn local_ring_as_zn<'a, 'ring>(&self, local_field: &'a Self::LocalRing<'ring>) -> &'a Self::LocalRingAsZn<'ring>;

    fn local_ring_into_zn<'ring>(&self, local_field: Self::LocalRing<'ring>) -> Self::LocalRingAsZn<'ring>;

    fn principal_ideal_generator<'ring>(&self, p: &Self::SuitableIdeal<'ring>) -> El<BigIntRing>
    where
        Self: 'ring,
    {
        assert_eq!(1, self.maximal_ideal_factor_count(p));
        let Fp = self.local_ring_at(p, 1, 0);
        let Fp = self.local_ring_as_zn(&Fp);
        return int_cast(
            Fp.integer_ring().clone_el(Fp.modulus()),
            BigIntRing::RING,
            Fp.integer_ring(),
        );
    }
}

#[stability::unstable(feature = "enable")]
pub struct IdealDisplayWrapper<'a, 'ring, R: 'ring + ?Sized + PolyGCDLocallyDomain> {
    ring: &'a R,
    ideal: &'a R::SuitableIdeal<'ring>,
}

impl<'a, 'ring, R: 'ring + ?Sized + PolyGCDLocallyDomain> IdealDisplayWrapper<'a, 'ring, R> {
    #[stability::unstable(feature = "enable")]
    pub fn new(ring: &'a R, ideal: &'a R::SuitableIdeal<'ring>) -> Self { Self { ring, ideal } }
}

impl<'a, 'ring, R: 'ring + ?Sized + PolyGCDLocallyDomain> Display for IdealDisplayWrapper<'a, 'ring, R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.ring.dbg_ideal(self.ideal, f) }
}

/// The map `R -> R/m^e`, where `m` is a maximal ideal factor of the ideal `I`,
/// as specified by [`PolyGCDLocallyDomain`].
#[stability::unstable(feature = "enable")]
pub struct PolyGCDLocallyReductionMap<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    ring: RingRef<'data, R>,
    ideal: &'data R::SuitableIdeal<'ring>,
    to: (&'local R::LocalRing<'ring>, usize),
    max_ideal_idx: usize,
}

impl<'ring, 'data, 'local, R> PolyGCDLocallyReductionMap<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    #[stability::unstable(feature = "enable")]
    pub fn new(
        ring: &'data R,
        ideal: &'data R::SuitableIdeal<'ring>,
        to: &'local R::LocalRing<'ring>,
        to_e: usize,
        max_ideal_idx: usize,
    ) -> Self {
        assert!(to.get_ring() == ring.local_ring_at(ideal, to_e, max_ideal_idx).get_ring());
        Self {
            ring: RingRef::new(ring),
            ideal,
            to: (to, to_e),
            max_ideal_idx,
        }
    }
}

impl<'ring, 'data, 'local, R> Homomorphism<R, R::LocalRingBase<'ring>>
    for PolyGCDLocallyReductionMap<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    type CodomainStore = &'local R::LocalRing<'ring>;
    type DomainStore = RingRef<'data, R>;

    fn codomain(&self) -> &Self::CodomainStore { &self.to.0 }

    fn domain(&self) -> &Self::DomainStore { &self.ring }

    fn map(&self, x: <R as RingBase>::Element) -> <R::LocalRingBase<'ring> as RingBase>::Element {
        self.ring
            .get_ring()
            .reduce_ring_el(self.ideal, (self.to.0.get_ring(), self.to.1), self.max_ideal_idx, x)
    }
}

/// The map `R/m^r -> R/m^e`, where `r > e` and `m` is a maximal ideal factor of the
/// ideal `I`, as specified by [`PolyGCDLocallyDomain`].
#[stability::unstable(feature = "enable")]
pub struct PolyGCDLocallyIntermediateReductionMap<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    ring: RingRef<'data, R>,
    ideal: &'data R::SuitableIdeal<'ring>,
    from: (&'local R::LocalRing<'ring>, usize),
    to: (&'local R::LocalRing<'ring>, usize),
    max_ideal_idx: usize,
}

impl<'ring, 'data, 'local, R> PolyGCDLocallyIntermediateReductionMap<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    #[stability::unstable(feature = "enable")]
    pub fn new(
        ring: &'data R,
        ideal: &'data R::SuitableIdeal<'ring>,
        from: &'local R::LocalRing<'ring>,
        from_e: usize,
        to: &'local R::LocalRing<'ring>,
        to_e: usize,
        max_ideal_idx: usize,
    ) -> Self {
        assert!(ring.local_ring_at(ideal, from_e, max_ideal_idx).get_ring() == from.get_ring());
        assert!(ring.local_ring_at(ideal, to_e, max_ideal_idx).get_ring() == to.get_ring());
        Self {
            ring: RingRef::new(ring),
            ideal,
            from: (from, from_e),
            to: (to, to_e),
            max_ideal_idx,
        }
    }

    #[stability::unstable(feature = "enable")]
    pub fn parent_ring<'a>(&'a self) -> RingRef<'a, R> { RingRef::new(self.ring.get_ring()) }

    #[stability::unstable(feature = "enable")]
    pub fn from_e(&self) -> usize { self.from.1 }

    #[stability::unstable(feature = "enable")]
    pub fn to_e(&self) -> usize { self.to.1 }

    #[stability::unstable(feature = "enable")]
    pub fn ideal<'a>(&'a self) -> &'a R::SuitableIdeal<'ring> { &self.ideal }

    #[stability::unstable(feature = "enable")]
    pub fn max_ideal_idx(&self) -> usize { self.max_ideal_idx }
}

impl<'ring, 'data, 'local, R> Homomorphism<R::LocalRingBase<'ring>, R::LocalRingBase<'ring>>
    for PolyGCDLocallyIntermediateReductionMap<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    type CodomainStore = &'local R::LocalRing<'ring>;
    type DomainStore = &'local R::LocalRing<'ring>;

    fn codomain(&self) -> &Self::CodomainStore { &self.to.0 }

    fn domain(&self) -> &Self::DomainStore { &self.from.0 }

    fn map(&self, x: <R::LocalRingBase<'ring> as RingBase>::Element) -> <R::LocalRingBase<'ring> as RingBase>::Element {
        self.ring.get_ring().reduce_partial(
            self.ideal,
            (self.from.0.get_ring(), self.from.1),
            (self.to.0.get_ring(), self.to.1),
            self.max_ideal_idx,
            x,
        )
    }
}

/// The isomorphism from the standard representation to the
/// field representation of `R / mi`, for a [`PolyGCDLocallyDomain`]
/// `R` with maximal ideal `mi`.
#[stability::unstable(feature = "enable")]
pub struct PolyGCDLocallyBaseRingToFieldIso<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    ring: RingRef<'data, R>,
    ideal: &'data R::SuitableIdeal<'ring>,
    from: RingRef<'local, R::LocalRingBase<'ring>>,
    to: RingRef<'local, R::LocalFieldBase<'ring>>,
    max_ideal_idx: usize,
}

impl<'ring, 'data, 'local, R> PolyGCDLocallyBaseRingToFieldIso<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    #[stability::unstable(feature = "enable")]
    pub fn new(
        ring: &'data R,
        ideal: &'data R::SuitableIdeal<'ring>,
        from: &'local R::LocalRingBase<'ring>,
        to: &'local R::LocalFieldBase<'ring>,
        max_ideal_idx: usize,
    ) -> Self {
        assert!(ring.local_ring_at(ideal, 1, max_ideal_idx).get_ring() == from);
        assert!(ring.local_field_at(ideal, max_ideal_idx).get_ring() == to);
        Self {
            ring: RingRef::new(ring),
            ideal,
            from: RingRef::new(from),
            to: RingRef::new(to),
            max_ideal_idx,
        }
    }

    #[stability::unstable(feature = "enable")]
    pub fn inv(&self) -> PolyGCDLocallyFieldToBaseRingIso<'ring, 'data, 'local, R> {
        PolyGCDLocallyFieldToBaseRingIso {
            ring: self.ring,
            ideal: self.ideal,
            from: self.to,
            to: self.from,
            max_ideal_idx: self.max_ideal_idx,
        }
    }
}

impl<'ring, 'data, 'local, R> Homomorphism<R::LocalRingBase<'ring>, R::LocalFieldBase<'ring>>
    for PolyGCDLocallyBaseRingToFieldIso<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    type DomainStore = RingRef<'local, R::LocalRingBase<'ring>>;
    type CodomainStore = RingRef<'local, R::LocalFieldBase<'ring>>;

    fn codomain(&self) -> &Self::CodomainStore { &self.to }

    fn domain(&self) -> &Self::DomainStore { &self.from }

    fn map(
        &self,
        x: <R::LocalRingBase<'ring> as RingBase>::Element,
    ) -> <R::LocalFieldBase<'ring> as RingBase>::Element {
        self.ring.get_ring().base_ring_to_field(
            self.ideal,
            self.from.get_ring(),
            self.to.get_ring(),
            self.max_ideal_idx,
            x,
        )
    }
}

/// The isomorphism from the field representation to the
/// standard representation of `R / mi`, for a [`PolyGCDLocallyDomain`]
/// `R` with maximal ideal `mi`.
#[stability::unstable(feature = "enable")]
pub struct PolyGCDLocallyFieldToBaseRingIso<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    ring: RingRef<'data, R>,
    ideal: &'data R::SuitableIdeal<'ring>,
    to: RingRef<'local, R::LocalRingBase<'ring>>,
    from: RingRef<'local, R::LocalFieldBase<'ring>>,
    max_ideal_idx: usize,
}

impl<'ring, 'data, 'local, R> PolyGCDLocallyFieldToBaseRingIso<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    #[stability::unstable(feature = "enable")]
    pub fn inv(&self) -> PolyGCDLocallyBaseRingToFieldIso<'ring, 'data, 'local, R> {
        PolyGCDLocallyBaseRingToFieldIso {
            ring: self.ring,
            ideal: self.ideal,
            from: self.to,
            to: self.from,
            max_ideal_idx: self.max_ideal_idx,
        }
    }
}

impl<'ring, 'data, 'local, R> Homomorphism<R::LocalFieldBase<'ring>, R::LocalRingBase<'ring>>
    for PolyGCDLocallyFieldToBaseRingIso<'ring, 'data, 'local, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    type DomainStore = RingRef<'local, R::LocalFieldBase<'ring>>;
    type CodomainStore = RingRef<'local, R::LocalRingBase<'ring>>;

    fn codomain(&self) -> &Self::CodomainStore { &self.to }

    fn domain(&self) -> &Self::DomainStore { &self.from }

    fn map(
        &self,
        x: <R::LocalFieldBase<'ring> as RingBase>::Element,
    ) -> <R::LocalRingBase<'ring> as RingBase>::Element {
        self.ring.get_ring().field_to_base_ring(
            self.ideal,
            self.from.get_ring(),
            self.to.get_ring(),
            self.max_ideal_idx,
            x,
        )
    }
}

/// The sequence of maps `R  ->  R/m1^e x ... x R/mr^e  ->  R/m1 x ... x R/mr`, where
/// `m1, ..., mr` are the maximal ideals containing `I`, as specified by [`PolyGCDLocallyDomain`].
///
/// This sequence of maps is very relevant when using the compute-mod-p-and-lift approach
/// for polynomial operations over infinite rings (e.g. `QQ`). This is also the primary use case
/// for [`ReductionContext`].
#[stability::unstable(feature = "enable")]
pub struct ReductionContext<'ring, 'data, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    ring: RingRef<'data, R>,
    ideal: &'data R::SuitableIdeal<'ring>,
    from_e: usize,
    from: Vec<R::LocalRing<'ring>>,
    to: Vec<R::LocalRing<'ring>>,
    to_fields: Vec<R::LocalField<'ring>>,
}

impl<'ring, 'data, R> ReductionContext<'ring, 'data, R>
where
    R: 'ring + ?Sized + PolyGCDLocallyDomain,
    'ring: 'data,
{
    #[stability::unstable(feature = "enable")]
    pub fn new(ring: &'data R, ideal: &'data R::SuitableIdeal<'ring>, e: usize) -> Self {
        assert!(e >= 1);
        let maximal_ideal_factor_count = ring.maximal_ideal_factor_count(ideal);
        Self {
            ring: RingRef::new(ring),
            ideal,
            from_e: e,
            from: (0..maximal_ideal_factor_count)
                .map(|idx| ring.local_ring_at(ideal, e, idx))
                .collect::<Vec<_>>(),
            to: (0..maximal_ideal_factor_count)
                .map(|idx| ring.local_ring_at(ideal, 1, idx))
                .collect::<Vec<_>>(),
            to_fields: (0..maximal_ideal_factor_count)
                .map(|idx| ring.local_field_at(ideal, idx))
                .collect::<Vec<_>>(),
        }
    }

    #[stability::unstable(feature = "enable")]
    pub fn ideal(&self) -> &'data R::SuitableIdeal<'ring> { self.ideal }

    #[stability::unstable(feature = "enable")]
    pub fn main_ring_to_field_reduction<'local>(
        &'local self,
        max_ideal_idx: usize,
    ) -> PolyGCDLocallyReductionMap<'ring, 'data, 'local, R> {
        PolyGCDLocallyReductionMap {
            ideal: self.ideal,
            ring: self.ring,
            to: (self.to.at(max_ideal_idx), 1),
            max_ideal_idx,
        }
    }

    #[stability::unstable(feature = "enable")]
    pub fn main_ring_to_intermediate_ring_reduction<'local>(
        &'local self,
        max_ideal_idx: usize,
    ) -> PolyGCDLocallyReductionMap<'ring, 'data, 'local, R> {
        PolyGCDLocallyReductionMap {
            ideal: self.ideal,
            ring: self.ring,
            to: (self.from.at(max_ideal_idx), self.from_e),
            max_ideal_idx,
        }
    }

    #[stability::unstable(feature = "enable")]
    pub fn intermediate_ring_to_field_reduction<'local>(
        &'local self,
        max_ideal_idx: usize,
    ) -> PolyGCDLocallyIntermediateReductionMap<'ring, 'data, 'local, R> {
        PolyGCDLocallyIntermediateReductionMap {
            from: (&self.from[max_ideal_idx], self.from_e),
            to: (&self.to[max_ideal_idx], 1),
            max_ideal_idx,
            ring: self.ring,
            ideal: self.ideal,
        }
    }

    #[stability::unstable(feature = "enable")]
    pub fn base_ring_to_field_iso<'local>(
        &'local self,
        max_ideal_idx: usize,
    ) -> PolyGCDLocallyBaseRingToFieldIso<'ring, 'data, 'local, R> {
        PolyGCDLocallyBaseRingToFieldIso {
            ring: self.ring,
            ideal: self.ideal,
            from: RingRef::new(self.to[max_ideal_idx].get_ring()),
            to: RingRef::new(self.to_fields[max_ideal_idx].get_ring()),
            max_ideal_idx,
        }
    }

    #[stability::unstable(feature = "enable")]
    pub fn len(&self) -> usize { self.from.len() }

    #[stability::unstable(feature = "enable")]
    pub fn reconstruct_ring_el<'local, V>(&self, els: V) -> R::Element
    where
        V: VectorFn<&'local El<R::LocalRing<'ring>>>,
        El<R::LocalRing<'ring>>: 'local,
        'ring: 'local,
    {
        fn do_reconstruction<'ring, 'local, R, V>(
            ring: &R,
            ideal: &R::SuitableIdeal<'ring>,
            local_rings: &[R::LocalRing<'ring>],
            e: usize,
            els: V,
        ) -> R::Element
        where
            R: 'ring + ?Sized + PolyGCDLocallyDomain,
            V: VectorFn<&'local El<R::LocalRing<'ring>>>,
            El<R::LocalRing<'ring>>: 'local,
            'ring: 'local,
        {
            ring.reconstruct_ring_el(ideal, local_rings.as_fn(), e, els)
        }
        do_reconstruction(self.ring.get_ring(), self.ideal, &self.from[..], self.from_e, els)
    }
}

#[stability::unstable(feature = "enable")]
pub const INTRING_HEURISTIC_FACTOR_SIZE_OVER_POLY_SIZE_FACTOR: f64 = 0.25;

/// Implements [`PolyGCDLocallyDomain`] and [`IntegerPolyGCDRing`] for an integer ring.
///
/// This uses a default implementation, where the maximal ideals are random 24-bit prime numbers,
/// and the corresponding residue field is implemented using [`crate::rings::zn::zn_64::Zn`]. This
/// should be suitable in almost all scenarios.
///
/// The syntax is the same as for other impl-macros, see e.g.
/// [`crate::impl_interpolation_base_ring_char_zero!`].
#[macro_export]
macro_rules! impl_poly_gcd_locally_for_ZZ {
    (IntegerPolyGCDRing for $int_ring_type:ty) => {
        impl_poly_gcd_locally_for_ZZ!{ <{}> IntegerPolyGCDRing for $int_ring_type where }
    };
    (<{$($gen_args:tt)*}> IntegerPolyGCDRing for $int_ring_type:ty where $($constraints:tt)*) => {

        impl<$($gen_args)*> $crate::reduce_lift::poly_factor_gcd::PolyGCDLocallyDomain for $int_ring_type
            where $($constraints)*
        {
            type LocalRing<'ring> = $crate::rings::zn::zn_big::Zn<BigIntRing>
                where Self: 'ring;
            type LocalRingBase<'ring> = $crate::rings::zn::zn_big::ZnBase<BigIntRing>
                where Self: 'ring;
            type LocalFieldBase<'ring> = $crate::rings::field::AsFieldBase<$crate::rings::zn::zn_64::Zn>
                where Self: 'ring;
            type LocalField<'ring> = $crate::rings::field::AsField<$crate::rings::zn::zn_64::Zn>
                where Self: 'ring;
            type SuitableIdeal<'ring> = i64
                where Self: 'ring;

            fn reconstruct_ring_el<'local, 'element, 'ring, V1, V2>(&self, _p: &Self::SuitableIdeal<'ring>, from: V1, _e: usize, x: V2) -> Self::Element
                where Self: 'ring,
                    V1: $crate::seq::VectorFn<&'local Self::LocalRing<'ring>>,
                    V2: $crate::seq::VectorFn<&'element El<Self::LocalRing<'ring>>>
            {
                use $crate::rings::zn::*;
                #[allow(unused)]
                use $crate::seq::*;
                assert_eq!(1, from.len());
                assert_eq!(1, x.len());
                int_cast(from.at(0).smallest_lift(from.at(0).clone_el(x.at(0))), RingRef::new(self), BigIntRing::RING)
            }

            fn maximal_ideal_factor_count<'ring>(&self, _p: &Self::SuitableIdeal<'ring>) -> usize
                where Self: 'ring
            {
                1
            }

            fn lift_partial<'ring>(&self, _p: &Self::SuitableIdeal<'ring>, from: (&Self::LocalRingBase<'ring>, usize), to: (&Self::LocalRingBase<'ring>, usize), max_ideal_idx: usize, x: El<Self::LocalRing<'ring>>) -> El<Self::LocalRing<'ring>>
                where Self: 'ring
            {
                use $crate::rings::zn::*;
                use $crate::homomorphism::*;

                assert_eq!(0, max_ideal_idx);
                assert!(from.1 <= to.1);
                let hom = RingRef::new(to.0).into_can_hom(to.0.integer_ring()).ok().unwrap();
                return hom.map(from.0.any_lift(x));
            }

            fn local_field_at<'ring>(&self, p: &Self::SuitableIdeal<'ring>, max_ideal_idx: usize) -> Self::LocalField<'ring>
                where Self: 'ring
            {
                use $crate::rings::zn::*;

                assert_eq!(0, max_ideal_idx);
                $crate::rings::zn::zn_64::Zn::new(*p as u64).as_field().ok().unwrap()
            }

            fn local_ring_at<'ring>(&self, p: &Self::SuitableIdeal<'ring>, e: usize, max_ideal_idx: usize) -> Self::LocalRing<'ring>
                where Self: 'ring
            {
                assert_eq!(0, max_ideal_idx);
                $crate::rings::zn::zn_big::Zn::new(BigIntRing::RING, BigIntRing::RING.pow(int_cast(*p, BigIntRing::RING, StaticRing::<i64>::RING), e))
            }

            fn random_suitable_ideal<'ring, F>(&'ring self, rng: F) -> Self::SuitableIdeal<'ring>
                where F: FnMut() -> u64
            {
                let lower_bound = StaticRing::<i64>::RING.get_ring().get_uniformly_random_bits(24, rng);
                return $crate::algorithms::miller_rabin::next_prime(StaticRing::<i64>::RING, lower_bound);
            }

            fn base_ring_to_field<'ring>(&self, _ideal: &Self::SuitableIdeal<'ring>, from: &Self::LocalRingBase<'ring>, to: &Self::LocalFieldBase<'ring>, max_ideal_idx: usize, x: El<Self::LocalRing<'ring>>) -> El<Self::LocalField<'ring>>
                where Self: 'ring
            {
                assert_eq!(0, max_ideal_idx);
                assert_eq!(from.characteristic(StaticRing::<i64>::RING).unwrap(), to.characteristic(StaticRing::<i64>::RING).unwrap());
                <_ as $crate::rings::zn::ZnRing>::from_int_promise_reduced(to, $crate::integer::int_cast(
                    <_ as $crate::rings::zn::ZnRing>::smallest_positive_lift(from, x),
                    <_ as $crate::rings::zn::ZnRing>::integer_ring(to),
                    <_ as $crate::rings::zn::ZnRing>::integer_ring(from),
                ))
            }

            fn field_to_base_ring<'ring>(&self, _ideal: &Self::SuitableIdeal<'ring>, from: &Self::LocalFieldBase<'ring>, to: &Self::LocalRingBase<'ring>, max_ideal_idx: usize, x: El<Self::LocalField<'ring>>) -> El<Self::LocalRing<'ring>>
                where Self: 'ring
            {

                assert_eq!(0, max_ideal_idx);
                assert_eq!(from.characteristic(StaticRing::<i64>::RING).unwrap(), to.characteristic(StaticRing::<i64>::RING).unwrap());
                <_ as $crate::rings::zn::ZnRing>::from_int_promise_reduced(to, $crate::integer::int_cast(
                    <_ as $crate::rings::zn::ZnRing>::smallest_positive_lift(from, x),
                    <_ as $crate::rings::zn::ZnRing>::integer_ring(to),
                    <_ as $crate::rings::zn::ZnRing>::integer_ring(from),
                ))
            }

            fn reduce_ring_el<'ring>(&self, _p: &Self::SuitableIdeal<'ring>, to: (&Self::LocalRingBase<'ring>, usize), max_ideal_idx: usize, x: Self::Element) -> El<Self::LocalRing<'ring>>
                where Self: 'ring
            {
                use $crate::homomorphism::*;

                assert_eq!(0, max_ideal_idx);
                let self_ref = RingRef::new(self);
                let hom = RingRef::new(to.0).into_can_hom(&self_ref).ok().unwrap();
                return hom.map(x);
            }

            fn reduce_partial<'ring>(&self, _p: &Self::SuitableIdeal<'ring>, from: (&Self::LocalRingBase<'ring>, usize), to: (&Self::LocalRingBase<'ring>, usize), max_ideal_idx: usize, x: El<Self::LocalRing<'ring>>) -> El<Self::LocalRing<'ring>>
                where Self: 'ring
            {
                use $crate::rings::zn::*;
                use $crate::homomorphism::*;

                assert_eq!(0, max_ideal_idx);
                assert!(from.1 >= to.1);
                let hom = RingRef::new(to.0).into_can_hom(to.0.integer_ring()).ok().unwrap();
                return hom.map(from.0.smallest_lift(x));
            }

            fn heuristic_exponent<'ring, 'a, I>(&self, p: &i64, poly_deg: usize, coefficients: I) -> usize
                where I: Iterator<Item = &'a Self::Element>,
                    Self: 'a,
                    Self: 'ring
            {
                let log2_max_coeff = coefficients.map(|c| RingRef::new(self).abs_log2_ceil(c).unwrap_or(0)).max().unwrap_or(0);
                // this is in no way a rigorous bound, but equals the worst-case bound at least asymptotically (up to constants)
                return ((log2_max_coeff as f64 + poly_deg as f64) / (*p as f64).log2() * $crate::reduce_lift::poly_factor_gcd::INTRING_HEURISTIC_FACTOR_SIZE_OVER_POLY_SIZE_FACTOR).ceil() as usize + 1;
            }

            fn dbg_ideal<'ring>(&self, p: &Self::SuitableIdeal<'ring>, out: &mut std::fmt::Formatter) -> std::fmt::Result
                where Self: 'ring
            {
                write!(out, "({})", p)
            }
        }

        impl<$($gen_args)*> $crate::reduce_lift::poly_factor_gcd::IntegerPolyGCDRing for $int_ring_type
            where $($constraints)*
        {
            type LocalRingAsZnBase<'ring> = Self::LocalRingBase<'ring>
                where Self: 'ring;

            type LocalRingAsZn<'ring> = Self::LocalRing<'ring>
                where Self: 'ring;

            fn local_ring_as_zn<'a, 'ring>(&self, local_field: &'a Self::LocalRing<'ring>) -> &'a Self::LocalRingAsZn<'ring>
                where Self: 'ring
            {
                local_field
            }

            fn local_ring_into_zn<'ring>(&self, local_field: Self::LocalRing<'ring>) -> Self::LocalRingAsZn<'ring>
                where Self: 'ring
            {
                local_field
            }
        }
    };
}

/// We cannot provide a blanket impl of [`crate::algorithms::poly_gcd::PolyTFracGCDRing`] for finite
/// fields, since it would conflict with the one for all rings that impl [`PolyGCDLocallyDomain`].
/// Thus, we implement [`PolyGCDLocallyDomain`] for all finite fields, and reuse the blanket impl.
///
/// Note that while technically, finite fields are always [`PolyGCDLocallyDomain`] - where the
/// local rings are all equal to itself - we still panic in the implementations. In particular,
/// giving a working implementation would be "correct", but this implementation should never be
/// called anyway, since we specialize on finite fields previously anyway.
#[allow(unused)]
impl<R> PolyGCDLocallyDomain for R
where
    R: ?Sized + FiniteRing + FactorPolyField + Field + SelfIso,
{
    type LocalRingBase<'ring>
        = Self
    where
        Self: 'ring;
    type LocalRing<'ring>
        = RingRef<'ring, Self>
    where
        Self: 'ring;

    type LocalFieldBase<'ring>
        = Self
    where
        Self: 'ring;
    type LocalField<'ring>
        = RingRef<'ring, Self>
    where
        Self: 'ring;
    type SuitableIdeal<'ring>
        = RingRef<'ring, Self>
    where
        Self: 'ring;

    fn heuristic_exponent<'ring, 'element, IteratorType>(
        &self,
        _maximal_ideal: &Self::SuitableIdeal<'ring>,
        _poly_deg: usize,
        _coefficients: IteratorType,
    ) -> usize
    where
        IteratorType: Iterator<Item = &'element Self::Element>,
        Self: 'element,
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn maximal_ideal_factor_count<'ring>(&self, ideal: &Self::SuitableIdeal<'ring>) -> usize
    where
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn random_suitable_ideal<'ring, RandomNumberFunction>(
        &'ring self,
        rng: RandomNumberFunction,
    ) -> Self::SuitableIdeal<'ring>
    where
        RandomNumberFunction: FnMut() -> u64,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn local_field_at<'ring>(&self, p: &Self::SuitableIdeal<'ring>, max_ideal_idx: usize) -> Self::LocalField<'ring>
    where
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn local_ring_at<'ring>(
        &self,
        p: &Self::SuitableIdeal<'ring>,
        e: usize,
        max_ideal_idx: usize,
    ) -> Self::LocalRing<'ring>
    where
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn reduce_ring_el<'ring>(
        &self,
        p: &Self::SuitableIdeal<'ring>,
        to: (&Self::LocalRingBase<'ring>, usize),
        max_ideal_idx: usize,
        x: Self::Element,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn base_ring_to_field<'ring>(
        &self,
        _ideal: &Self::SuitableIdeal<'ring>,
        from: &Self::LocalRingBase<'ring>,
        to: &Self::LocalFieldBase<'ring>,
        max_ideal_idx: usize,
        x: El<Self::LocalRing<'ring>>,
    ) -> El<Self::LocalField<'ring>>
    where
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn field_to_base_ring<'ring>(
        &self,
        _ideal: &Self::SuitableIdeal<'ring>,
        from: &Self::LocalFieldBase<'ring>,
        to: &Self::LocalRingBase<'ring>,
        max_ideal_idx: usize,
        x: El<Self::LocalField<'ring>>,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn reduce_partial<'ring>(
        &self,
        p: &Self::SuitableIdeal<'ring>,
        from: (&Self::LocalRingBase<'ring>, usize),
        to: (&Self::LocalRingBase<'ring>, usize),
        max_ideal_idx: usize,
        x: El<Self::LocalRing<'ring>>,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn lift_partial<'ring>(
        &self,
        p: &Self::SuitableIdeal<'ring>,
        from: (&Self::LocalRingBase<'ring>, usize),
        to: (&Self::LocalRingBase<'ring>, usize),
        max_ideal_idx: usize,
        x: El<Self::LocalRing<'ring>>,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn reconstruct_ring_el<'local, 'element, 'ring, V1, V2>(
        &self,
        p: &Self::SuitableIdeal<'ring>,
        from: V1,
        e: usize,
        x: V2,
    ) -> Self::Element
    where
        Self: 'ring,
        V1: VectorFn<&'local Self::LocalRing<'ring>>,
        V2: VectorFn<&'element El<Self::LocalRing<'ring>>>,
        'ring: 'local + 'element,
        Self::LocalRing<'ring>: 'local,
        El<Self::LocalRing<'ring>>: 'element,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }

    fn dbg_ideal<'ring>(&self, p: &Self::SuitableIdeal<'ring>, out: &mut std::fmt::Formatter) -> std::fmt::Result
    where
        Self: 'ring,
    {
        unreachable!(
            "this should never be called for finite fields, since specialized functions are available in this case"
        )
    }
}

#[stability::unstable(feature = "enable")]
pub struct IntegersWithLocalZnQuotient<'a, R>
where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + LinSolveRing + Clone,
{
    integers: &'a R::IntegerRing,
    prime: El<R::IntegerRing>,
}

impl<'a, R> IntegersWithLocalZnQuotient<'a, R>
where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + LinSolveRing + Clone,
{
    #[stability::unstable(feature = "enable")]
    pub fn new(integers: &'a R::IntegerRing, prime: El<R::IntegerRing>) -> Self {
        assert!(is_prime(integers, &prime, 10));
        return Self { integers, prime };
    }

    #[stability::unstable(feature = "enable")]
    pub fn reduction_context<'b>(&'b self, from_e: usize) -> ReductionContext<'b, 'b, Self> {
        ReductionContext {
            ring: RingRef::new(self),
            ideal: &self.prime,
            from_e,
            from: vec![self.local_ring_at(&self.prime, from_e, 0)],
            to: vec![self.local_ring_at(&self.prime, 1, 0)],
            to_fields: vec![self.local_field_at(&self.prime, 0)],
        }
    }
}

impl<'a, R> Debug for IntegersWithLocalZnQuotient<'a, R>
where
    R: ?Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + LinSolveRing + Clone,
    R::IntegerRingBase: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IntegersWithLocalZnQuotient")
            .field("integers", &self.integers.get_ring())
            .finish()
    }
}

impl<'a, R> PartialEq for IntegersWithLocalZnQuotient<'a, R>
where
    R: ?Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + LinSolveRing + Clone,
{
    fn eq(&self, other: &Self) -> bool { self.integers.get_ring() == other.integers.get_ring() }
}

impl<'a, R> DelegateRing for IntegersWithLocalZnQuotient<'a, R>
where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + LinSolveRing + Clone,
{
    type Base = <R as ZnRing>::IntegerRingBase;
    type Element = El<<R as ZnRing>::IntegerRing>;

    fn get_delegate(&self) -> &Self::Base { self.integers.get_ring() }

    fn delegate(&self, el: Self::Element) -> <Self::Base as RingBase>::Element { el }
    fn delegate_mut<'b>(&self, el: &'b mut Self::Element) -> &'b mut <Self::Base as RingBase>::Element { el }
    fn delegate_ref<'b>(&self, el: &'b Self::Element) -> &'b <Self::Base as RingBase>::Element { el }
    fn rev_delegate(&self, el: <Self::Base as RingBase>::Element) -> Self::Element { el }
}

impl<'a, R> OrderedRing for IntegersWithLocalZnQuotient<'a, R>
where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + Clone,
{
    fn cmp(&self, lhs: &Self::Element, rhs: &Self::Element) -> std::cmp::Ordering {
        self.get_delegate().cmp(self.delegate_ref(lhs), self.delegate_ref(rhs))
    }
    fn abs_cmp(&self, lhs: &Self::Element, rhs: &Self::Element) -> std::cmp::Ordering {
        self.get_delegate()
            .abs_cmp(self.delegate_ref(lhs), self.delegate_ref(rhs))
    }
}

impl<'a, R> Domain for IntegersWithLocalZnQuotient<'a, R> where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + Clone
{
}

impl<'a, R> DelegateRingImplFiniteRing for IntegersWithLocalZnQuotient<'a, R> where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + Clone
{
}

impl<'a, R> DelegateRingImplEuclideanRing for IntegersWithLocalZnQuotient<'a, R> where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + Clone
{
}

impl<'a, R> crate::reduce_lift::poly_eval::EvalPolyLocallyRing for IntegersWithLocalZnQuotient<'a, R>
where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + Clone,
{
    type LocalRingBase<'ring>
        = <<Self as DelegateRing>::Base as crate::reduce_lift::poly_eval::EvalPolyLocallyRing>::LocalRingBase<'ring>
    where
        Self: 'ring;
    type LocalRing<'ring>
        = <<Self as DelegateRing>::Base as crate::reduce_lift::poly_eval::EvalPolyLocallyRing>::LocalRing<'ring>
    where
        Self: 'ring;
    type LocalComputationData<'ring>
        = <<Self as DelegateRing>::Base as crate::reduce_lift::poly_eval::EvalPolyLocallyRing>::LocalComputationData<
        'ring,
    >
    where
        Self: 'ring;

    fn ln_pseudo_norm(&self, el: &Self::Element) -> f64 { self.get_delegate().ln_pseudo_norm(self.delegate_ref(el)) }

    fn reduce<'ring>(
        &self,
        computation: &Self::LocalComputationData<'ring>,
        el: &Self::Element,
    ) -> Vec<<Self::LocalRingBase<'ring> as RingBase>::Element>
    where
        Self: 'ring,
    {
        self.get_delegate().reduce(computation, self.delegate_ref(el))
    }

    fn local_ring_count<'ring>(&self, computation: &Self::LocalComputationData<'ring>) -> usize
    where
        Self: 'ring,
    {
        self.get_delegate().local_ring_count(computation)
    }

    fn local_ring_at<'ring>(&self, computation: &Self::LocalComputationData<'ring>, i: usize) -> Self::LocalRing<'ring>
    where
        Self: 'ring,
    {
        crate::reduce_lift::poly_eval::EvalPolyLocallyRing::local_ring_at(self.get_delegate(), computation, i)
    }

    fn local_computation<'ring>(&'ring self, ln_pseudo_norm_bound: f64) -> Self::LocalComputationData<'ring> {
        self.get_delegate().local_computation(ln_pseudo_norm_bound)
    }

    fn lift_combine<'ring>(
        &self,
        computation: &Self::LocalComputationData<'ring>,
        el: &[<Self::LocalRingBase<'ring> as RingBase>::Element],
    ) -> Self::Element
    where
        Self: 'ring,
    {
        self.rev_delegate(self.get_delegate().lift_combine(computation, el))
    }
}

impl<'a, R> IntegerRing for IntegersWithLocalZnQuotient<'a, R>
where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + Clone,
{
    fn to_float_approx(&self, value: &Self::Element) -> f64 {
        self.get_delegate()
            .to_float_approx(self.delegate_ref(self.rev_element_cast_ref(value)))
    }
    fn from_float_approx(&self, value: f64) -> Option<Self::Element> {
        self.get_delegate()
            .from_float_approx(value)
            .map(|x| self.element_cast(self.rev_delegate(x)))
    }
    fn abs_is_bit_set(&self, value: &Self::Element, i: usize) -> bool {
        self.get_delegate()
            .abs_is_bit_set(self.delegate_ref(self.rev_element_cast_ref(value)), i)
    }
    fn abs_highest_set_bit(&self, value: &Self::Element) -> Option<usize> {
        self.get_delegate()
            .abs_highest_set_bit(self.delegate_ref(self.rev_element_cast_ref(value)))
    }
    fn abs_lowest_set_bit(&self, value: &Self::Element) -> Option<usize> {
        self.get_delegate()
            .abs_lowest_set_bit(self.delegate_ref(self.rev_element_cast_ref(value)))
    }
    fn get_uniformly_random_bits<G: FnMut() -> u64>(&self, log2_bound_exclusive: usize, rng: G) -> Self::Element {
        self.element_cast(self.rev_delegate(self.get_delegate().get_uniformly_random_bits(log2_bound_exclusive, rng)))
    }
    fn rounded_div(&self, lhs: Self::Element, rhs: &Self::Element) -> Self::Element {
        self.element_cast(self.rev_delegate(self.get_delegate().rounded_div(
            self.delegate(self.rev_element_cast(lhs)),
            self.delegate_ref(self.rev_element_cast_ref(rhs)),
        )))
    }
    fn ceil_div(&self, lhs: Self::Element, rhs: &Self::Element) -> Self::Element {
        self.element_cast(self.rev_delegate(self.get_delegate().ceil_div(
            self.delegate(self.rev_element_cast(lhs)),
            self.delegate_ref(self.rev_element_cast_ref(rhs)),
        )))
    }
    fn floor_div(&self, lhs: Self::Element, rhs: &Self::Element) -> Self::Element {
        self.element_cast(self.rev_delegate(self.get_delegate().floor_div(
            self.delegate(self.rev_element_cast(lhs)),
            self.delegate_ref(self.rev_element_cast_ref(rhs)),
        )))
    }
    fn power_of_two(&self, power: usize) -> Self::Element {
        self.element_cast(self.rev_delegate(self.get_delegate().power_of_two(power)))
    }
    fn representable_bits(&self) -> Option<usize> { self.get_delegate().representable_bits() }
    fn parse(&self, string: &str, base: u32) -> Result<Self::Element, ()> {
        self.get_delegate()
            .parse(string, base)
            .map(|x| self.element_cast(self.rev_delegate(x)))
    }

    fn euclidean_div_pow_2(&self, value: &mut Self::Element, power: usize) {
        self.get_delegate()
            .euclidean_div_pow_2(self.delegate_mut(self.rev_element_cast_mut(value)), power);
        self.postprocess_delegate_mut(self.rev_element_cast_mut(value));
    }

    fn mul_pow_2(&self, value: &mut Self::Element, power: usize) {
        self.get_delegate()
            .mul_pow_2(self.delegate_mut(self.rev_element_cast_mut(value)), power);
        self.postprocess_delegate_mut(self.rev_element_cast_mut(value));
    }
}

impl<'a, R> PolyGCDLocallyDomain for IntegersWithLocalZnQuotient<'a, R>
where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + LinSolveRing + Clone,
{
    type LocalRingBase<'ring>
        = R
    where
        Self: 'ring;

    type LocalRing<'ring>
        = RingValue<R>
    where
        Self: 'ring;

    type LocalFieldBase<'ring>
        = AsFieldBase<RingValue<R>>
    where
        Self: 'ring;

    type LocalField<'ring>
        = AsField<RingValue<R>>
    where
        Self: 'ring;

    type SuitableIdeal<'ring>
        = Self::Element
    where
        Self: 'ring;

    fn heuristic_exponent<'ring, 'el, I>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        poly_deg: usize,
        coefficients: I,
    ) -> usize
    where
        I: Iterator<Item = &'el Self::Element>,
        Self: 'el + 'ring,
    {
        let log2_max_coeff = coefficients
            .map(|c| self.integers.abs_log2_ceil(c).unwrap_or(0))
            .max()
            .unwrap_or(0);
        // this is in no way a rigorous bound, but equals the worst-case bound at least
        // asymptotically (up to constants)
        return ((log2_max_coeff as f64 + poly_deg as f64) / self.integers.abs_log2_floor(ideal).unwrap_or(1) as f64
            * crate::reduce_lift::poly_factor_gcd::INTRING_HEURISTIC_FACTOR_SIZE_OVER_POLY_SIZE_FACTOR)
            .ceil() as usize
            + 1;
    }

    fn random_suitable_ideal<'ring, F>(&'ring self, _rng: F) -> Self::SuitableIdeal<'ring>
    where
        F: FnMut() -> u64,
    {
        self.integers.clone_el(&self.prime)
    }

    fn maximal_ideal_factor_count<'ring>(&self, ideal: &Self::SuitableIdeal<'ring>) -> usize
    where
        Self: 'ring,
    {
        debug_assert!(self.integers.eq_el(ideal, &self.prime));
        1
    }

    fn local_field_at<'ring>(&self, ideal: &Self::SuitableIdeal<'ring>, max_ideal_idx: usize) -> Self::LocalField<'ring>
    where
        Self: 'ring,
    {
        assert_eq!(0, max_ideal_idx);
        self.local_ring_at(ideal, 1, 0).as_field().ok().unwrap()
    }

    fn local_ring_at<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        e: usize,
        max_ideal_idx: usize,
    ) -> Self::LocalRing<'ring>
    where
        Self: 'ring,
    {
        assert_eq!(0, max_ideal_idx);
        assert!(self.integers.eq_el(ideal, &self.prime));
        RingValue::from(
            R::from_modulus(|ZZ| {
                Ok(RingRef::new(ZZ).pow(
                    int_cast(self.integers.clone_el(&self.prime), RingRef::new(ZZ), &self.integers),
                    e,
                ))
            })
            .unwrap_or_else(no_error),
        )
    }

    fn reduce_ring_el<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        to: (&Self::LocalRingBase<'ring>, usize),
        max_ideal_idx: usize,
        x: Self::Element,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring,
    {
        debug_assert_eq!(0, max_ideal_idx);
        debug_assert!(self.integers.eq_el(ideal, &self.prime));
        debug_assert!(self.integers.eq_el(
            &self.integers.pow(self.integers.clone_el(&self.prime), to.1),
            to.0.modulus()
        ));
        RingRef::new(to.0).coerce(&self.integers, x)
    }

    fn reduce_partial<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        from: (&Self::LocalRingBase<'ring>, usize),
        to: (&Self::LocalRingBase<'ring>, usize),
        max_ideal_idx: usize,
        x: El<Self::LocalRing<'ring>>,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring,
    {
        debug_assert_eq!(0, max_ideal_idx);
        debug_assert!(self.integers.eq_el(ideal, &self.prime));
        debug_assert!(self.integers.eq_el(
            &self.integers.pow(self.integers.clone_el(&self.prime), to.1),
            to.0.modulus()
        ));
        debug_assert!(self.integers.eq_el(
            &self.integers.pow(self.integers.clone_el(&self.prime), from.1),
            from.0.modulus()
        ));
        RingRef::new(to.0).coerce(&self.integers, from.0.smallest_positive_lift(x))
    }

    fn lift_partial<'ring>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        from: (&Self::LocalRingBase<'ring>, usize),
        to: (&Self::LocalRingBase<'ring>, usize),
        max_ideal_idx: usize,
        x: El<Self::LocalRing<'ring>>,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring,
    {
        debug_assert_eq!(0, max_ideal_idx);
        debug_assert!(self.integers.eq_el(ideal, &self.prime));
        debug_assert!(self.integers.eq_el(
            &self.integers.pow(self.integers.clone_el(&self.prime), to.1),
            to.0.modulus()
        ));
        debug_assert!(self.integers.eq_el(
            &self.integers.pow(self.integers.clone_el(&self.prime), from.1),
            from.0.modulus()
        ));
        RingRef::new(to.0).coerce(&self.integers, from.0.smallest_positive_lift(x))
    }

    fn base_ring_to_field<'ring>(
        &self,
        _ideal: &Self::SuitableIdeal<'ring>,
        from: &Self::LocalRingBase<'ring>,
        to: &Self::LocalFieldBase<'ring>,
        max_ideal_idx: usize,
        x: El<Self::LocalRing<'ring>>,
    ) -> El<Self::LocalField<'ring>>
    where
        Self: 'ring,
    {
        debug_assert_eq!(0, max_ideal_idx);
        assert!(from == to.get_delegate());
        to.element_cast(to.rev_delegate(x))
    }

    fn field_to_base_ring<'ring>(
        &self,
        _ideal: &Self::SuitableIdeal<'ring>,
        from: &Self::LocalFieldBase<'ring>,
        to: &Self::LocalRingBase<'ring>,
        max_ideal_idx: usize,
        x: El<Self::LocalField<'ring>>,
    ) -> El<Self::LocalRing<'ring>>
    where
        Self: 'ring,
    {
        debug_assert_eq!(0, max_ideal_idx);
        assert!(to == from.get_delegate());
        from.delegate(from.rev_element_cast(x))
    }

    fn reconstruct_ring_el<'local, 'element, 'ring, V1, V2>(
        &self,
        ideal: &Self::SuitableIdeal<'ring>,
        from: V1,
        e: usize,
        x: V2,
    ) -> Self::Element
    where
        Self: 'ring,
        V1: VectorFn<&'local Self::LocalRing<'ring>>,
        V2: VectorFn<&'element El<Self::LocalRing<'ring>>>,
        Self::LocalRing<'ring>: 'local,
        El<Self::LocalRing<'ring>>: 'element,
        'ring: 'local + 'element,
    {
        assert_eq!(1, x.len());
        assert_eq!(1, from.len());
        debug_assert!(self.integers.eq_el(ideal, &self.prime));
        debug_assert!(self.integers.eq_el(
            &self.integers.pow(self.integers.clone_el(&self.prime), e),
            from.at(0).modulus()
        ));
        from.at(0).smallest_lift(from.at(0).clone_el(x.at(0)))
    }

    fn dbg_ideal<'ring>(&self, ideal: &Self::SuitableIdeal<'ring>, out: &mut std::fmt::Formatter) -> std::fmt::Result
    where
        Self: 'ring,
    {
        self.dbg(ideal, out)
    }
}

impl<'a, R> IntegerPolyGCDRing for IntegersWithLocalZnQuotient<'a, R>
where
    R: Sized + SelfIso + ZnRing + FromModulusCreateableZnRing + LinSolveRing + Clone,
{
    type LocalRingAsZn<'ring>
        = Self::LocalRing<'ring>
    where
        Self: 'ring;
    type LocalRingAsZnBase<'ring>
        = Self::LocalRingBase<'ring>
    where
        Self: 'ring;

    fn local_ring_as_zn<'b, 'ring>(&self, local_field: &'b Self::LocalRing<'ring>) -> &'b Self::LocalRingAsZn<'ring>
    where
        Self: 'ring,
    {
        local_field
    }

    fn local_ring_into_zn<'ring>(&self, local_field: Self::LocalRing<'ring>) -> Self::LocalRingAsZn<'ring>
    where
        Self: 'ring,
    {
        local_field
    }
}