Exercise: Phred quality scores
Goal
Write a function phred_score(byte: u8) -> u8 that converts a single Phred+33 quality byte (as found in FASTQ files) to its numeric quality score. Panic if the byte is outside the valid Phred+33 range.
Background
FASTQ files store per-base quality alongside the sequence. The quality of base i is the ASCII character at position i of the quality line. The most common encoding today is Phred+33: each quality score q (an integer in the range 0..=93) is stored as the byte q + 33. So:
| byte | byte value | Phred score | meaning |
|---|---|---|---|
! |
33 | 0 | as bad as it gets |
I |
73 | 40 | typical Illumina “high quality” |
~ |
126 | 93 | as good as the encoding allows |
A score of q corresponds to a base-call error probability of 10^(−q/10). So q = 30 ≈ 1 wrong call in 1000; q = 40 ≈ 1 in 10,000.
I column is the canonical Q = 40 Illumina “high-quality” call; ~ is the encoding’s ceiling.
Anything outside the byte range 33..=126 is not a valid Phred+33 quality and your function should panic.
The exercise
cd day1/ex-phredMake all five tests pass.
How to run
cargo test
cargo run -- IExpected output for I:
byte 'I' -> Phred score 40
Hints
u8
u8 supports <, >, <=, >=, ==, !=. You can combine two checks with || (logical OR):
if byte < 33 || byte > 126 {
// out of range
}For a more idiomatic version using a range expression, see RangeInclusive::contains: (33..=126).contains(&byte).
Once you have ruled out the out-of-range case, the score is simply byte - 33. Rust’s arithmetic operators on u8 will panic on underflow in debug mode and wrap silently in release mode — so the range check is doing real safety work.
Solution
fn phred_score(byte: u8) -> u8 {
if byte < 33 || byte > 126 {
panic!(
"phred_score: byte {} ({:?}) is outside the Phred+33 range 33..=126",
byte,
byte as char,
);
}
byte - 33
}Full reference implementation in day1/ex-phred-solution/src/main.rs.
Where this leads
- Day 3: replace the panic with a
Result— “byte out of Phred+33 range” becomes a returnable error the caller can act on, not a crash. - Day 4: apply this function to every byte of every quality line in a real
.fastq.gz, streamed throughnoodles-fastq, to compute the mean quality of each read. - Day 5: plot the FastQC-style per-position mean-quality profile with
plotters.