nucs 0.3.1

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
use std::cmp::Ordering;
use std::fmt::{Display, Formatter};
use std::hash::Hash;
use std::num::NonZeroU32;
use std::ops::{BitOr, BitOrAssign};
use std::str::FromStr;

use crate::error::ParseSymbolError;
use crate::iter::AmbiAminoIter;
use crate::{Seq, Symbol};

/// Amino acid
///
/// For details, see: <https://en.wikipedia.org/wiki/FASTA_format#Sequence_representation>
///
/// [`Amino`]s are ordered by the value of their ASCII representation.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Amino {
    /// Translation stop
    #[default]
    Stop = b'*',
    /// Alanine
    A = b'A',
    /// Cysteine
    C = b'C',
    /// Aspartic acid
    D = b'D',
    /// Glutamic acid
    E = b'E',
    /// Phenylalanine
    F = b'F',
    /// Glycine
    G = b'G',
    /// Histidine
    H = b'H',
    /// Isoleucine
    I = b'I',
    /// Lysine
    K = b'K',
    /// Leucine
    L = b'L',
    /// Methionine
    M = b'M',
    /// Asparagine
    N = b'N',
    /// Pyrrolysine
    O = b'O',
    /// Proline,
    P = b'P',
    /// Glutamine
    Q = b'Q',
    /// Arginine
    R = b'R',
    /// Serine
    S = b'S',
    /// Threonine
    T = b'T',
    /// Selenocysteine
    U = b'U',
    /// Valine
    V = b'V',
    /// Tryptophan
    W = b'W',
    /// Tyrosine
    Y = b'Y',
}

impl Amino {
    /// All [`Amino`]s sorted in ascending order
    pub const ALL: [Self; 23] = Self::arr(b"*ACDEFGHIKLMNOPQRSTUVWY");

