I/O and the crate ecosystem

Day 4

Rust for bioinformaticians

What this lecture is

  • Day 4 is when you stop writing every byte of every parser yourself
  • File I/O with the standard library — File, BufReader, BufWriter
  • Cargo’s [dependencies] and how crates.io actually works
  • noodles for FASTA / FASTQ, plotters for plots, zip for bundles
  • Modules — splitting one crate across files

Day 4 in one diagram

The Day 4 pipeline: a FASTQ on disk flows into a BufReader, then a noodles Reader produces Record structs one at a time; from there branches go to plotters (chart SVG), to zip (archive), and back to the filesystem.

Files in, structured records out — the same five blocks reappear in every exercise.

Reading a file — the simplest possible thing

use std::fs;

let contents: String = fs::read_to_string("reads.fa")?;
println!("{contents}");

fs::read_to_string reads the entire FASTA into memory as a String. Three lines, done — the first line is the FASTA header >chr1.

There is also fs::read — returns Vec<u8> instead of a String, no UTF-8 (the modern text encoding for any character; ASCII is the older 1-byte-per-character subset) check.

The problem with whole-file reads

A FASTQ file from a single Illumina lane is 5–50 GB compressed.

A String of that size will not fit in the RAM of your laptop.

// DON'T do this on a real FASTQ
let everything = fs::read_to_string("big.fastq")?;   // OOM-killed

We need to stream (process the file piece-by-piece, never holding the whole thing in RAM at once) — load a small piece, process it, drop it, load the next.

BufReader — a small window onto a large file

A buffer here is a small fixed-size byte array (~64 KB) that the standard library refills from disk in one syscall.

let file   = File::open("reads.fastq")?;          // open the file
let reader = BufReader::new(file);                // wrap in a 64 KB buffer
for line in reader.lines() { /* one line at a time */ }

BufReader visualised

Diagram in three columns showing BufReader workflow. Left column titled 'On disk' shows a reads.fastq file labeled 10 GB containing FASTQ records (@read1, sequence, +, quality lines repeating). A dark arrow labeled '64 KB at a time' and 'one syscall per refill' leads to a middle column titled 'In RAM' showing a light-blue box labeled BufReader<File> with a 64 KB internal buffer holding the first few records as text. A green arrow labeled '.lines()' and 'one line at a time' leads to the right column titled 'Your code' showing a for-loop with successive String lines yielded into small boxes: '@read1', 'ACGTACGTAC', '+', '!!!!!!!!!!', noted as 'only one line lives at a time' with a bold 'O(1) memory' caption. A red-bordered footer panel titled 'The wrong way' shows the code 'let s = std::fs::read_to_string("reads.fastq")?;' with a warning that a 10 GB FASTQ will not fit in RAM and the program will be killed by the OS.

Stream through a 64 KB window; file size no longer matters.

The four I/O traits you will see today

A trait (shared interface — like Python’s __iter__ lets for work over lists, files, and generators) is a set of method signatures that many types can implement. The standard library defines small traits and every readable thing implements them:

Trait What it gives you Implementors
Read read(buf) -> Result<usize> File, &[u8], Cursor
Write write(buf) -> Result<usize> File, Vec<u8>, Stdout
BufRead line-buffered reading BufReader<R>, Cursor<&[u8]>
Seek jump to a position File, Cursor

Code that takes a value implementing BufRead works with a file, an in-memory byte string, a gzip stream — anything that implements the trait. We will see the generic syntax (R: BufRead) on a later slide.

File::open and File::create

use std::fs::File;
use std::io::{BufReader, BufWriter};

let input  = File::open("sample.fasta")?;       // read-only
let output = File::create("out.tsv")?;          // write, truncates if exists

let reader = BufReader::new(input);             // wrap once
let writer = BufWriter::new(output);            // same for writes

Always wrap a File in BufReader or BufWriter. The unbuffered version makes one syscall per byte.

File wrapped in BufReader

An outer rounded box labelled BufReader contains a smaller rounded box labelled File, which contains an arrow into the kernel's file table. Annotation: 'BufReader holds a File and a buffer; the File holds an OS file descriptor.'

A File provides byte-level access; BufReader wraps it and reads chunks.

Lines, words, bytes — what BufRead gives you

use std::io::{BufReader, BufRead};

let f = File::open("sample.bed")?;
let reader = BufReader::new(f);

for line in reader.lines() {
    let line = line?;                         // Result<String, io::Error>
    let cols: Vec<&str> = line.split('\t').collect();
    println!("chrom = {}", cols[0]);
}

