nucs 0.4.0

Library for working with nucleotide and amino acid sequences
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
//! Types related to translation of codons into amino acids.

use std::fmt::{Debug, Display, Formatter};
use std::iter::Rev;

use crate::error::TryFillBufLenError;
use crate::iter::{Codons, Complemented, DnaIterExt, Translated};
use crate::symbol::iter_symbols;
use crate::{AmbiAmino, AmbiNuc, Amino, DnaSliceExt, Nuc, Nucleotide, Seq};

/// Trait representing any type that can be used to translate codons into amino acids.
///
/// The most commonly used [`GeneticCode`] is [`NCBI1`] but there are others in
/// [`nucs::translation`](crate::translation).
pub trait GeneticCode {
    /// Translate a codon to an amino acid
    ///
    /// Examples
    ///
    /// ```
    /// use nucs::{AmbiAmino, Amino, AmbiNuc, Nuc, translation::GeneticCode};
    ///
    /// let genetic_code = |_codon| Amino::W; // translate everything to tryptophan
    /// assert_eq!(genetic_code.translate([Nuc::A; 3]), Amino::W);
    /// assert_eq!(genetic_code.translate([AmbiNuc::N; 3]), AmbiAmino::W);
    /// ```
    fn translate<N: Nucleotide>(&self, codon: [N; 3]) -> N::Amino {
        N::translate(self, codon)
    }

    /// Translate reverse complement of a codon to an amino acid
    ///
    /// Examples
    ///
    /// ```
    /// use nucs::{AmbiAmino, Amino, AmbiNuc, Nuc, translation::GeneticCode};
    /// use Nuc::{A, G, T};
    ///
    /// let genetic_code = |codon: [Nuc; 3]| match codon {
    ///    [A, T, G] => Amino::W,
    ///    _ => Amino::Stop,
    /// };
    /// assert_eq!(genetic_code.translate_rc(Nuc::arr(b"CAT")), Amino::W);
    /// assert_eq!(genetic_code.translate_rc(AmbiNuc::arr(b"CAT")), AmbiAmino::W);
    /// assert_eq!(genetic_code.translate_rc(AmbiNuc::arr(b"ANT")), AmbiAmino::Stop);
    /// ```
    fn translate_rc<N: Nucleotide>(&self, codon: [N; 3]) -> N::Amino {
        N::translate_rc(self, codon)
    }

    /// Translate a concrete codon to an amino acid
    ///
    /// Consider calling [`GeneticCode::translate`] instead; this primarily exists to be provided
    /// by implementors of [`GeneticCode`].
    fn translate_concrete_codon(&self, codon: [Nuc; 3]) -> Amino;

    /// Translate an ambiguous codon to an amino acid
    ///
    /// Consider calling [`GeneticCode::translate`] instead; this primarily exists to be provided
    /// by implementors of [`GeneticCode`].
    fn translate_ambiguous_codon(&self, codon: [AmbiNuc; 3]) -> AmbiAmino {
        let [ambi_n1, ambi_n2, ambi_n3] = codon;
        ambi_n1
            .iter()
            .flat_map(|n1| ambi_n2.iter().map(move |n2| [n1, n2]))
            .flat_map(|[n1, n2]| ambi_n3.iter().map(move |n3| [n1, n2, n3]))
            .map(|codon| AmbiAmino::from(self.translate_concrete_codon(codon)))
            .reduce(|a, b| a | b)
            .expect("BUG: null nucleotide encountered")
    }

    /// Translate reverse complement of a concrete codon to an amino acid
    ///
    /// Consider calling [`GeneticCode::translate_rc`] instead; this primarily exists to be provided
    /// by implementors of [`GeneticCode`].
    fn translate_rc_concrete_codon(&self, mut codon: [Nuc; 3]) -> Amino {
        codon.reverse();
        codon.complement();
        self.translate_concrete_codon(codon)
    }

    /// Translate reverse complement of an ambiguous codon to an amino acid
    ///
    /// Consider calling [`GeneticCode::translate_rc`] instead; this primarily exists to be provided
    /// by implementors of [`GeneticCode`].
    fn translate_rc_ambiguous_codon(&self, mut codon: [AmbiNuc; 3]) -> AmbiAmino {
        codon.reverse();
        codon.complement();
        self.translate_ambiguous_codon(codon)
    }
}

impl<F: Fn([Nuc; 3]) -> Amino> GeneticCode for F {
    fn translate_concrete_codon(&self, codon: [Nuc; 3]) -> Amino {
        self(codon)
    }
}

/// A table of amino acids can be used for genetic coding.
///
/// The [`Amino`]s must be ordered to correspond with codons in ascending lexicographical order
/// (`AAA`, `AAC`, `AAG`, `AAT`, `ACA`, ... `TTT`).
impl GeneticCode for &[Amino; 64] {
    fn translate_concrete_codon(&self, codon: [Nuc; 3]) -> Amino {
        let [n1, n2, n3] = codon;
        let idx = 16 * (n1 as u8).trailing_zeros()
            + 4 * (n2 as u8).trailing_zeros()
            + (n3 as u8).trailing_zeros();
        self[idx as usize]
    }
}

/// [`GeneticCode`] implementation optimized for speed over space.
///
/// Each [`FullLookup`] comes with about 18KiB of additional lookup tables,
/// dramatically improving translation speed, particularly for ambigous codons.
#[derive(Clone)]
pub struct FullLookup {
    lookup: ConcreteLookup,
    lookup_rc: ConcreteLookup,
    ambi_lookup: AmbiLookup,
    ambi_lookup_rc: AmbiLookup,
}

impl FullLookup {
    /// Build [`FullLookup`] from another [`GeneticCode`].
    ///
    /// This precalculates every possible ambiguous codon's translation.
    #[must_use]
    pub fn from_genetic_code<G: GeneticCode>(genetic_code: &G) -> Self {
        Self::from_table(&std::array::from_fn(|i| {
            let codon = [4, 2, 0].map(|offset| Nuc::ALL[(i >> offset) & 0b11]);
            genetic_code.translate(codon)
        }))
    }

    /// Build [`FullLookup`] from a table of [`Amino`]s.
    ///
    /// The [`Amino`]s must correspond to all codons in ascending lexicographical order.
    ///
    /// This precalculates every possible ambiguous codon's translation,
    /// but can be done at compile-time.
    #[must_use]
    pub const fn from_table(table: &[Amino; 64]) -> Self {
        let lookup = ConcreteLookup::from_table(table);
        let lookup_rc = lookup.reverse_complement();
        let ambi_lookup = lookup.to_ambi_lookup();
        let ambi_lookup_rc = ambi_lookup.reverse_complement();
        Self {
            lookup,
            lookup_rc,
            ambi_lookup,
            ambi_lookup_rc,
        }
    }

