bio_seq/codec/degenerate/
ry.rs

1use crate::ComplementMut;
2use crate::codec::Codec;
3
4/// 1-bit encoding for nucleotides with pu**R**ine (`A`/`G`) and p**Y**ramidine (`T`/`C`) structures.
5#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
6#[repr(u8)]
7pub enum RY {
8    R = 0b0,
9    Y = 0b1,
10}
11
12impl Codec for RY {
13    const BITS: u8 = 1;
14
15    /// Transmute a `u8` into a degenerate 1-bit nucleotide
16    ///
17    /// SAFETY: This only looks at the lower 2 bits of the `u8`
18    fn unsafe_from_bits(b: u8) -> Self {
19        debug_assert!(b < 2);
20        unsafe { std::mem::transmute(b & 0b1) }
21    }
22
23    /// Valid values are `0` and `1`
24    fn try_from_bits(b: u8) -> Option<Self> {
25        if b < 2 {
26            Some(unsafe { std::mem::transmute::<u8, RY>(b) })
27        } else {
28            None
29        }
30    }
31
32    /// TODO: fast translation of A, T, W to 0 and C, G, S to 1
33    fn unsafe_from_ascii(_b: u8) -> Self {
34        todo!()
35    }
36
37    fn try_from_ascii(c: u8) -> Option<Self> {
38        match c {
39            b'R' | b'A' | b'G' => Some(RY::R),
40            b'Y' | b'T' | b'C' => Some(RY::Y),
41            _ => None,
42        }
43    }
44
45    fn to_char(self) -> char {
46        match self {
47            RY::R => 'R',
48            RY::Y => 'Y',
49        }
50    }
51
52    fn to_bits(self) -> u8 {
53        self as u8
54    }
55
56    fn items() -> impl Iterator<Item = Self> {
57        vec![RY::R, RY::Y].into_iter()
58    }
59}
60
61impl ComplementMut for RY {
62    /// This representation preserves complementarity, `R = comp(Y)`
63    fn comp(&mut self) {
64        *self = unsafe { std::mem::transmute(*self as u8 ^ 1) };
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use crate::codec::degenerate;
71    use crate::prelude::*;
72
73    #[test]
74    fn test_1bit() {
75        let seq = Seq::<degenerate::RY>::from_str("RRYRYRRY").unwrap();
76        let seq_rc: Seq<degenerate::RY> = seq.to_revcomp();
77        assert_eq!("RYYRYRYY", String::from(seq_rc));
78    }
79}