    /// Return uppercase string representation
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::Amino;
    ///
    /// assert_eq!(Amino::A.to_str(), "A");
    /// assert_eq!(Amino::Stop.to_str(), "*");
    /// ```
    #[must_use]
    pub fn to_str(self) -> &'static str {
        match self {
            Self::Stop => "*",

            Self::A => "A",
            Self::C => "C",
            Self::D => "D",
            Self::E => "E",
            Self::F => "F",
            Self::G => "G",
            Self::H => "H",
            Self::I => "I",
            Self::K => "K",
            Self::L => "L",
            Self::M => "M",
            Self::N => "N",
            Self::O => "O",
            Self::P => "P",
            Self::Q => "Q",
            Self::R => "R",
            Self::S => "S",
            Self::T => "T",
            Self::U => "U",
            Self::V => "V",
            Self::W => "W",
            Self::Y => "Y",
        }
    }

    /// Construct from ASCII representation
    ///
    /// # Errors
    ///
    /// Returns [`ParseSymbolError`] if the given byte isn't `A`, `C`, `D`, `E`, `F`,
    /// `G`, `H`, `I`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`, `U`, `V`, `W`, `Y`
    /// or `*` (case-insensitive).
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::Amino;
    ///
    /// assert_eq!(Amino::from_ascii(b'A'), Ok(Amino::A));
    /// assert_eq!(Amino::from_ascii(b'*'), Ok(Amino::Stop));
    /// assert!(Amino::from_ascii(b'B').is_err());
    /// ```
    pub const fn from_ascii(ascii: u8) -> Result<Self, ParseSymbolError> {
        Ok(match ascii {
            b'*' => Self::Stop,

            b'A' | b'a' => Self::A,
            b'C' | b'c' => Self::C,
            b'D' | b'd' => Self::D,
            b'E' | b'e' => Self::E,
            b'F' | b'f' => Self::F,
            b'G' | b'g' => Self::G,
            b'H' | b'h' => Self::H,
            b'I' | b'i' => Self::I,
            b'K' | b'k' => Self::K,
            b'L' | b'l' => Self::L,
            b'M' | b'm' => Self::M,
            b'N' | b'n' => Self::N,
            b'O' | b'o' => Self::O,
            b'P' | b'p' => Self::P,
            b'Q' | b'q' => Self::Q,
            b'R' | b'r' => Self::R,
            b'S' | b's' => Self::S,
            b'T' | b't' => Self::T,
            b'U' | b'u' => Self::U,
            b'V' | b'v' => Self::V,
            b'W' | b'w' => Self::W,
            b'Y' | b'y' => Self::Y,

            _ => return Err(ParseSymbolError::new::<Self>()),
        })
    }

    /// Return uppercase ASCII representation
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::Amino;
    ///
    /// assert_eq!(Amino::A.to_ascii(), b'A');
    /// assert_eq!(Amino::Stop.to_ascii(), b'*');
    /// ```
    #[must_use]
    pub fn to_ascii(self) -> u8 {
        self.to_str().as_bytes()[0]
    }

    /// Construct [`Amino`] array from literal without allocating.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::Amino;
    ///
    /// let aas1 = Amino::arr(b"ACME*WIDGETS");
    /// // ...is shorthand for...
    /// use Amino::{A, C, M, E, Stop, W, I, D, G, T, S};
    /// let aas2 = [A, C, M, E, Stop, W, I, D, G, E, T, S];
    ///
    /// assert_eq!(aas1, aas2);
    /// ```
    ///
    /// # Panics
    ///
    /// This panics if the supplied literal isn't valid. **Whitespace is NOT allowed**
    /// because the returned array must have the same length.
    #[must_use]
    #[track_caller]
    pub const fn arr<const N: usize>(literal: &[u8; N]) -> [Amino; N] {
        let mut aas = [Self::A; N];
        let mut i = 0;
        while i < literal.len() {
            let Ok(aa) = Self::from_ascii(literal[i]) else {
                panic!("Invalid Amino in literal");
            };
            aas[i] = aa;
            i += 1;
        }
        aas
    }

    /// Construct [`Seq`]-wrapped [`Amino`] array from literal without allocating.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{Amino, Seq};
    ///
    /// let aas1 = Amino::seq(b"ACME*WIDGETS");
    /// // ...is shorthand for...
    /// use Amino::{A, C, M, E, Stop, W, I, D, G, T, S};
    /// let aas2 = Seq([A, C, M, E, Stop, W, I, D, G, E, T, S]);
    ///
    /// assert_eq!(aas1, aas2);
    /// ```
    ///
    /// # Panics
    ///
    /// This panics if the supplied literal isn't valid. **Whitespace is NOT allowed**
    /// because the returned array must have the same length.
    #[must_use]
    #[track_caller]
    pub const fn seq<const N: usize>(literal: &[u8; N]) -> Seq<[Amino; N]> {
        Seq(Self::arr(literal))
    }
}

impl Display for Amino {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        self.to_str().fmt(f)
    }
}

impl FromStr for Amino {
    type Err = ParseSymbolError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.as_bytes() {
            [b] => Self::from_ascii(*b),
            _ => Err(ParseSymbolError::new::<Self>()),
        }
    }
}

impl AsRef<Amino> for Amino {
    fn as_ref(&self) -> &Amino {
        self
    }
}

impl AsMut<Amino> for Amino {
    fn as_mut(&mut self) -> &mut Amino {
        self
    }
}

/// Ambiguous amino acid
///
/// Note that [`AmbiAmino`] always represents *at least one* possible amino acid;
/// there is no such thing as an empty/null [`AmbiAmino`]. Also beware that
/// `ambi_amino.to_string().parse()` is **lossy** because there are too many [`AmbiAmino`]s
/// to represent in a single character; anything without a standard character will be
/// displayed as `"X"` but `"X"` is parsed as a maximally ambiguous [`AmbiAmino`].
/// However, the [`Debug`](std::fmt::Debug) implementation will exactly represent
/// the [`AmbiAmino`] at the cost of being 1-25 characters long.
///
/// For details, see: <https://en.wikipedia.org/wiki/FASTA_format#Sequence_representation>
///
/// <div class="warning">
///
/// Beware that [`AmbiAmino`]'s order isn't alphabetic.
///
/// </div>
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AmbiAmino(NonZeroU32);

// Implementation notes:
// Bit 0 is always on, allowing niche optimizations.
// Other bits are determined by Self::bit_offset.
// (the low 5 bits of the IUPAC ASCII representation are the bit offset)
// That unfortunately means * falls on bit 10, so the bits aren't in quite in alphabetical order.
// (we fix that up if anybody actually asks us to iterate)