    /// Convert to simple amino acid table.
    ///
    /// The returned [`Amino`]s correspond to all codons in ascending lexicographical order.
    /// Although such a table can be used as a [`GeneticCode`], it's intended more for interop
    /// or inspection.
    ///
    /// ```
    /// use nucs::{Amino, NCBI1};
    ///
    /// let table = NCBI1.to_table();
    /// assert_eq!(table[0], Amino::K);  // AAA -> K
    /// assert_eq!(table[1], Amino::N);  // AAC -> N
    /// assert_eq!(table[2], Amino::K);  // AAG -> K
    /// assert_eq!(table[3], Amino::N);  // AAT -> N
    /// assert_eq!(table[4], Amino::T);  // ACA -> T
    /// // ...
    /// assert_eq!(table[16], Amino::Q); // CAA -> Q
    /// // ...
    /// assert_eq!(table[32], Amino::E); // GAA -> E
    /// // ...
    /// assert_eq!(table[62], Amino::L); // TTG -> L
    /// assert_eq!(table[63], Amino::F); // TTT -> F
    /// ```
    #[must_use]
    pub const fn to_table(&self) -> [Amino; 64] {
        self.lookup.to_table()
    }
}

impl GeneticCode for &FullLookup {
    #[inline(always)]
    fn translate_concrete_codon(&self, codon: [Nuc; 3]) -> Amino {
        (&self.lookup).translate_concrete_codon(codon)
    }

    #[inline(always)]
    fn translate_ambiguous_codon(&self, codon: [AmbiNuc; 3]) -> AmbiAmino {
        (&self.ambi_lookup).translate_ambiguous_codon(codon)
    }

    #[inline(always)]
    fn translate_rc_concrete_codon(&self, codon: [Nuc; 3]) -> Amino {
        (&self.lookup_rc).translate_concrete_codon(codon)
    }

    #[inline(always)]
    fn translate_rc_ambiguous_codon(&self, codon: [AmbiNuc; 3]) -> AmbiAmino {
        (&self.ambi_lookup_rc).translate_ambiguous_codon(codon)
    }
}

impl std::fmt::Debug for FullLookup {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.lookup.fmt(f)
    }
}

/// A lookup to efficiently translate concrete codons
///
/// The lookup doesn't allocate, but is about 2KiB in size. It supports very fast translation of
/// concrete codons (`[Nuc; 3]`) but is slower at translating ambiguous codons, or
/// reverse-complement codons.
#[derive(Clone)]
pub struct ConcreteLookup([Amino; 1 + 0x888]);
// The table layout:
// Each `Nuc` can be thought of as a hexidecimal digit, and each codon as a big-endian
// 3-digit hexadecimal index into the lookup table. A `Nuc` caps out at 0x8, so TTT
// corresponds to 0x888, plus an extra spot is needed at the start for 0x000.

impl ConcreteLookup {
    /// Build [`ConcreteLookup`] from a table of [`Amino`]s.
    ///
    /// The [`Amino`]s must correspond to all codons in ascending lexicographical order.
    #[must_use]
    pub const fn from_table(table: &[Amino; 64]) -> Self {
        let mut lookup = [Amino::A; _];
        let mut i = 0;
        while i < table.len() {
            lookup[Self::table_index_to_fast_lookup_index(i)] = table[i];
            i += 1;
        }
        Self(lookup)
    }

    /// Convert to simple amino acid table.
    ///
    /// The returned [`Amino`]s correspond to all codons in ascending lexicographical order.
    /// Although such a table can be used as a [`GeneticCode`], it's intended more for interop
    /// or inspection.
    ///
    /// ```
    /// use nucs::{Amino, NCBI1};
    /// use nucs::translation::ConcreteLookup;
    ///
    /// let table = Amino::arr(b"ACDEFGHIKLMNOPQRSTUVWY*ACDEFGHIKLMNOPQRSTUVWY*ACDEFGHIKLMNOPQRS*");
    /// let lookup = ConcreteLookup::from_table(&table);
    /// assert_eq!(lookup.to_table(), table);
    /// ```
    #[must_use]
    pub const fn to_table(&self) -> [Amino; 64] {
        let mut table = [Amino::A; _];
        let mut i = 0;
        while i < table.len() {
            table[i] = self.0[Self::table_index_to_fast_lookup_index(i)];
            i += 1;
        }
        table
    }

    // (by "table", I mean list of one amino per concrete codon, in lexicographical order)
    const fn table_index_to_fast_lookup_index(idx: usize) -> usize {
        let n1 = 1 << (0b11 & (idx >> 4));
        let n2 = 1 << (0b11 & (idx >> 2));
        let n3 = 1 << (0b11 & idx);
        (n1 << 8) | (n2 << 4) | n3
    }

    /// Return the reverse complement of this translation table.
    ///
    /// It produces a copy of the translation table where the reverse complement of each codon
    /// maps to the same amino acid as before. For example:
    ///
    /// ```
    /// use nucs::{Amino, Nuc};
    /// use nucs::translation::{ConcreteLookup, GeneticCode};
    /// use Nuc::{A, C, G, T};
    ///
    /// let table = Amino::arr(b"ACDEFGHIKLMNOPQRSTUVWY*ACDEFGHIKLMNOPQRSTUVWY*ACDEFGHIKLMNOPQRS*");
    /// let lookup = ConcreteLookup::from_table(&table);
    /// assert_eq!((&lookup).translate([A, T, G]), Amino::Q);
    /// let lookup_rc = lookup.reverse_complement();
    /// // ATG reverse-complemented is CAT, so...
    /// assert_eq!((&lookup_rc).translate([C, A, T]), Amino::Q);
    /// ```
    #[must_use]
    pub const fn reverse_complement(&self) -> Self {
        let mut lookup = [Amino::A; _];
        // As before, this could be flattened into a single unnested loop, but this nested
        // loop results in much sparser work.
        let mut n1 = 0x100;
        while n1 <= 0x800 {
            let mut n2 = 0x010;
            while n2 <= 0x080 {
                let mut n3 = 0x001;
                while n3 <= 0x008 {
                    let n1_n2_n3 = n1 | n2 | n3;
                    lookup[n1_n2_n3] = self.0[reverse_complement_index(n1_n2_n3)];
                    n3 <<= 1;
                }
                n2 <<= 1;
            }
            n1 <<= 1;
        }
        Self(lookup)
    }