.lines() yields one Result<String> per line, lazily. Use it for BED, TSV, plain FASTA headers.

BufRead visualised

Horizontal flow: raw file bytes → BufReader internal buffer (64 KB) → find next \n → yield String (owned by you) → loop body consumes it → next iteration drops it. Annotation: at any moment ~64 KB is in memory; everything else is on disk.

From file bytes to your loop variable: BufRead fills a buffer, splits at newlines, hands you one line at a time.

Result propagation — ? is your verb

fn read_fasta(path: &Path) -> Result<String, io::Error> {
    let mut file = File::open(path)?;                // fail -> return Err
    let mut s = String::new();
    file.read_to_string(&mut s)?;                    // fail -> return Err
    Ok(s)
}

The ? operator: if the value is Err, return it from this function. Otherwise, unwrap to the inner value.

? on an Option — promoting “missing” to an error

Sometimes you get an Option (the value might be missing) but your function returns a Result. Convert with ok_or_else:

fn first_header(path: &Path) -> Result<String, io::Error> {
    let file   = File::open(path)?;
    let reader = BufReader::new(file);
    reader.lines().next()                            // Option<Result<String>>
          .ok_or_else(|| io::Error::other("empty FASTA"))?   // -> Result
}

ok_or_else takes a closure (anonymous function — the || ... bit) that builds the error only if the Option is None.

? is a fork at every fallible call

Diagram titled 'The ? operator: a fork at every fallible call' with the function signature 'fn first_line(path: &Path) -> Result<String, io::Error>' at the top. Three steps shown horizontally: 1) File::open(path)? — may fail if file missing or permission denied; 2) BufReader::new(f) — infallible, no ? needed; 3) .lines().next() .ok_or(empty)?? — may fail on empty file or I/O error. Green Ok arrows connect each step left to right; red Err arrows shoot upward from each fallible step into a red top lane reading 'any ? hits Err -> caller sees Err(io::Error), function body never reaches Ok'. The happy path arrow leaves the third step downward to a green Ok(line) return box. At the bottom, the full function code is shown.

Every ? routes Err out; the happy path reads top to bottom.

Writing files — BufWriter and writeln!

use std::io::{BufWriter, Write};

let out = File::create("contigs.tsv")?;
let mut writer = BufWriter::new(out);

writeln!(writer, "name\tlength\tgc")?;
writeln!(writer, "{}\t{}\t{:.3}", name, length, gc)?;

writer.flush()?;                              // optional: drop also flushes

writeln! is println! but writes to any Write. The trailing ? catches I/O failures.

Where the heavy work goes — external crates

The standard library gives you bytes and lines. Bioinformatics formats are more than bytes:

  • FASTA / FASTQ — multi-line records, quality scores, line wrapping rules
  • BAM / VCF — binary, indexed, compressed
  • Plots — pixels, axes, scales, colours
  • Archives — zip, tar, gzip

Writing each by hand is a lot of work. We use crates instead.

What [dependencies] actually does

For each line in [dependencies], Cargo:

  • downloads the dep from crates.io
  • caches it in ~/.cargo (shared across all your projects)
  • links it statically into your binary (the single compiled program file)

Cargo.toml to running binary

Diagram titled 'Cargo.toml to running binary' showing a flow from top-left to bottom-right. Top-left: a yellow Cargo.toml box with [package] and [dependencies] sections listing 'noodles-fasta = "0.50"', 'plotters = "0.3"', 'zip = "0.6"'. Grey dashed arrows from each dep line lead down to a blue cloud shape labeled 'crates.io public registry' captioned '"0.50" resolves to e.g. 0.50.3'. A grey arrow leads down to a grey box labeled '~/.cargo/registry/' captioned 'downloaded once, reused forever'. A green arrow labeled 'linked in' leads right to an orange 'rustc + linker' box (your code + crates = one binary). A green arrow labeled 'produces' leads down to a green 'target/debug/qc-report' box captioned 'contains every byte of every dep'. Footer: 'You add one line to Cargo.toml. Cargo handles fetching, version resolution, caching, and linking.'

One line of TOML, and Cargo does the rest — fetch, resolve, cache, link.

A real Cargo.toml for day 4

[package]
name = "qc-report"
edition = "2021"

[dependencies]
noodles-fasta = "0.50"
noodles-fastq = "0.20"
plotters      = "0.3"
zip           = "0.6"
serde         = { version = "1", features = ["derive"] }

One line per crate. Optionally a version, optionally a list of features.