macro_rules! ambi_amino_consts {
    ( $( #[doc = $doc:literal] $ambi_amino:ident = $($amino:ident)|+  ),+ $(,)? ) => {
        $(
            #[doc = $doc]
            pub const $ambi_amino: Self = const {
                let bits = 1 | $(Self::bit_mask(Amino::$amino))|+;
                Self(NonZeroU32::new(bits).expect("BUG: somehow 1 | X == 0"))
            };
        )+
    }
}

impl AmbiAmino {
    /// Translation stop (alias for consistency with [`Amino::Stop`])
    #[allow(non_upper_case_globals)]
    pub const Stop: Self = Self::STOP;

    ambi_amino_consts!(
        /// Translation stop
        STOP = Stop,
        /// Alanine
        A = A,
        /// Aspartic acid ([D](Self::D)) or asparagine ([N](Self::N))
        B = D | N,
        /// Cysteine
        C = C,
        /// Aspartic acid
        D = D,
        /// Glutamic acid
        E = E,
        /// Phenylalanine
        F = F,
        /// Glycine
        G = G,
        /// Histidine
        H = H,
        /// Isoleucine
        I = I,
        /// Leucine ([L](Self::L)) or isoleucine ([I](Self::I))
        J = L | I,
        /// Lysine
        K = K,
        /// Leucine
        L = L,
        /// Methionine
        M = M,
        /// Asparagine
        N = N,
        /// Pyrrolysine
        O = O,
        /// Proline,
        P = P,
        /// Glutamine
        Q = Q,
        /// Arginine
        R = R,
        /// Serine
        S = S,
        /// Threonine
        T = T,
        /// Selenocysteine
        U = U,
        /// Valine
        V = V,
        /// Tryptophan
        W = W,
        /// Tyrosine
        Y = Y,
        /// Glutamic acid ([E](Self::E)) or glutamine ([Q](Self::Q))
        Z = E | Q,
    );

    /// Any amino acid
    ///
    /// Note that this doesn't perfectly round-trip. Any ambiguous amino that can't be represented
    /// with a single-letter code will be displayed as "X" but "X" will be parsed as the
    /// [`X`](Self::X) constant, which refers to a maximally ambiguous [`AmbiAmino`].
    pub const X: Self = const {
        let mut i = 0;
        let mut bits = 1;
        while i < Amino::ALL.len() {
            bits |= Self::bit_mask(Amino::ALL[i]);
            i += 1;
        }
        Self(NonZeroU32::new(bits).expect("BUG: somehow 1 | X == 0"))
    };

    /// Cast [`AmbiAmino`] to [`NonZeroU32`].
    ///
    /// <div class="warning">
    ///
    /// No particular representation is promised and the exact values are not part of
    /// stability guarantees.
    ///
    /// </div>
    #[must_use]
    pub fn to_bits(self) -> NonZeroU32 {
        self.0
    }

    /// Return uppercase string representation
    ///
    /// Note that anything without a single-character representation will result in `"X"`.
    /// Use [`Debug`](std::fmt::Debug) formatting if you want a lossless representation.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::AmbiAmino;
    ///
    /// assert_eq!(AmbiAmino::A.to_str(), "A");
    /// assert_eq!(AmbiAmino::STOP.to_str(), "*");
    /// assert_eq!((AmbiAmino::D | AmbiAmino::N).to_str(), "B");
    /// assert_eq!((AmbiAmino::D | AmbiAmino::E).to_str(), "X");
    /// ```
    #[must_use]
    pub fn to_str(self) -> &'static str {
        match self {
            Self::STOP => "*",
            Self::A => "A",
            Self::B => "B",
            Self::C => "C",
            Self::D => "D",
            Self::E => "E",
            Self::F => "F",
            Self::G => "G",
            Self::H => "H",
            Self::I => "I",
            Self::J => "J",
            Self::K => "K",
            Self::L => "L",
            Self::M => "M",
            Self::N => "N",
            Self::O => "O",
            Self::P => "P",
            Self::Q => "Q",
            Self::R => "R",
            Self::S => "S",
            Self::T => "T",
            Self::U => "U",
            Self::V => "V",
            Self::W => "W",
            Self::Y => "Y",
            Self::Z => "Z",
            _ => "X",
        }
    }

    /// Construct from ASCII representation
    ///
    /// # Errors
    ///
    /// Returns [`ParseSymbolError`] if the given byte isn't a letter or `*`.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::AmbiAmino;
    ///
    /// assert_eq!(AmbiAmino::from_ascii(b'A'), Ok(AmbiAmino::A));
    /// assert_eq!(AmbiAmino::from_ascii(b'*'), Ok(AmbiAmino::STOP));
    /// assert_eq!(AmbiAmino::from_ascii(b'X'), Ok(AmbiAmino::X));
    /// assert!(AmbiAmino::from_ascii(b'.').is_err());
    /// ```
    pub const fn from_ascii(ascii: u8) -> Result<Self, ParseSymbolError> {
        Ok(match ascii {
            b'*' => Self::STOP,

            b'A' | b'a' => Self::A,
            b'B' | b'b' => Self::B,
            b'C' | b'c' => Self::C,
            b'D' | b'd' => Self::D,
            b'E' | b'e' => Self::E,
            b'F' | b'f' => Self::F,
            b'G' | b'g' => Self::G,
            b'H' | b'h' => Self::H,
            b'I' | b'i' => Self::I,
            b'J' | b'j' => Self::J,
            b'K' | b'k' => Self::K,
            b'L' | b'l' => Self::L,
            b'M' | b'm' => Self::M,
            b'N' | b'n' => Self::N,
            b'O' | b'o' => Self::O,
            b'P' | b'p' => Self::P,
            b'Q' | b'q' => Self::Q,
            b'R' | b'r' => Self::R,
            b'S' | b's' => Self::S,
            b'T' | b't' => Self::T,
            b'U' | b'u' => Self::U,
            b'V' | b'v' => Self::V,
            b'W' | b'w' => Self::W,
            b'X' | b'x' => Self::X,
            b'Y' | b'y' => Self::Y,
            b'Z' | b'z' => Self::Z,

            _ => return Err(ParseSymbolError::new::<Self>()),
        })
    }

    /// Return uppercase ASCII representation
    ///
    /// See [`to_str`](Self::to_str) for caveats.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::AmbiAmino;
    ///
    /// assert_eq!(AmbiAmino::A.to_ascii(), b'A');
    /// assert_eq!(AmbiAmino::STOP.to_ascii(), b'*');
    /// assert_eq!((AmbiAmino::D | AmbiAmino::N).to_ascii(), b'B');
    /// assert_eq!((AmbiAmino::D | AmbiAmino::E).to_ascii(), b'X');
    /// ```
    #[must_use]
    pub fn to_ascii(self) -> u8 {
        self.to_str().as_bytes()[0]
    }

    /// Construct [`AmbiAmino`] array from literal without allocating.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::AmbiAmino;
    ///
    /// let aas1 = AmbiAmino::arr(b"TOO*LONG");
    /// // ...is shorthand for...
    /// let aas2 = [
    ///     AmbiAmino::T, AmbiAmino::O, AmbiAmino::O, AmbiAmino::STOP,
    ///     AmbiAmino::L, AmbiAmino::O, AmbiAmino::N, AmbiAmino::G
    /// ];
    ///
    /// assert_eq!(aas1, aas2);
    /// ```
    ///
    /// # Panics
    ///
    /// This panics if the supplied literal isn't valid. **Whitespace is NOT allowed**
    /// because the returned array must have the same length.
    #[must_use]
    #[track_caller]
    pub const fn arr<const N: usize>(literal: &[u8; N]) -> [AmbiAmino; N] {
        let mut aas = [Self::A; N];
        let mut i = 0;
        while i < literal.len() {
            let Ok(aa) = Self::from_ascii(literal[i]) else {
                panic!("Invalid Amino in literal");
            };
            aas[i] = aa;
            i += 1;
        }
        aas
    }

    /// Construct [`Seq`]-wrapped [`AmbiAmino`] array from literal without allocating.
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{AmbiAmino, Seq};
    ///
    /// let aas1 = AmbiAmino::seq(b"TOO*LONG");
    /// // ...is shorthand for...
    /// let aas2 = Seq([
    ///     AmbiAmino::T, AmbiAmino::O, AmbiAmino::O, AmbiAmino::STOP,
    ///     AmbiAmino::L, AmbiAmino::O, AmbiAmino::N, AmbiAmino::G
    /// ]);
    ///
    /// assert_eq!(aas1, aas2);
    /// ```
    ///
    /// # Panics
    ///
    /// This panics if the supplied literal isn't valid. **Whitespace is NOT allowed**
    /// because the returned array must have the same length.
    #[must_use]
    #[track_caller]
    pub const fn seq<const N: usize>(literal: &[u8; N]) -> Seq<[AmbiAmino; N]> {
        Seq(Self::arr(literal))
    }

    /// Return iterator of [`Amino`]s that this ambiguous amino acid could be.
    ///
    /// The iterator is guaranteed to return things in sorted order and without duplicates,
    /// and its contents are guaranteed to recompose into this [`AmbiAmino`] via [`BitOr`].
    ///
    /// # Examples
    ///
    /// ```
    /// use nucs::{AmbiAmino, Amino};
    ///
    /// let aa = AmbiAmino::A | AmbiAmino::B | AmbiAmino::C;
    /// assert!(aa.iter().eq(Amino::arr(b"ACDN")));
    /// ```
    pub fn iter(self) -> AmbiAminoIter {
        AmbiAminoIter::new(self)
    }

    pub(crate) const fn from_amino(amino: Amino) -> AmbiAmino {
        Self(NonZeroU32::new(1 | Self::bit_mask(amino)).expect("x OR 1 is non-zero"))
    }

    pub(crate) const fn or(self, rhs: AmbiAmino) -> AmbiAmino {
        Self(NonZeroU32::new(self.0.get() | rhs.0.get()).expect("non-zero OR non-zero is non-zero"))
    }

    pub(crate) const fn bit_offset(amino: Amino) -> u8 {
        (amino as u8) % 32
    }

    pub(crate) const fn bit_mask(amino: Amino) -> u32 {
        1 << Self::bit_offset(amino)
    }
}