    /// Build [`AmbiLookup`] from this [`ConcreteLookup`].
    ///
    /// This precalculates every possible ambiguous codon's translation,
    /// but can be done at compile-time.
    #[must_use]
    pub const fn to_ambi_lookup(&self) -> AmbiLookup {
        // This is 20x faster than calculating each lookup entry in isolation because it dedupes
        // the work of building merged table results. It treats the lookup like a lattice of sets:
        // Instead of having to build each set from scratch, it just builds them out of two
        // smaller sets. And counting upwards has the nice property of visiting the sets in
        // topological order so subsets will be populated before the sets that they feed into.
        // When an index contains multiple bits (when _b variables are non-zero), that means it's
        // ambiguous and should composed out of the results of smaller indices. In theory this
        // could be flattened into a single unnested loop that populates the indices in order,
        // but then the iterations couldn't share as much work, so it'd take about 50% longer.
        let mut lookup = [AmbiAmino::X; _];
        let mut n1 = 0x100;
        while n1 <= 0xf00 {
            let (n1_a, n1_b) = Self::split_lowest_bit(n1);
            if n1_b == 0 {
                let mut n2 = 0x010;
                while n2 <= 0x0f0 {
                    let n1_n2 = n1 | n2;
                    let (n2_a, n2_b) = Self::split_lowest_bit(n2);
                    if n2_b == 0 {
                        let mut n3 = 0x001;
                        while n3 <= 0x00f {
                            let n1_n2_n3 = n1_n2 | n3;
                            let (n3_a, n3_b) = Self::split_lowest_bit(n3);
                            if n3_b == 0 {
                                lookup[n1_n2_n3] = AmbiAmino::from_amino(self.0[n1_n2_n3]);
                            } else {
                                lookup[n1_n2_n3] = lookup[n1_n2 | n3_a].or(lookup[n1_n2 | n3_b]);
                            }
                            n3 += 0x001;
                        }
                    } else {
                        let n1_n2_a = n1 | n2_a;
                        let n1_n2_b = n1 | n2_b;
                        let mut n3 = 0x001;
                        while n3 <= 0x00f {
                            lookup[n1_n2 | n3] = lookup[n1_n2_a | n3].or(lookup[n1_n2_b | n3]);
                            n3 += 1;
                        }
                    }
                    n2 += 0x010;
                }
            } else {
                let mut n2_n3 = 0x011;
                while n2_n3 <= 0x0ff {
                    lookup[n1 | n2_n3] = lookup[n1_a | n2_n3].or(lookup[n1_b | n2_n3]);
                    n2_n3 += 1;
                }
            }
            n1 += 0x100;
        }
        AmbiLookup(lookup)
    }

    // Split a number into its lowest bit and other bits.
    const fn split_lowest_bit(i: usize) -> (usize, usize) {
        let lowest = 1 << i.trailing_zeros();
        (lowest, i & !lowest)
    }
}

impl GeneticCode for &ConcreteLookup {
    #[inline(always)]
    fn translate_concrete_codon(&self, codon: [Nuc; 3]) -> Amino {
        let [n1, n2, n3] = codon;
        self.0[((n1 as usize) << 8) | ((n2 as usize) << 4) | (n3 as usize)]
    }
}

impl std::fmt::Debug for ConcreteLookup {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt_genetic_code(&self, f)
    }
}

/// A lookup to efficiently translate ambiguous codons
///
/// The lookup doesn't allocate, but is about 2KiB in size. It supports very fast translation of
/// ambiguous codons (`[AmbiNuc; 3]`) but is slower at translating concrete codons, or
/// reverse-complement codons.
#[derive(Clone)]
pub struct AmbiLookup([AmbiAmino; 1 + 0xfff]);
// The table layout is similar to `ConcreteLookup`:
// Each `AmbiNuc` can be thought of as a hexidecimal digit, and each codon as a big-endian
// 3-digit hexadecimal index into the lookup table. An `AmbiNuc` caps out at 0xf, so NNN
// corresponds to 0xfff, plus an extra spot is needed at the start for 0x000.

impl AmbiLookup {
    /// Return the reverse complement of this translation table.
    ///
    /// It produces a copy of the translation table where the reverse complement of each codon
    /// maps to the same amino acid as before. For example:
    ///
    /// ```
    /// use nucs::{Amino, Nuc, NCBI1};
    /// use nucs::translation::{ConcreteLookup, GeneticCode};
    /// use Nuc::{A, C, G, T};
    ///
    /// let table = Amino::arr(b"ACDEFGHIKLMNOPQRSTUVWY*ACDEFGHIKLMNOPQRSTUVWY*ACDEFGHIKLMNOPQRS*");
    /// let lookup = ConcreteLookup::from_table(&table).to_ambi_lookup();
    /// assert_eq!((&lookup).translate([A, T, G]), Amino::Q);
    /// let lookup_rc = lookup.reverse_complement();
    /// // ATG reverse-complemented is CAT, so...
    /// assert_eq!((&lookup_rc).translate([C, A, T]), Amino::Q);
    /// ```
    #[must_use]
    pub const fn reverse_complement(&self) -> Self {
        let mut ambi_lookup = [AmbiAmino::X; _];
        // As before, this could be flattened into a single unnested loop, but this nested
        // loop results in much sparser work.
        let mut n1 = 0x100;
        while n1 <= 0xf00 {
            let mut n2 = 0x010;
            while n2 <= 0x0f0 {
                let mut n3 = 0x001;
                while n3 <= 0x00f {
                    let n1_n2_n3 = n1 | n2 | n3;
                    ambi_lookup[n1_n2_n3] = self.0[reverse_complement_index(n1_n2_n3)];
                    n3 += 0x001;
                }
                n2 += 0x010;
            }
            n1 += 0x100;
        }
        Self(ambi_lookup)
    }
}

impl GeneticCode for &AmbiLookup {
    #[inline(always)]
    fn translate_concrete_codon(&self, codon: [Nuc; 3]) -> Amino {
        let [n1, n2, n3] = codon;
        let amino = self.translate_ambiguous_codon([n1.into(), n2.into(), n3.into()]);
        amino
            .try_into()
            .expect("BUG: to_ambi_lookup mapped concrete codon to ambi amino")
    }

    #[inline(always)]
    fn translate_ambiguous_codon(&self, codon: [AmbiNuc; 3]) -> AmbiAmino {
        let [n1, n2, n3] = codon;
        self.0[((n1 as usize) << 8) | ((n2 as usize) << 4) | (n3 as usize)]
    }
}

impl std::fmt::Debug for AmbiLookup {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt_genetic_code(&self, f)
    }
}