Semver — what "0.50" means

You write Cargo accepts Cargo rejects
"0.50" 0.50.0, 0.50.3, 0.50.99 0.51.0, 0.49.0
"1" 1.0.0, 1.5.3, 1.99.0 2.0.0, 0.99.0
"=0.50.1" exactly 0.50.1 anything else

The exact resolved version goes into Cargo.lock — commit that file for applications.

Semver visualised

Three example version transitions: 1.4.2 → 1.4.3 (patch — bug fix, drop-in safe), 1.4.2 → 1.5.0 (minor — new feature, backward compatible), 1.4.2 → 2.0.0 (major — breaking change, code may not compile). Cargo defaults to '^1.4.2' meaning 'compatible with 1.4.2, ≤ 2.0.0'.

Semver: major.minor.patch — break, add, fix.

crates.io and docs.rs

  • crates.io — the public registry. Search, browse, see download counts.
  • docs.rs — every published crate is auto-documented here.
  • cargo doc --open — build and view docs for your own deps, offline.
https://docs.rs/noodles-fasta/             -> latest version
https://docs.rs/noodles-fasta/0.50.3/      -> a specific version
Two boxes side by side: crates.io (the package registry — metadata, downloads counts, link to source), and docs.rs (auto-generated documentation for every published version, with searchable API). Arrow: every publish to crates.io triggers a docs.rs build.

crates.io hosts the packages; docs.rs renders the docs.

How to learn a new crate — five steps

  1. Search crates.io. Downloads count is a rough proxy for community trust.
  2. Read the package page. Check license, last-updated date, repository link.
  3. Open docs.rs. Top-of-page module docs usually show a runnable example.
  4. Paste the example into your project. Get the canonical example working before customising.
  5. Add it to Cargo.toml and run cargo build.

A docs.rs landing page

A mock docs.rs landing page for noodles-fasta, showing the module-level documentation with a short example and a list of submodules and types.

noodles — streaming records, step 1

The reader holds a window into the file; you process one record at a time.

Step 1 of noodles streaming: a FASTQ file on disk; a Reader is constructed over a BufReader of the file, with an empty internal buffer ready to be filled.

Step 1: open the file, the reader allocates a small buffer.

noodles — streaming records, step 2

Step 2 of noodles streaming: the Reader has read the first record from disk into its buffer and yielded a Record value to your loop body.

Step 2: reader fills the buffer with the first record, hands it to you.

noodles — streaming records, step 3

Step 3 of noodles streaming: the previous Record has been dropped (memory freed); the Reader fetches the next record from disk into the same buffer and yields it.

Step 3: you drop the record, the reader fetches the next.

Memory stays roughly constant — independent of file size.

noodles-fasta in eight lines

use noodles_fasta as fasta;
use std::fs::File;
use std::io::BufReader;

fn count_records(reader: BufReader<File>) -> std::io::Result<usize> {
    let mut reader = fasta::io::Reader::new(reader);
    let mut n = 0;
    for result in reader.records() {
        let _record = result?;
        n += 1;
    }
    Ok(n)
}

fasta::io::Reader::new wraps the buffered file. .records() yields Result<Record>.

How the reader layers stack

Three nested rectangles, outermost to innermost: 'noodles_fasta::Reader' contains 'BufReader<File>' contains 'File' contains an OS file descriptor. Each layer's purpose annotated: File = bytes from disk; BufReader = chunked reads; noodles Reader = FASTA semantics.

Layered abstractions: BufReader wraps a File; noodles Reader wraps a BufReader; the records iterator wraps the Reader.

Same function, generic over the reader

A generic function is one that works for any type that meets a stated requirement. The requirement here — R: BufRead — is called a trait bound.

fn count_records<R: BufRead>(reader: R) -> std::io::Result<usize> {
    let mut reader = fasta::io::Reader::new(reader);
    let mut n = 0;
    for result in reader.records() {
        let _record = result?;
        n += 1;
    }
    Ok(n)
}

Same body. Now both calls compile:

count_records(BufReader::new(File::open("sample.fa")?))?;        // real file
count_records(Cursor::new(b">chr1\nACGT\n>chr2\nTTGCAA\n"))?;    // test bytes

Reading a Record — name and sequence

for result in reader.records() {
    let record = result?;

    let name: &[u8] = record.name();
    let seq:  &[u8] = record.sequence().as_ref();
    let length = seq.len();

    let mut gc_count = 0u64;
    for &base in seq {                          // &base = give me the byte
        if base == b'G' || base == b'C'
            || base == b'g' || base == b'c' {
            gc_count += 1;
        }
    }
    let gc = gc_count as f64 / length as f64;
}