impl Default for AmbiAmino {
    fn default() -> AmbiAmino {
        AmbiAmino::X
    }
}

impl BitOr for AmbiAmino {
    type Output = AmbiAmino;

    fn bitor(self, rhs: AmbiAmino) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

impl BitOr for &AmbiAmino {
    type Output = AmbiAmino;

    fn bitor(self, rhs: &AmbiAmino) -> Self::Output {
        *self | *rhs
    }
}

impl BitOr<Amino> for AmbiAmino {
    type Output = AmbiAmino;

    fn bitor(self, rhs: Amino) -> Self::Output {
        self | AmbiAmino::from(rhs)
    }
}

impl BitOr<&Amino> for &AmbiAmino {
    type Output = AmbiAmino;

    fn bitor(self, rhs: &Amino) -> Self::Output {
        *self | *rhs
    }
}

impl BitOr<AmbiAmino> for Amino {
    type Output = AmbiAmino;

    fn bitor(self, rhs: AmbiAmino) -> Self::Output {
        AmbiAmino::from(self) | rhs
    }
}

impl BitOr<&AmbiAmino> for &Amino {
    type Output = AmbiAmino;

    fn bitor(self, rhs: &AmbiAmino) -> Self::Output {
        *self | *rhs
    }
}

impl BitOr for Amino {
    type Output = AmbiAmino;