#[allow(
    clippy::cast_possible_truncation,
    reason = "valid lookup indexes are 12 bits"
)]
const fn reverse_complement_index(idx: usize) -> usize {
    ((idx as u16).reverse_bits() >> 4) as usize
}

fn fmt_genetic_code(
    genetic_code: &impl GeneticCode,
    f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
    let mut map = f.debug_map();
    for n1 in Nuc::ALL {
        for n2 in Nuc::ALL {
            for n3 in Nuc::ALL {
                let codon = [n1, n2, n3];
                map.entry(&codon.display(), &genetic_code.translate([n1, n2, n3]));
            }
        }
    }
    map.finish()
}

/// Standard code
pub const NCBI1: &FullLookup = &ncbi(0);
/// Vertebrate mitochondrial code
pub const NCBI2: &FullLookup = &ncbi(1);
/// Yeast mitochondrial code
pub const NCBI3: &FullLookup = &ncbi(2);
/// Mold, protozoan, and coelenterate mitochondrial code as well as mycoplasma and spiroplasma code
pub const NCBI4: &FullLookup = &ncbi(3);
/// Invertebrate mitochondrial code
pub const NCBI5: &FullLookup = &ncbi(4);
/// Ciliate dasycladacean and hexamita nuclear code
pub const NCBI6: &FullLookup = &ncbi(5);
/// Echinoderm and flatworm mitochondrial code
pub const NCBI9: &FullLookup = &ncbi(6);
/// Euplotid nuclear code
pub const NCBI10: &FullLookup = &ncbi(7);
/// Bacterial, archaeal and plant plastid code
pub const NCBI11: &FullLookup = &ncbi(8);
/// Alternative yeast nuclear code
pub const NCBI12: &FullLookup = &ncbi(9);
/// Ascidian mitochondrial code
pub const NCBI13: &FullLookup = &ncbi(10);
/// Alternative flatworm mitochondrial code
pub const NCBI14: &FullLookup = &ncbi(11);
/// Blepharisma nuclear code
pub const NCBI15: &FullLookup = &ncbi(12);
/// Chlorophycean mitochondrial code
pub const NCBI16: &FullLookup = &ncbi(13);
/// Trematode mitochondrial code
pub const NCBI21: &FullLookup = &ncbi(14);
/// Scenedesmus obliquus mitochondrial code
pub const NCBI22: &FullLookup = &ncbi(15);
/// Thraustochytrium mitochondrial code
pub const NCBI23: &FullLookup = &ncbi(16);
/// Pterobranchia mitochondrial code
pub const NCBI24: &FullLookup = &ncbi(17);
/// Candidate division SR1 and gracilibacteria code
pub const NCBI25: &FullLookup = &ncbi(18);
/// Pachysolen tannophilus nuclear code
pub const NCBI26: &FullLookup = &ncbi(19);
/// Karyorelict nuclear code
pub const NCBI27: &FullLookup = &ncbi(20);
/// Condylostoma nuclear code
pub const NCBI28: &FullLookup = &ncbi(21);
/// Mesodinium nuclear code
pub const NCBI29: &FullLookup = &ncbi(22);
/// Peritrich nuclear code
pub const NCBI30: &FullLookup = &ncbi(23);
/// Blastocrithidia nuclear code
pub const NCBI31: &FullLookup = &ncbi(24);
/// Balanophoraceae plastid code
pub const NCBI32: &FullLookup = &ncbi(25);
/// Cephalodiscidae mitochondrial code
pub const NCBI33: &FullLookup = &ncbi(26);
/// Enterosoma code
pub const NCBI34: &FullLookup = &ncbi(27);
/// Peptacetobacter code
pub const NCBI35: &FullLookup = &ncbi(28);
/// Anaerococcus and onthovivens code
pub const NCBI36: &FullLookup = &ncbi(29);
/// Absconditabacterales genetic code
pub const NCBI37: &FullLookup = &ncbi(30);

const fn ncbi(i: usize) -> FullLookup {
    FullLookup::from_table(&NCBI_DATA[i])
}

macro_rules! aminos {
    [ $( [$( $c:tt )+ ]),+ $(,)? ] => {{
        [$(
            [$(to_amino!($c)),+]
        ),+]
    }}
}

macro_rules! to_amino {
    (*) => {{ Amino::Stop }};
    ($v:tt) => {{ Amino::$v }};
}

const NCBI_DATA: [[Amino; 64]; 31] = transpose(aminos! [
    // Tables are obtained from: https://en.wikipedia.org/wiki/List_of_genetic_codes
    //         1  2  3  4  5  6  9 10 11 12 13 14 15 16 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
    /* AAA */ [K  K  K  K  K  K  N  K  K  K  K  N  K  K  N  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K],
    /* AAC */ [N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N],
    /* AAG */ [K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K  K],
    /* AAT */ [N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N],
    /* ACA */ [T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T],
    /* ACC */ [T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T],
    /* ACG */ [T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T],
    /* ACT */ [T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T  T],
    /* AGA */ [R  *  R  R  S  R  S  R  R  R  G  S  R  R  S  R  R  S  R  R  R  R  R  R  R  R  S  R  R  R  R],
    /* AGC */ [S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S],
    /* AGG */ [R  *  R  R  S  R  S  R  R  R  G  S  R  R  S  R  R  K  R  R  R  R  R  R  R  R  K  M  R  R  R],
    /* AGT */ [S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S],
    /* ATA */ [I  M  M  I  M  I  I  I  I  I  M  I  I  I  M  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I],
    /* ATC */ [I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I],
    /* ATG */ [M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M],
    /* ATT */ [I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I  I],
    /* CAA */ [Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q],
    /* CAC */ [H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H],
    /* CAG */ [Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q  Q],
    /* CAT */ [H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H],
    /* CCA */ [P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P],
    /* CCC */ [P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P],
    /* CCG */ [P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P],
    /* CCT */ [P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P  P],
    /* CGA */ [R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  W],
    /* CGC */ [R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R],
    /* CGG */ [R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  Q  W  W],
    /* CGT */ [R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R],
    /* CTA */ [L  L  T  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L],
    /* CTC */ [L  L  T  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L],
    /* CTG */ [L  L  T  L  L  L  L  L  L  S  L  L  L  L  L  L  L  L  L  A  L  L  L  L  L  L  L  L  L  L  L],
    /* CTT */ [L  L  T  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L],
    /* GAA */ [E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E],
    /* GAC */ [D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D],
    /* GAG */ [E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E],
    /* GAT */ [D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D],
    /* GCA */ [A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A],
    /* GCC */ [A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A],
    /* GCG */ [A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A],
    /* GCT */ [A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A],
    /* GGA */ [G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G],
    /* GGC */ [G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G],
    /* GGG */ [G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G],
    /* GGT */ [G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G  G],
    /* GTA */ [V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V],
    /* GTC */ [V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V],
    /* GTG */ [V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V],
    /* GTT */ [V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V],
    /* TAA */ [*  *  *  *  *  Q  *  *  *  *  *  Y  *  *  *  *  *  *  *  *  Q  Q  Y  E  E  *  Y  *  *  *  *],
    /* TAC */ [Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y],
    /* TAG */ [*  *  *  *  *  Q  *  *  *  *  *  *  Q  L  *  L  *  *  *  *  Q  Q  Y  E  E  W  *  *  *  *  *],
    /* TAT */ [Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y],
    /* TCA */ [S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  *  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S],
    /* TCC */ [S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S],
    /* TCG */ [S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S],
    /* TCT */ [S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S  S],
    /* TGA */ [*  W  W  W  W  *  W  C  *  *  W  W  *  *  W  *  *  W  G  *  W  W  *  *  W  *  W  *  *  *  G],
    /* TGC */ [C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C],
    /* TGG */ [W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W  W],
    /* TGT */ [C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C],
    /* TTA */ [L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  *  L  L  L  L  L  L  L  L  L  L  L  L  L  L],
    /* TTC */ [F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F],
    /* TTG */ [L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L  L],
    /* TTT */ [F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F  F],
]);