Accessors return borrowed slices — no copying.

Record in memory

A `Record` struct on the stack with three fields (name: String, sequence: Sequence, description: Option<String>), each pointing to heap allocations holding the actual bytes. Annotation: the record owns its data — dropping it frees the heap allocations.

A noodles Record in memory: a struct holding owned String fields for name and sequence.

noodles-fastq — read, filter, write

use noodles_fastq as fastq;

fn filter<R: BufRead, W: Write>(reader: R, writer: W, min_len: usize)
    -> std::io::Result<(usize, usize)>
{
    let mut reader = fastq::io::Reader::new(reader);
    let mut writer = fastq::io::Writer::new(writer);
    let (mut total, mut kept) = (0, 0);
    for result in reader.records() {
        let record = result?;
        total += 1;
        if record.sequence().len() >= min_len {
            writer.write_record(&record)?;
            kept += 1;
        }
    }
    Ok((kept, total))
}

The filter pipeline

Horizontal flow: source FASTQ file → noodles_fastq::Reader → filter (`record.sequence().len() >= min_len`) → noodles_fastq::Writer → destination FASTQ file. Records that fail the filter are dropped (red arrow). Annotation: constant memory; one record in flight at a time.

Streaming filter pipeline: reader produces records, filter keeps the good ones, writer emits them.

Modules — splitting one crate across files

A real project does not live in one main.rs. Three keywords carry the system:

  • mod declares a child module — mod parser; tells the compiler “look for parser.rs”
  • pub controls visibility — without pub, items are private to the module
  • use brings names into scope so you can write parse_record(...) instead of crate::parser::parse_record(...)

Modules visualised

Diagram titled 'Modules: split one crate across files'. Left side titled 'On disk' shows a directory tree: ex-fasta-stats/, Cargo.toml, src/, main.rs, parser.rs, stats.rs, captioned 'one source file per module'. Right side top: a blue box labeled 'src/main.rs' showing code 'mod parser;', 'mod stats;', 'use crate::parser::parse_record;', 'use crate::stats::ContigStat;', 'fn main() { /* ... */ }'. Right side bottom: a green box labeled 'src/parser.rs' showing code 'pub struct Record { pub name: String, pub sequence: Vec<u8>, }', 'pub fn parse_record(line: &str) -> Record { /* ... */ }', captioned 'pub = visible to other modules'. A grey dashed arrow labeled 'mod parser; -> look for parser.rs' connects the mod declaration to the parser.rs file. A green arrow labeled 'name lookup' connects the use statement to the pub function. Footer: 'mod declares a child module; pub controls what leaks out; use brings a name into scope.'

mod declares, pub exposes, use brings names into scope.

A tiny module example

// src/main.rs
mod parser;            // look for src/parser.rs

use parser::parse_record;

fn main() {
    let rec = parse_record("chr1\t100\t200");
    println!("{}", rec.chrom);
}
// src/parser.rs
pub struct BedRecord {
    pub chrom: String,
    pub start: u64,
    pub end:   u64,
}

pub fn parse_record(line: &str) -> BedRecord { /* ... */ }

Three keywords carry the system: mod, pub, use.

The same trait wraps real files and test bytes

use std::io::{BufReader, Cursor};

let real    = BufReader::new(File::open("sample.fa")?);
let in_test = Cursor::new(b">chr1\nACGT\n>chr2\nTTGCAA\n");

count_records(real)?;        // BufReader<File>: BufRead
count_records(in_test)?;     // Cursor<&[u8]>: BufRead

The function takes R: BufRead. Both arguments satisfy it. Both compile.

Putting it together — a day-4 main

use std::fs::File;
use std::io::{BufReader, BufWriter};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let reader = BufReader::new(File::open("sample.fastq")?);
    let writer = BufWriter::new(File::create("filtered.fastq")?);

    let (kept, total) = filter(reader, writer, 50)?;
    eprintln!("kept {}/{} reads", kept, total);
    Ok(())
}

Every piece you have seen in this lecture, in one tidy main.

To the next lectures

This was I/O and crates. Two more short lectures today:

  • lec2-plotting — plotters, and how it compares to ggplot and matplotlib
  • lec3-archives — zip files, compression, and why DNA only needs 2 bits per base

Then the exercises this afternoon: BED parse, FASTA stats, FASTQ filter, plot, zip bundle.