    fn bitor(self, rhs: Amino) -> Self::Output {
        AmbiAmino::from(self) | rhs
    }
}

impl BitOr for &Amino {
    type Output = AmbiAmino;

    fn bitor(self, rhs: &Amino) -> Self::Output {
        *self | *rhs
    }
}

impl BitOrAssign for AmbiAmino {
    fn bitor_assign(&mut self, rhs: AmbiAmino) {
        *self = *self | rhs;
    }
}

impl BitOrAssign<&AmbiAmino> for AmbiAmino {
    fn bitor_assign(&mut self, rhs: &AmbiAmino) {
        *self |= *rhs;
    }
}

impl BitOrAssign<Amino> for AmbiAmino {
    fn bitor_assign(&mut self, rhs: Amino) {
        *self = *self | rhs;
    }
}

impl BitOrAssign<&Amino> for AmbiAmino {
    fn bitor_assign(&mut self, rhs: &Amino) {
        *self |= *rhs;
    }
}

impl PartialEq<Amino> for AmbiAmino {
    fn eq(&self, other: &Amino) -> bool {
        *self == AmbiAmino::from(*other)
    }
}

impl PartialEq<AmbiAmino> for Amino {
    fn eq(&self, other: &AmbiAmino) -> bool {
        other == self
    }
}

impl PartialOrd<Amino> for AmbiAmino {
    fn partial_cmp(&self, other: &Amino) -> Option<Ordering> {
        Some(self.cmp(&AmbiAmino::from(*other)))
    }
}

impl PartialOrd<AmbiAmino> for Amino {
    fn partial_cmp(&self, other: &AmbiAmino) -> Option<Ordering> {
        other.partial_cmp(self).map(Ordering::reverse)
    }
}

impl From<Amino> for AmbiAmino {
    fn from(amino: Amino) -> Self {
        Self(NonZeroU32::MIN | Self::bit_mask(amino))
    }
}

impl TryFrom<AmbiAmino> for Amino {
    type Error = AmbiAmino;