const fn transpose<const N: usize, const M: usize>(table: [[Amino; N]; M]) -> [[Amino; M]; N] {
    let mut output = [[Amino::A; M]; N];
    let mut i = 0;
    while i < N {
        let mut j = 0;
        while j < M {
            output[i][j] = table[j][i];
            j += 1;
        }
        i += 1;
    }
    output
}

/// Translation of DNA slice via a [`GeneticCode`].
///
/// The translation isn't actually executed until methods such as [`to_seq`](Self::to_seq)
/// are invoked. Alternatively, this can be converted to an iterator, though the resulting
/// translation is slower.
#[derive(Clone, Copy)]
pub struct Translation<'a, N, G> {
    pub(crate) dna: &'a [N],
    pub(crate) genetic_code: G,
}

impl<'a, N: Nucleotide, G: GeneticCode> Translation<'a, N, G> {
    /// Translate the reverse complement of the DNA instead.
    ///
    /// For precomputed genetic codes such as [`NCBI1`], this is *much* faster
    /// than reverse-complementing the DNA and translating it as separate steps.
    /// The methods of [`RcTranslation`] are much the same as [`Translation`].
    pub fn reverse_complemented(self) -> RcTranslation<'a, N, G> {
        let Self { dna, genetic_code } = self;
        RcTranslation { dna, genetic_code }
    }

    /// Perform translation, returning the peptide as [`Seq<Vec<T>>`].
    ///
    /// For large sequences, this is usually much faster than populating directly from an iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{DnaSliceExt, NCBI1, Nuc};
    ///
    /// let dna = Nuc::arr(b"TATGCGAGAAACA");
    /// let peptide = dna.translated_by(NCBI1).to_seq();
    /// assert_eq!(peptide, "YARN");
    /// ```
    pub fn to_seq(&self) -> Seq<Vec<N::Amino>> {
        self.into()
    }

    /// Perform translation, returning the peptide as [`Seq<[T; M]>`](Seq).
    ///
    /// # Panics
    ///
    /// Panics if the number of codons to be translated is different from the returned array.
    ///
    /// If a non-panicking version is desired, use [`TryInto`].
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{DnaSliceExt, NCBI1, Nuc};
    ///
    /// let dna = Nuc::arr(b"TATGCGAGAAACA");
    /// let peptide = dna.translated_by(NCBI1).to_array_seq::<4>();
    /// assert_eq!(peptide, "YARN");
    /// ```
    pub fn to_array_seq<const M: usize>(&self) -> Seq<[N::Amino; M]> {
        self.try_into()
            .expect("peptide length must match output array")
    }

    /// Perform translation, returning the peptide as [`Vec<T>`].
    ///
    /// For large sequences, this is usually much faster than populating directly from an iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{DnaSliceExt, NCBI1, Nuc, Seq};
    ///
    /// let dna = Nuc::arr(b"TATGCGAGAAACA");
    /// let peptide = dna.translated_by(NCBI1).to_vec();
    /// assert_eq!(Seq(peptide), "YARN");
    /// ```
    pub fn to_vec(&self) -> Vec<N::Amino> {
        self.into()
    }

    /// Perform translation, returning the peptide as [`[T; M]`](array).
    ///
    /// # Panics
    ///
    /// Panics if the number of codons to be translated is different from the returned array.
    ///
    /// If a non-panicking version is desired, use [`TryInto`].
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{DnaSliceExt, NCBI1, Nuc, Seq};
    ///
    /// let dna = Nuc::arr(b"TATGCGAGAAACA");
    /// let peptide = dna.translated_by(NCBI1).to_array::<4>();
    /// assert_eq!(Seq(peptide), "YARN");
    /// ```
    pub fn to_array<const M: usize>(&self) -> [N::Amino; M] {
        self.try_into()
            .expect("peptide length must match output array")
    }

    /// Perform translation, putting the peptide in the given buffer.
    ///
    /// For large sequences, this is usually much faster than populating directly from an iterator.
    ///
    /// # Errors
    ///
    /// If `buf`'s length doesn't match the translation's [`len`](Self::len), then a
    /// [`TryFillBufLenError`] error is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{DnaSliceExt, NCBI1, Nuc, Seq};
    ///
    /// let dna = Nuc::arr(b"TATGCGAGAAACA");
    /// let mut peptide: [_; 4] = Default::default();
    /// dna.translated_by(NCBI1).try_fill(&mut peptide).unwrap();
    /// assert_eq!(Seq(peptide), "YARN");
    /// ```
    pub fn try_fill(&self, buf: &mut [N::Amino]) -> Result<(), TryFillBufLenError> {
        const CHUNK_LEN: usize = 16;
        let codons = self.dna.as_codons();
        if codons.len() != buf.len() {
            return Err(TryFillBufLenError(()));
        }
        let (codon_chunks, codon_remainder) = codons.as_chunks::<CHUNK_LEN>();
        let (amino_chunks, amino_remainder) = buf.as_chunks_mut::<CHUNK_LEN>();
        for (aminos, codons) in std::iter::zip(amino_chunks, codon_chunks) {
            for (amino, codon) in std::iter::zip(aminos, codons) {
                *amino = self.genetic_code.translate(*codon);
            }
        }
        for (amino, codon) in std::iter::zip(amino_remainder, codon_remainder) {
            *amino = self.genetic_code.translate(*codon);
        }
        Ok(())
    }

    /// Return the number of amino acids in the translation.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{DnaSliceExt, NCBI1, Nuc};
    ///
    /// let translation = [Nuc::A; 20].translated_by(NCBI1);
    /// assert_eq!(translation.len(), 6);
    /// ```
    pub fn len(&self) -> usize {
        self.dna.as_codons().len()
    }

    /// Return `true` if the translation produces no amino acids.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{DnaSliceExt, NCBI1, Nuc};
    ///
    /// assert!(Nuc::arr(b"AT").translated_by(NCBI1).is_empty());
    /// assert!(!Nuc::arr(b"ACT").translated_by(NCBI1).is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    // not public until we make the types concrete; limited by borrowing G
    fn iter(&self) -> impl Iterator<Item = N::Amino> + Clone {
        self.dna
            .iter()
            .codons()
            .map(|c| self.genetic_code.translate(c))
    }
}

