From a0f2e250310ed273e8d98a788f1691644669e220 Mon Sep 17 00:00:00 2001 From: Steve Wooster Date: Tue, 17 Oct 2023 13:01:42 -0700 Subject: [PATCH] Add conversions between Codon and CodonAmbiguous --- src/nucleotide.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/src/nucleotide.rs b/src/nucleotide.rs index a71bd30..2678606 100644 --- a/src/nucleotide.rs +++ b/src/nucleotide.rs @@ -435,6 +435,26 @@ impl CodonAmbiguous { } } +impl From for CodonAmbiguous { + #[inline(always)] + fn from(codon: Codon) -> Self { + codon.0.map(Into::into).into() + } +} + +impl TryFrom for Codon { + type Error = TranslationError; + + #[inline(always)] + fn try_from(codon: CodonAmbiguous) -> Result { + Ok(Self([ + codon.0[0].try_into()?, + codon.0[1].try_into()?, + codon.0[2].try_into()?, + ])) + } +} + #[cfg(feature = "serde")] serde_utils::impl_stringlike!(Codon); @@ -443,11 +463,11 @@ serde_utils::impl_stringlike!(CodonAmbiguous); #[cfg(test)] mod tests { + use super::*; + #[cfg(feature = "serde")] #[test] fn test_serde_json() { - use super::*; - assert_eq!( serde_json::to_value(Nucleotide::A).unwrap(), serde_json::json!("A") @@ -470,4 +490,36 @@ mod tests { serde_json::json!("ABC") ); } + + #[test] + fn concrete_codon_to_ambiguous_codon_conversion() { + let codon = Codon([Nucleotide::C, Nucleotide::A, Nucleotide::T]); + let expected = CodonAmbiguous([ + NucleotideAmbiguous::C, + NucleotideAmbiguous::A, + NucleotideAmbiguous::T, + ]); + assert_eq!(CodonAmbiguous::from(codon), expected); + } + + #[test] + fn ambiguous_codon_to_concrete_codon_conversion() { + let amb_codon = CodonAmbiguous([ + NucleotideAmbiguous::C, + NucleotideAmbiguous::A, + NucleotideAmbiguous::T, + ]); + let expected = Codon([Nucleotide::C, Nucleotide::A, Nucleotide::T]); + assert_eq!(Codon::try_from(amb_codon).unwrap(), expected); + } + + #[test] + fn ambiguous_codon_to_concrete_codon_conversion_failure() { + let amb_codon = CodonAmbiguous([ + NucleotideAmbiguous::B, + NucleotideAmbiguous::A, + NucleotideAmbiguous::T, + ]); + assert!(Codon::try_from(amb_codon).is_err()); + } }