    fn try_from(amino: AmbiAmino) -> Result<Self, Self::Error> {
        Ok(match amino {
            AmbiAmino::STOP => Self::Stop,
            AmbiAmino::A => Amino::A,
            AmbiAmino::C => Amino::C,
            AmbiAmino::D => Amino::D,
            AmbiAmino::E => Amino::E,
            AmbiAmino::F => Amino::F,
            AmbiAmino::G => Amino::G,
            AmbiAmino::H => Amino::H,
            AmbiAmino::I => Amino::I,
            AmbiAmino::K => Amino::K,
            AmbiAmino::L => Amino::L,
            AmbiAmino::M => Amino::M,
            AmbiAmino::N => Amino::N,
            AmbiAmino::O => Amino::O,
            AmbiAmino::P => Amino::P,
            AmbiAmino::Q => Amino::Q,
            AmbiAmino::R => Amino::R,
            AmbiAmino::S => Amino::S,
            AmbiAmino::T => Amino::T,
            AmbiAmino::U => Amino::U,
            AmbiAmino::V => Amino::V,
            AmbiAmino::W => Amino::W,
            AmbiAmino::Y => Amino::Y,
            _ => return Err(amino),
        })
    }
}

#[cfg(any(feature = "proptest", feature = "rand", test))]
impl AmbiAmino {
    pub(crate) const BITS_RANGE: std::ops::Range<u32> = 1..(1 << Amino::ALL.len());

    /// Note: `bits` must be in [`Self::BITS_RANGE`].
    pub(crate) fn from_bits(bits: u32) -> AmbiAmino {
        // The bit layout of all valid AmbiAminos:
        // 000000x0 xxxxxxxx xxxxxxxx xxxxx0x1
        //          <--------21 bits------>
        // Note: Big-endian, and x can be any bit (with the contraint at least one x is true)

        // Given a random number, consisting of 23 (low-order) bits, we need to spread them
        // to match the bit pattern above... Easiest approach is move the second bit up.
        Self(NonZeroU32::MIN | ((bits & 2) << 24) | ((bits & !2) << 1))
    }
}

/// Displays a single-character code, falling back to `X`.
///
/// # Examples
///
/// ```
/// use nucs::AmbiAmino;
///
/// assert_eq!(AmbiAmino::S.to_string(), "S");
/// assert_eq!((AmbiAmino::L | AmbiAmino::I).to_string(), "J");
/// assert_eq!((AmbiAmino::A | AmbiAmino::B).to_string(), "X");
/// assert_eq!(AmbiAmino::X.to_string(), "X");
/// // Note that despite the same representation they're not actually the same:
/// assert_ne!(AmbiAmino::A | AmbiAmino::B, AmbiAmino::X);
/// ```
impl Display for AmbiAmino {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        self.to_str().fmt(f)
    }
}