impl<'a, N: Nucleotide, G: GeneticCode> IntoIterator for Translation<'a, N, G> {
    type Item = N::Amino;
    type IntoIter = Translated<G, Codons<N, std::slice::Iter<'a, N>>>;

    fn into_iter(self) -> Self::IntoIter {
        self.dna.iter().translated_by(self.genetic_code)
    }
}

impl<N: Nucleotide, G: GeneticCode> PartialEq<&str> for Translation<'_, N, G> {
    fn eq(&self, rhs: &&str) -> bool {
        self == *rhs
    }
}

impl<N: Nucleotide, G: GeneticCode> PartialEq<str> for Translation<'_, N, G> {
    fn eq(&self, rhs: &str) -> bool {
        self.iter().map(Ok).eq(iter_symbols(rhs))
    }
}

impl<N: Nucleotide, G: GeneticCode> Display for Translation<'_, N, G> {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        Display::fmt(&crate::iter::Display::new(self.iter()), f)
    }
}

impl<N: Nucleotide, G: GeneticCode> Debug for Translation<'_, N, G> {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        // It's tempting to instead show the source DNA and genetic code,
        // but this is more useful with `assert_eq`.
        f.debug_tuple("Translation")
            .field(&crate::iter::Display::new(self.iter()))
            .finish()
    }
}

impl<'a, N, G> From<Translation<'a, N, G>> for Vec<N::Amino>
where
    N: Nucleotide,
    G: GeneticCode,
{
    fn from(translation: Translation<'a, N, G>) -> Vec<N::Amino> {
        (&translation).into()
    }
}

impl<'a, N, G> From<&Translation<'a, N, G>> for Vec<N::Amino>
where
    N: Nucleotide,
    G: GeneticCode,
{
    fn from(translation: &Translation<'a, N, G>) -> Vec<N::Amino> {
        let mut peptide = vec![Default::default(); translation.len()];
        translation.try_fill(&mut peptide).unwrap();
        peptide
    }
}

impl<'a, N, G> From<Translation<'a, N, G>> for Seq<Vec<N::Amino>>
where
    N: Nucleotide,
    G: GeneticCode,
{
    fn from(translation: Translation<'a, N, G>) -> Seq<Vec<N::Amino>> {
        (&translation).into()
    }
}

impl<'a, N, G> From<&Translation<'a, N, G>> for Seq<Vec<N::Amino>>
where
    N: Nucleotide,
    G: GeneticCode,
{
    fn from(translation: &Translation<'a, N, G>) -> Seq<Vec<N::Amino>> {
        Seq(translation.into())
    }
}

impl<'a, const M: usize, N, G> TryFrom<Translation<'a, N, G>> for [N::Amino; M]
where
    N: Nucleotide,
    G: GeneticCode,
{
    type Error = std::array::TryFromSliceError;

    fn try_from(translation: Translation<'a, N, G>) -> Result<[N::Amino; M], Self::Error> {
        (&translation).try_into()
    }
}

impl<'a, const M: usize, N, G> TryFrom<&Translation<'a, N, G>> for [N::Amino; M]
where
    N: Nucleotide,
    G: GeneticCode,
{
    type Error = std::array::TryFromSliceError;

    fn try_from(translation: &Translation<'a, N, G>) -> Result<[N::Amino; M], Self::Error> {
        let mut buf = [Default::default(); _];
        if translation.try_fill(&mut buf).is_err() {
            // Trigger error (uses appropriate sizes for future-proofing)
            let peptide_sized_slice = &translation.dna[0..translation.len()];
            let err = <[_; M]>::try_from(peptide_sized_slice).unwrap_err();
            return Err(err);
        }
        Ok(buf)
    }
}

impl<'a, const M: usize, N, G> TryFrom<Translation<'a, N, G>> for Seq<[N::Amino; M]>
where
    N: Nucleotide,
    G: GeneticCode,
{
    type Error = std::array::TryFromSliceError;

    fn try_from(translation: Translation<'a, N, G>) -> Result<Seq<[N::Amino; M]>, Self::Error> {
        (&translation).try_into()
    }
}

impl<'a, const M: usize, N, G> TryFrom<&Translation<'a, N, G>> for Seq<[N::Amino; M]>
where
    N: Nucleotide,
    G: GeneticCode,
{
    type Error = std::array::TryFromSliceError;

    fn try_from(translation: &Translation<'a, N, G>) -> Result<Seq<[N::Amino; M]>, Self::Error> {
        translation.try_into().map(Seq)
    }
}

/// Reverse-complemented translation of DNA slice via a [`GeneticCode`].
///
/// The translation isn't actually executed until methods such as [`to_seq`](Self::to_seq)
/// are invoked. Alternatively, this can be converted to an iterator, though the resulting
/// translation is slower.
#[derive(Clone, Copy)]
pub struct RcTranslation<'a, N, G> {
    dna: &'a [N],
    genetic_code: G,
}

