Exercise: Quality trimming as a slice view

Goal

Write quality_trim(qual: &[u8], min_score: u8) -> &[u8]: given a FASTQ quality string (Phred+33 encoded — see day 1 exercise 4) and a minimum quality score, return the largest interior slice of qual whose endpoints both pass the threshold.

That is: trim low-quality bases from the start and the end, but leave the middle alone.

The function returns a &[u8] — a view into the input — not a new Vec<u8>. No bytes are copied.

Background

Per-end quality trimming is the simplest quality-control step in any sequencing pipeline. (Real tools like cutadapt or fastp use sliding-window averages; we will stay simpler for today.) Conventionally:

  1. Move the start index forward as long as the leading base is below threshold.
  2. Move the end index backward as long as the trailing base is below threshold.
  3. Return the slice &qual[start..end].

The input quality is stored as Phred+33 bytes (so '!' = score 0, 'I' = score 40); the threshold is given as a score. Convert the score to a byte threshold by adding 33.

A horizontal strip of 10 cells showing Phred+33 quality bytes. The chars row reads ! ! # I I I I I # !, the Q row reads 0 0 2 40 40 40 40 40 2 0, and the idx row reads 0 through 9. Cells 0-2 and 8-9 are shaded grey (trimmed); cells 3-7 are shaded light green (kept). Above the strip, two green brackets and arrows mark the final positions start=3 (pointing at cell 3) and end=8 (pointing between cells 7 and 8). Faded dashed grey curves arc from the initial positions start=0 and end=10 inward, labelled 'advance while Q < 20' and 'retreat while Q < 20'. A green result box below the strip reads: result = seq[3..8] — 5 high-quality bases, zero bytes copied. A legend identifies the grey, green, and dashed-arrow elements.
Figure 1: Two-pointer quality trim of a 10-base read at threshold Q ≥ 20. start walks rightward from 0 until it lands on a passing base (index 3); end walks leftward from 10 until it lands just past one (index 8). The function returns &qual[3..8] — five bases, no bytes copied.

Why a slice, not a Vec?

Returning &[u8] means the function performs zero allocation. The returned slice points into the same memory as qual. The caller can use it for as long as qual itself is alive — the borrow checker tracks this for you, with no annotations needed (single input reference → its lifetime is the output’s).

The exercise

cd day2/ex-quality-trim

Make all seven tests pass.

How to run

cargo test
# A FASTQ quality string of "!!IIII!!" trimmed at score 30:
# bytes:  ! ! I I I I ! !
# scores: 0 0 40 40 40 40 0 0
# trimmed (drop leading and trailing low):  I I I I

Hints

The quality bytes are Phred+33-encoded, so a score q is stored as the byte q + 33. Compute the byte threshold once at the start of the function:

let threshold = min_score + 33;

After this, every comparison is just qual[i] >= threshold.

Walk the start index forward while the leading byte fails the threshold. Use a while loop:

let mut start: usize = 0;
while start < qual.len() && qual[start] < threshold {
    start += 1;
}

The start < qual.len() check is essential — without it, indexing past the end of the slice would panic. The short-circuit && guarantees qual[start] is only evaluated when start is in range.

Symmetrically, walk the end index backward while the trailing byte fails:

let mut end: usize = qual.len();
while end > start && qual[end - 1] < threshold {
    end -= 1;
}

The end > start guard is important: if every byte is below threshold, this loop should leave end == start, returning an empty slice. (Without the guard the loop would underflow end and panic.)

The final expression is the slice:

&qual[start..end]

No ;, no allocation — just a view.

Solution

fn quality_trim(qual: &[u8], min_score: u8) -> &[u8] {
    let threshold = min_score + 33;
    let mut start: usize = 0;
    while start < qual.len() && qual[start] < threshold {
        start += 1;
    }
    let mut end: usize = qual.len();
    while end > start && qual[end - 1] < threshold {
        end -= 1;
    }
    &qual[start..end]
}

Full reference in day2/ex-quality-trim-solution/src/main.rs.

Where this leads

  • Day 3: rewrite with <[T]>::iter().position() and rposition() — same algorithm, no explicit loop, no mutable counters.
  • Day 4: apply this to every read of a real .fastq.gz streamed through noodles-fastq, then write the trimmed reads to a new file.