/// Displays single-character code when possible, otherwise all possibilities.
///
/// Note that when falling back to bracket-enclosed possibilities, this doesn't use
/// ambiguity codes like [`B`](Self::B), [`J`](Self::J) or [`Z`](Self::Z).
///
// # Examples
///
/// ```
/// use nucs::AmbiAmino;
///
/// assert_eq!(format!("{:?}", AmbiAmino::S), "S");
/// assert_eq!(format!("{:?}", AmbiAmino::L | AmbiAmino::I), "J");
/// assert_eq!(format!("{:?}", AmbiAmino::A | AmbiAmino::B), "[ADN]");
/// assert_eq!(format!("{:?}", AmbiAmino::X), "X");
/// ```
impl std::fmt::Debug for AmbiAmino {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        let chr = self.to_str();
        if *self != Self::X && chr == "X" {
            f.write_str("[")?;
            for amino in self {
                f.write_str(amino.to_str())?;
            }
            f.write_str("]")
        } else {
            f.write_str(chr)
        }
    }
}

impl FromStr for AmbiAmino {
    type Err = ParseSymbolError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.as_bytes() {
            [b] => Self::from_ascii(*b),
            _ => Err(ParseSymbolError::new::<Self>()),
        }
    }
}

impl AsRef<AmbiAmino> for AmbiAmino {
    fn as_ref(&self) -> &AmbiAmino {
        self
    }
}

impl AsMut<AmbiAmino> for AmbiAmino {
    fn as_mut(&mut self) -> &mut AmbiAmino {
        self
    }
}

impl IntoIterator for AmbiAmino {
    type IntoIter = AmbiAminoIter;
    type Item = Amino;

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

impl IntoIterator for &AmbiAmino {
    type IntoIter = AmbiAminoIter;
    type Item = Amino;

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

impl Symbol for Amino {
    type Concrete = Amino;
    type Ambiguous = AmbiAmino;

    fn to_str(self) -> &'static str {
        Self::to_str(self)
    }

    fn from_ascii(ascii: u8) -> Result<Self, ParseSymbolError> {
        Self::from_ascii(ascii)
    }

    fn to_ascii(self) -> u8 {
        Self::to_ascii(self)
    }

    fn arr<const N: usize>(literal: &[u8; N]) -> [Self; N] {
        Self::arr(literal)
    }

    fn seq<const N: usize>(literal: &[u8; N]) -> Seq<[Self; N]> {
        Self::seq(literal)
    }
}

impl Symbol for AmbiAmino {
    type Concrete = Amino;
    type Ambiguous = AmbiAmino;

    fn to_str(self) -> &'static str {
        Self::to_str(self)
    }

    fn from_ascii(ascii: u8) -> Result<Self, ParseSymbolError> {
        Self::from_ascii(ascii)
    }

    fn to_ascii(self) -> u8 {
        Self::to_ascii(self)
    }

    fn arr<const N: usize>(literal: &[u8; N]) -> [Self; N] {
        Self::arr(literal)
    }

    fn seq<const N: usize>(literal: &[u8; N]) -> Seq<[Self; N]> {
        Self::seq(literal)
    }
}

impl crate::symbol::sealed::Sealed for Amino {
    const NAME: &str = "amino acid";
    const EXPECTED: &str =
        "one of A/C/D/E/F/G/H/I/K/L/M/N/O/P/Q/R/S/T/U/V/W/Y/* (case-insensitive)";
}