impl<N: Nucleotide, G: GeneticCode> RcTranslation<'_, N, G> {
    /// Perform reverse-complemented translation, returning the peptide as [`Seq<Vec<T>>`].
    ///
    /// For large sequences, this is usually much faster than populating directly from an iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{AmbiNuc, DnaSliceExt, NCBI1};
    ///
    /// let dna = AmbiNuc::arr(b"NGCACCGCTAGGTACTGGCGAA");
    /// let peptide = dna.translated_by(NCBI1).reverse_complemented().to_seq();
    /// assert_eq!(peptide, "FAST*RC");
    /// ```
    pub fn to_seq(&self) -> Seq<Vec<N::Amino>> {
        self.into()
    }

    /// Perform reverse-complemented translation, returning the peptide as [`Seq<[T; M]>`](Seq).
    ///
    /// # Panics
    ///
    /// Panics if the number of codons to be translated is different from the returned array.
    ///
    /// If a non-panicking version is desired, use [`TryInto`].
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{AmbiNuc, DnaSliceExt, NCBI1};
    ///
    /// let dna = AmbiNuc::arr(b"NGCACCGCTAGGTACTGGCGAA");
    /// let peptide = dna.translated_by(NCBI1).reverse_complemented().to_array_seq::<7>();
    /// assert_eq!(peptide, "FAST*RC");
    /// ```
    pub fn to_array_seq<const M: usize>(&self) -> Seq<[N::Amino; M]> {
        self.try_into()
            .expect("peptide length must match output array")
    }

    /// Perform reverse-complemented translation, returning the peptide as [`Vec<T>`].
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{AmbiNuc, DnaSliceExt, NCBI1, Seq};
    ///
    /// let dna = AmbiNuc::arr(b"NGCACCGCTAGGTACTGGCGAA");
    /// let peptide = dna.translated_by(NCBI1).reverse_complemented().to_vec();
    /// assert_eq!(Seq(peptide), "FAST*RC");
    /// ```
    pub fn to_vec(&self) -> Vec<N::Amino> {
        self.into()
    }

    /// Perform reverse-complemented translation, returning the peptide as [`[T; M]`](array).
    ///
    /// # Panics
    ///
    /// Panics if the number of codons to be translated is different from the returned array.
    ///
    /// If a non-panicking version is desired, use [`TryInto`].
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{AmbiNuc, DnaSliceExt, NCBI1, Seq};
    ///
    /// let dna = AmbiNuc::arr(b"NGCACCGCTAGGTACTGGCGAA");
    /// let peptide = dna.translated_by(NCBI1).reverse_complemented().to_array::<7>();
    /// assert_eq!(Seq(peptide), "FAST*RC");
    /// ```
    pub fn to_array<const M: usize>(&self) -> [N::Amino; M] {
        self.try_into()
            .expect("peptide length must match output array")
    }

    /// Perform reverse-complemented translation, putting the peptide in the given buffer.
    ///
    /// For large sequences, this is usually much faster than populating directly from an iterator.
    ///
    /// # Errors
    ///
    /// If `buf`'s length doesn't match the translation's [`len`](Self::len), then a
    /// [`TryFillBufLenError`] error is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{AmbiNuc, DnaSliceExt, NCBI1, Seq};
    ///
    /// let dna = AmbiNuc::arr(b"NGCACCGCTAGGTACTGGCGAA");
    /// let mut peptide: [_; 7] = Default::default();
    /// dna.translated_by(NCBI1).reverse_complemented().try_fill(&mut peptide).unwrap();
    /// assert_eq!(Seq(peptide), "FAST*RC");
    /// ```
    pub fn try_fill(&self, buf: &mut [N::Amino]) -> Result<(), TryFillBufLenError> {
        const CHUNK_LEN: usize = 16;
        let codons = self.dna.as_rcodons();
        if codons.len() != buf.len() {
            return Err(TryFillBufLenError(()));
        }
        let (codon_chunks, codon_remainder) = codons.as_chunks::<CHUNK_LEN>();
        let (amino_remainder, amino_chunks) = buf.as_rchunks_mut::<CHUNK_LEN>();
        for (aminos, codons) in amino_chunks.iter_mut().rev().zip(codon_chunks) {
            for (amino, codon) in aminos.iter_mut().rev().zip(codons) {
                *amino = self.genetic_code.translate_rc(*codon);
            }
        }
        for (amino, codon) in amino_remainder.iter_mut().rev().zip(codon_remainder) {
            *amino = self.genetic_code.translate_rc(*codon);
        }
        Ok(())
    }

    /// Return the number of amino acids in the translation.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{DnaSliceExt, NCBI1, Nuc};
    ///
    /// let translation = [Nuc::A; 20].translated_by(NCBI1).reverse_complemented();
    /// assert_eq!(translation.len(), 6);
    /// ```
    pub fn len(&self) -> usize {
        self.dna.as_rcodons().len()
    }

    /// Return `true` if the translation produces no amino acids.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{DnaSliceExt, NCBI1, Nuc};
    ///
    /// assert!(Nuc::arr(b"AT").translated_by(NCBI1).reverse_complemented().is_empty());
    /// assert!(!Nuc::arr(b"ACT").translated_by(NCBI1).reverse_complemented().is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    // not public until we make the types concrete; limited by borrowing G
    fn iter(&self) -> impl Iterator<Item = N::Amino> + Clone {
        self.dna
            .iter()
            .reverse_complemented()
            .codons()
            .map(|c| self.genetic_code.translate(c))
    }
}

impl<'a, N: Nucleotide, G: GeneticCode> IntoIterator for RcTranslation<'a, N, G> {
    type Item = N::Amino;
    type IntoIter = Translated<G, Codons<N, Complemented<N, Rev<std::slice::Iter<'a, N>>>>>;

    fn into_iter(self) -> Self::IntoIter {
        self.dna
            .iter()
            .reverse_complemented()
            .translated_by(self.genetic_code)
    }
}

impl<N: Nucleotide, G: GeneticCode> PartialEq<&str> for RcTranslation<'_, N, G> {
    fn eq(&self, rhs: &&str) -> bool {
        self == *rhs
    }
}

impl<N: Nucleotide, G: GeneticCode> PartialEq<str> for RcTranslation<'_, N, G> {
    fn eq(&self, rhs: &str) -> bool {
        self.iter().map(Ok).eq(iter_symbols(rhs))
    }
}

impl<N: Nucleotide, G: GeneticCode> Display for RcTranslation<'_, N, G> {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        Display::fmt(&crate::iter::Display::new(self.iter()), f)
    }
}

impl<N: Nucleotide, G: GeneticCode> Debug for RcTranslation<'_, N, G> {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        // It's tempting to instead show the source DNA and genetic code,
        // but this is more useful with `assert_eq`.
        f.debug_tuple("RcTranslation")
            .field(&crate::iter::Display::new(self.iter()))
            .finish()
    }
}

impl<'a, N, G> From<RcTranslation<'a, N, G>> for Vec<N::Amino>
where
    N: Nucleotide,
    G: GeneticCode,
{
    fn from(translation: RcTranslation<'a, N, G>) -> Vec<N::Amino> {
        (&translation).into()
    }
}

