Exercise: Per-contig stats with noodles-fasta
Goal
Add the noodles-fasta crate as a dependency, then write a function that streams records from a BufRead source and produces per-contig statistics:
struct ContigStat { name: String, length: usize, gc: f64 }
fn fasta_stats<R: std::io::BufRead>(reader: R) -> std::io::Result<Vec<ContigStat>>This is your first exercise with a real external crate doing the heavy lifting. Compare the body of your function with the hand-rolled FASTA stretch goal from day 1.
The crate
Open Cargo.toml and confirm the dependency block reads:
[dependencies]
noodles-fasta = "0.50"Then in code:
use noodles_fasta as fasta;The crate docs are your reference. You will need:
fasta::io::Reader::newto wrap anyBufReadreader.records()to get an iterator overResult<Record>record.name()for the record’s name as bytesrecord.sequence().as_ref()for the raw sequence as&[u8]
The exercise
cd day4/ex-fasta-statsImplement fasta_stats. Make all four tests pass — they use std::io::Cursor to feed in-memory byte strings to the function without touching the filesystem.
How to run
cargo test
cargo run -- data/sample.faHints
noodles-fasta expects a BufRead. Any BufRead will do — a BufReader<File>, a Cursor<&[u8]>, anything implementing the trait. Construct the FASTA reader once at the top of the function:
let mut reader = fasta::io::Reader::new(reader);records() returns an iterator yielding std::io::Result<Record>. Use a for loop and the ? operator to short-circuit on the first error:
let mut out = Vec::new();
for result in reader.records() {
let record = result?;
// ... process record ...
out.push(stat);
}
Ok(out)The record’s name (the first whitespace-delimited token after >) and sequence are accessed via methods:
let name = std::str::from_utf8(record.name())
.map_err(|_| std::io::Error::other("non-UTF-8 record name"))?
.to_string();
let seq: &[u8] = record.sequence().as_ref();
let length = seq.len();
let gc_count = seq.iter().filter(|&&b| matches!(b, b'G' | b'C' | b'g' | b'c')).count();
let gc = if length == 0 { 0.0 } else { gc_count as f64 / length as f64 };Note matches!: a macro that is shorthand for match x { pat => true, _ => false }. Very handy in iterator filters.
Solution
See day4/ex-fasta-stats-solution/src/main.rs for the full reference. The function is around 15 lines — almost all of it is the GC arithmetic. noodles-fasta does every byte of parsing for you.
Where this leads
- Replace
BufReader<File>with aBufReader<flate2::read::GzDecoder<File>>and your tool works on.fa.gzwith no other changes.noodles-fastadoes not care: it just wants aBufRead. - Exercise 03: same pattern, for FASTQ — but now you also write filtered records back out.