impl crate::symbol::sealed::Sealed for AmbiAmino {
    const NAME: &str = "ambiguous amino acid";
    const EXPECTED: &str = "a letter or the character *";
}

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

    #[test]
    fn unambiguous_amino_is_its_only_possiblity() {
        for aa in Amino::ALL {
            assert!(AmbiAmino::from(aa).iter().eq([aa]));
        }
    }

    #[test]
    fn unambiguous_pair_of_aminos_are_their_only_possiblities() {
        for aa1 in Amino::ALL {
            for aa2 in Amino::ALL {
                if aa1 < aa2 {
                    assert!((aa1 | aa2).iter().eq([aa1, aa2]));
                }
            }
        }
    }

    fn all_ambi_aminos() -> impl Iterator<Item = AmbiAmino> {
        (1..(1 << Amino::ALL.len()) - 1).filter_map(|amino_i| {
            (0..Amino::ALL.len())
                .filter(|bit| amino_i & (1 << bit) != 0)
                .map(|bit| AmbiAmino::from(Amino::ALL[bit]))
                .reduce(|a, b| a | b)
        })
    }

    #[cfg_attr(debug_assertions, ignore = "slow outside of release mode")]
    #[test]
    fn amino_possiblities_are_sorted_and_unique() {
        for aa in all_ambi_aminos() {
            assert!(aa.iter().zip(aa.iter().skip(1)).all(|(a, b)| a < b));
        }
    }

    #[cfg_attr(debug_assertions, ignore = "slow outside of release mode")]
    #[test]
    fn ambi_amino_bitor_is_itempotent() {
        for aa in all_ambi_aminos() {
            assert_eq!(aa | aa, aa);
        }
    }

    #[cfg_attr(debug_assertions, ignore = "slow outside of release mode")]
    #[test]
    fn amino_possibilities_can_be_recomposed_into_ambi_nucs() {
        for aa in all_ambi_aminos() {
            let possibilities = aa.iter().map(AmbiAmino::from);
            assert_eq!(possibilities.reduce(|a, b| a | b), Some(aa));
        }
    }

    // Definitely way to many AmbiAminos to exhaustively test OR-ing them together...
    #[test]
    fn smoke_test_ambi_amino_bitor() {
        assert!(
            (AmbiAmino::A | AmbiAmino::B)
                .iter()
                .eq([Amino::A, Amino::D, Amino::N])
        );
    }

    // // WAY too many possibilities (70T) to exhaustively test. :/
    // #[ignore]
    // #[test]
    // fn ambi_amino_bitor_is_consistent_with_possibilities() {
    //     for ambi1 in all_ambi_aminos() {
    //         for ambi2 in all_ambi_aminos() {
    //             let mut expected: Vec<_> = ambi1.iter().chain(ambi2).collect();
    //             expected.sort();
    //             expected.dedup();
    //             assert!((ambi1 | ambi2).iter().eq(expected));
    //         }
    //     }
    // }

    #[test]
    fn amino_bitor_with_x_is_x() {
        for aa in Amino::ALL {
            assert_eq!(aa | AmbiAmino::X, AmbiAmino::X);
            assert_eq!(AmbiAmino::X | aa, AmbiAmino::X);
        }
    }

    #[cfg_attr(debug_assertions, ignore = "slow outside of release mode")]
    #[test]
    fn ambi_amino_bitor_with_x_is_x() {
        for aa in all_ambi_aminos() {
            assert_eq!(aa | AmbiAmino::X, AmbiAmino::X);
            assert_eq!(AmbiAmino::X | aa, AmbiAmino::X);
        }
    }

    #[test]
    fn str_roundtrips() {
        for aa in Amino::ALL {
            assert_eq!(Amino::from_str(aa.to_str()), Ok(aa));
        }
        // Notably, this test is NOT applicable to `AmbiAmino`
    }

    #[test]
    fn ascii_roundtrips() {
        for aa in Amino::ALL {
            assert_eq!(Amino::from_ascii(aa.to_ascii()), Ok(aa));
        }
        // Notably, this test is NOT applicable to `AmbiAmino`
    }

    #[test]
    fn all_is_sorted() {
        let mut sorted = Amino::ALL;
        sorted.sort();
        assert_eq!(Amino::ALL, sorted);
    }

    #[test]
    fn sanity_check_from_bits_values() {
        // AmbiAmino::X has all bits enabled, and it's generated at compile-time via a slow
        // but fairly fool-proof method, so it makes a good reference value.
        // The last value in BITS_RANGE should have all bits turned on, so hopefully passing
        // that to AmbiAmino::from_bits should result in AmbiAmino::X.
        let all_bits = AmbiAmino::BITS_RANGE.last().unwrap();
        assert_eq!(AmbiAmino::from_bits(all_bits), AmbiAmino::X);

        // Make sure turning each bit on individually results in the same set of values
        // as the concrete Aminos.
        let mut concrete_ambi_aminos = std::array::from_fn(|i| AmbiAmino::from_bits(1u32 << i));
        let mut expected = Amino::ALL.map(AmbiAmino::from);
        concrete_ambi_aminos.sort();
        expected.sort();
        assert_eq!(concrete_ambi_aminos, expected);
    }
}