impl<'a, N, G> From<&RcTranslation<'a, N, G>> for Vec<N::Amino>
where
    N: Nucleotide,
    G: GeneticCode,
{
    fn from(translation: &RcTranslation<'a, N, G>) -> Vec<N::Amino> {
        let mut peptide = vec![Default::default(); translation.len()];
        translation.try_fill(&mut peptide).unwrap();
        peptide
    }
}

impl<'a, N, G> From<RcTranslation<'a, N, G>> for Seq<Vec<N::Amino>>
where
    N: Nucleotide,
    G: GeneticCode,
{
    fn from(translation: RcTranslation<'a, N, G>) -> Seq<Vec<N::Amino>> {
        (&translation).into()
    }
}

impl<'a, N, G> From<&RcTranslation<'a, N, G>> for Seq<Vec<N::Amino>>
where
    N: Nucleotide,
    G: GeneticCode,
{
    fn from(translation: &RcTranslation<'a, N, G>) -> Seq<Vec<N::Amino>> {
        Seq(translation.into())
    }
}

impl<'a, const M: usize, N, G> TryFrom<RcTranslation<'a, N, G>> for [N::Amino; M]
where
    N: Nucleotide,
    G: GeneticCode,
{
    type Error = std::array::TryFromSliceError;

    fn try_from(translation: RcTranslation<'a, N, G>) -> Result<[N::Amino; M], Self::Error> {
        (&translation).try_into()
    }
}

impl<'a, const M: usize, N, G> TryFrom<&RcTranslation<'a, N, G>> for [N::Amino; M]
where
    N: Nucleotide,
    G: GeneticCode,
{
    type Error = std::array::TryFromSliceError;

    fn try_from(translation: &RcTranslation<'a, N, G>) -> Result<[N::Amino; M], Self::Error> {
        let mut buf = [Default::default(); _];
        if translation.try_fill(&mut buf).is_err() {
            // Trigger error (uses appropriate sizes for future-proofing)
            let peptide_sized_slice = &translation.dna[0..translation.len()];
            let err = <[_; M]>::try_from(peptide_sized_slice).unwrap_err();
            return Err(err);
        }
        Ok(buf)
    }
}

impl<'a, const M: usize, N, G> TryFrom<RcTranslation<'a, N, G>> for Seq<[N::Amino; M]>
where
    N: Nucleotide,
    G: GeneticCode,
{
    type Error = std::array::TryFromSliceError;

    fn try_from(translation: RcTranslation<'a, N, G>) -> Result<Seq<[N::Amino; M]>, Self::Error> {
        (&translation).try_into()
    }
}

impl<'a, const M: usize, N, G> TryFrom<&RcTranslation<'a, N, G>> for Seq<[N::Amino; M]>
where
    N: Nucleotide,
    G: GeneticCode,
{
    type Error = std::array::TryFromSliceError;

    fn try_from(translation: &RcTranslation<'a, N, G>) -> Result<Seq<[N::Amino; M]>, Self::Error> {
        translation.try_into().map(Seq)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
    #[test]
    fn compare_fast_lookup_against_reference_implementation() {
        // In order to be able to build `FullLookup`s for all NCBI tables at compile-time
        // in 1 second, the ambiguous lookup generation code is convoluted. (doing things the
        // obvious way would result in `nucs` taking 30 seconds to compile) To improve confidence,
        // we check that for all codons and NCBI tables, `FullLookup` gives the same results as
        // the simpler implementations provided by `&[Amino; 64]` and `GeneticCode`.
        for raw in &NCBI_DATA {
            let fast = &FullLookup::from_table(raw);
            assert_genetic_codes_eq(&fast, &raw);
        }
    }

    #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
    #[test]
    fn fast_lookup_can_be_built_from_other_genetic_code() {
        let new = &FullLookup::from_genetic_code(&NCBI1);
        assert_genetic_codes_eq(&new, &NCBI1);
    }

    #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
    #[test]
    fn fast_lookup_conversion_roundtrips() {
        let table = &NCBI_DATA[0];
        assert_eq!(&FullLookup::from_table(table).to_table(), table);
    }

    #[test]
    fn fast_lookup_reverse_complement() {
        let dna = Nuc::arr(b"ATCTTCGGGGGGAATTAAAAACTAATAAAGTTCAACAATGGTTGGCATCTCTTCCCGGGG");
        let peptide = dna.translated_by(NCBI1).reverse_complemented().to_seq();
        assert_eq!(peptide, "PREEMPTIVELY*FLIPPED");
    }

    #[test]
    fn exhaustively_test_reverse_complement_concrete_lookups() {
        for n1 in Nuc::ALL {
            for n2 in Nuc::ALL {
                for n3 in Nuc::ALL {
                    let codon = [n1, n2, n3];
                    let mut codon_rc = codon;
                    codon_rc.reverse_complement();
                    assert_eq!(
                        NCBI1.translate_rc(codon),
                        NCBI1.translate(codon_rc),
                        "Mismatch for {codon:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn exhaustively_test_reverse_complement_ambiguous_lookups() {
        for n1 in AmbiNuc::ALL {
            for n2 in AmbiNuc::ALL {
                for n3 in AmbiNuc::ALL {
                    let codon = [n1, n2, n3];
                    let mut codon_rc = codon;
                    codon_rc.reverse_complement();
                    assert_eq!(
                        NCBI1.translate_rc(codon),
                        NCBI1.translate(codon_rc),
                        "Mismatch for {codon:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn translation_eq() {
        let dna = Nuc::arr(b"AAAACCCGGT");
        let translation = dna.translated_by(NCBI1);
        assert_eq!(translation, "KTR");
        assert_eq!(translation.reverse_complemented(), "TGF");
    }

    #[test]
    fn translation_display() {
        let dna = Nuc::arr(b"AAAACCCGGT");
        let translation = dna.translated_by(NCBI1);
        assert_eq!(translation.to_string(), "KTR");
        assert_eq!(translation.reverse_complemented().to_string(), "TGF");
    }

    fn assert_genetic_codes_eq(g1: &impl GeneticCode, g2: &impl GeneticCode) {
        for n1 in Nuc::ALL {
            for n2 in Nuc::ALL {
                for n3 in Nuc::ALL {
                    let codon = [n1, n2, n3];
                    assert_eq!(g1.translate(codon), g2.translate(codon));
                }
            }
        }
        for n1 in AmbiNuc::ALL {
            for n2 in AmbiNuc::ALL {
                for n3 in AmbiNuc::ALL {
                    let codon = [n1, n2, n3];
                    assert_eq!(g1.translate(codon), g2.translate(codon));
                }
            }
        }
    }
}