Exercise: Reverse complement into a caller-owned buffer
Goal
Rewrite reverse complement so the function does not allocate. Instead, the caller passes in a buffer that the function fills:
fn reverse_complement_into(seq: &[u8], out: &mut Vec<u8>)The function takes a shared reference to the input and a mutable reference to the output buffer.
Why this matters
In the previous exercise, reverse_complement allocated a fresh Vec<u8> on every call. That is fine for one-off use, but it is very wasteful in a hot loop — e.g. when processing 100 million reads. Real bioinformatics tools take a buffer once and reuse it across millions of calls.
This is also your first real encounter with &mut: a unique reference that lets the callee modify the caller’s data, while Rust’s borrow checker guarantees nobody else can touch that data at the same time.
Vec<u8> across one call to revcomp_into. The heap allocation is the same 64-byte block in all three states; only the Vec header’s len field changes. clear() is essentially free, and revcomp_into writes into the existing storage rather than asking the allocator for new memory.
The exercise
cd day2/ex-revcomp-bufMake all six tests pass. One of the tests calls the function twice with the same buffer to verify that the buffer is reused (cleared) on each call.
How to run
cargo test
cargo run -- ATGCATGC # expected: GCATGCATHints
The caller may pass in a buffer that already contains data from a previous call. Your first job is to empty it. Vec::clear sets the length to zero without freeing the allocation — that is the whole point: the caller keeps the underlying memory and you avoid reallocating:
out.clear();After clear(), the vector has length 0 but may still have plenty of capacity from before. Vec::reserve tops it up if it is not big enough; if it is already big enough, this is a no-op:
out.reserve(seq.len());The body is the same indexed reverse loop from exercise 1:
for i in (0..seq.len()).rev() {
out.push(complement_base(seq[i]));
}Note that there is no return and no final expression — the function returns () (the unit type).
Solution
fn reverse_complement_into(seq: &[u8], out: &mut Vec<u8>) {
out.clear();
out.reserve(seq.len());
for i in (0..seq.len()).rev() {
out.push(complement_base(seq[i]));
}
}Full reference in day2/ex-revcomp-buf-solution/src/main.rs.
Where this leads
- This is the API shape that crates like
noodlesandrust-htslibuse throughout their inner loops. You will see it again on day 4. - Day 5 will measure how much faster the buffer-reusing version is on a real workload of millions of reads.