Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/dna/translation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,12 @@ impl str::FromStr for &'static TranslationTable {

fn from_str(s: &str) -> Result<Self> {
let id = s.parse::<usize>()?;
TABLES[id - 1]
.as_ref()
.ok_or_else(|| Error::UnknownTable(id).into())
// Tables are numbered from one, and not every number in the range is used, so
// both the subtraction and the lookup can fail.
id.checked_sub(1)
.and_then(|index| TABLES.get(index))
.and_then(|table| table.as_ref())
.ok_or(Error::UnknownTable(id))
}
}

Expand Down Expand Up @@ -227,6 +230,18 @@ mod tests {
}
}

#[test]
fn test_translation_table_out_of_range() {
// Zero underflowed the index, anything past the end ran off it, and both
// panicked rather than reporting an unknown table.
for id in &["0", "24", "99", "1000000"] {
assert_matches!(
id.parse::<&TranslationTable>().unwrap_err(),
Error::UnknownTable(_)
);
}
}

#[test]
fn test_number_of_codons() {
assert_eq!(64, CodonIterator::new().count());
Expand Down
Loading