pmdshodh 0.4.1

Per-read post-mortem damage (PMD) scoring and filtering of ancient DNA alignments, compatible with PMDtools
Documentation
//! BAM header reading without a second reference sequence dictionary ([#110]).
//!
//! noodles-bam 0.98 parses the SAM header text, then collects the binary reference sequence list
//! into a second dictionary only to compare it with the first. With millions of `@SQ` lines that
//! doubles the time and the peak memory of reading the header. Here the binary list is compared
//! with the text's dictionary entry by entry as it is read. The header and every error are the
//! same as noodles' `bam::io::Reader::read_header`: on the first entry that is not an in-order
//! match (a mismatch, or a duplicate name, which noodles' dictionary collapses) the rest of the
//! list is collected and compared as noodles does.
//!
//! [#110]: https://github.com/dpatel511/pmdshodh/issues/110

use std::ffi::CStr;
use std::io::{self, BufRead, Read};
use std::num::NonZero;

use noodles::bam;
use noodles::bam::io::reader::header::sam_header;
use noodles::sam;
use noodles::sam::header::ReferenceSequences;
use noodles::sam::header::record::value::{Map, map::ReferenceSequence};

const MAGIC_NUMBER: [u8; 4] = *b"BAM\x01";

/// Read a BAM header from the start of the decompressed `reader`, leaving it at the first record.
pub fn read_header<R: Read>(reader: &mut R) -> io::Result<sam::Header> {
    let mut bam_reader = bam::io::Reader::from(reader);
    let mut header_reader = bam_reader.header_reader();
    if header_reader.read_magic_number()? != MAGIC_NUMBER {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "invalid BAM header",
        ));
    }
    let mut header = read_sam_header(&mut header_reader.raw_sam_header_reader()?)?;
    if header.reference_sequences().is_empty() {
        *header.reference_sequences_mut() = header_reader.read_reference_sequences()?;
    } else if !reference_sequences_match(bam_reader.get_mut(), header.reference_sequences())? {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "SAM header and binary reference sequence dictionaries mismatch",
        ));
    }
    Ok(header)
}

/// As noodles-bam reads the header text.
fn read_sam_header<R: Read>(reader: &mut sam_header::Reader<R>) -> io::Result<sam::Header> {
    let mut parser = sam::header::Parser::default();
    let mut buf = Vec::new();
    while read_line(reader, &mut buf)? != 0 {
        parser
            .parse_partial(&buf)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    }
    reader.discard_to_end()?;
    Ok(parser.finish())
}

/// A line without its `\n` or `\r\n`, as noodles-bam reads it; 0 at the end of the text.
fn read_line<R: BufRead>(reader: &mut R, dst: &mut Vec<u8>) -> io::Result<usize> {
    dst.clear();
    let n = reader.read_until(b'\n', dst)?;
    if dst.ends_with(b"\n") {
        dst.pop();
        if dst.ends_with(b"\r") {
            dst.pop();
        }
    }
    Ok(n)
}

/// Read the binary reference sequence list and say whether it equals `text` in names, lengths
/// and order. Entries are compared as they are read. Only at the first entry that is not the next
/// one of `text` is a dictionary built, as noodles-bam builds it: the entries before it (equal to
/// those of `text`), that entry and the rest of the list. It is then compared as noodles-bam does.
fn reference_sequences_match<R: Read>(
    reader: &mut R,
    text: &ReferenceSequences,
) -> io::Result<bool> {
    let n = read_u32_le(reader).and_then(|n| {
        usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
    })?;
    let mut name = Vec::new();
    for i in 0..n {
        read_name(reader, &mut name)?;
        let length = read_u32_le_as_nonzero_usize(reader)?;
        let next = text.get_index(i);
        if next.is_some_and(|(t_name, t_map)| **t_name == name && t_map.length() == length) {
            continue;
        }
        let mut binary: ReferenceSequences = text
            .iter()
            .take(i)
            .map(|(n, m)| (n.clone(), Map::<ReferenceSequence>::new(m.length())))
            .collect();
        binary.insert(
            name.as_slice().into(),
            Map::<ReferenceSequence>::new(length),
        );
        for _ in i + 1..n {
            let (name, map) = read_reference_sequence(reader)?;
            binary.insert(name.into(), map);
        }
        return Ok(reference_sequences_eq(text, &binary));
    }
    Ok(n == text.len())
}

/// noodles-bam's comparison of the two dictionaries.
fn reference_sequences_eq(text: &ReferenceSequences, binary: &ReferenceSequences) -> bool {
    text.len() == binary.len()
        && text
            .iter()
            .zip(binary)
            .all(|((t_name, t_map), (b_name, b_map))| {
                t_name == b_name && t_map.length() == b_map.length()
            })
}

fn read_reference_sequence<R: Read>(
    reader: &mut R,
) -> io::Result<(Vec<u8>, Map<ReferenceSequence>)> {
    let mut name = Vec::new();
    read_name(reader, &mut name)?;
    let length = read_u32_le_as_nonzero_usize(reader)?;
    Ok((name, Map::<ReferenceSequence>::new(length)))
}

/// A NUL-terminated name into `dst`, without its NUL.
fn read_name<R: Read>(reader: &mut R, dst: &mut Vec<u8>) -> io::Result<()> {
    let len = read_u32_le_as_nonzero_usize(reader)?;
    if len.get() > dst.capacity() {
        // Zeroed on allocation, as in noodles, so a corrupt length does not touch every byte.
        *dst = vec![0; len.get()];
    } else {
        dst.clear();
        dst.resize(len.get(), 0);
    }
    reader.read_exact(dst)?;
    let name_len = CStr::from_bytes_with_nul(dst)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
        .to_bytes()
        .len();
    dst.truncate(name_len);
    Ok(())
}

fn read_u32_le_as_nonzero_usize<R: Read>(reader: &mut R) -> io::Result<NonZero<usize>> {
    read_u32_le(reader).and_then(|n| {
        usize::try_from(n)
            .and_then(NonZero::try_from)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
    })
}

fn read_u32_le<R: Read>(reader: &mut R) -> io::Result<u32> {
    let mut buf = [0; 4];
    reader.read_exact(&mut buf)?;
    Ok(u32::from_le_bytes(buf))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Bytes after the header, which both readers must leave unread.
    const RECORDS: &[u8] = b"records";

    /// A BAM header: magic, the text with its length, and `(l_name, name bytes, l_ref)` entries.
    fn bam(magic: &[u8], text: &[u8], refs: &[(u32, &[u8], u32)]) -> Vec<u8> {
        let mut src = magic.to_vec();
        src.extend(u32::try_from(text.len()).unwrap().to_le_bytes());
        src.extend(text);
        src.extend(u32::try_from(refs.len()).unwrap().to_le_bytes());
        for &(l_name, name, l_ref) in refs {
            src.extend(l_name.to_le_bytes());
            src.extend(name);
            src.extend(l_ref.to_le_bytes());
        }
        src.extend(RECORDS);
        src
    }

    /// Entries with well-formed names.
    fn refs(entries: &[(&[u8], u32)]) -> Vec<(u32, Vec<u8>, u32)> {
        entries
            .iter()
            .map(|&(name, len)| {
                let mut c = name.to_vec();
                c.push(0);
                (u32::try_from(c.len()).unwrap(), c, len)
            })
            .collect()
    }

    fn bam_of(text: &[u8], entries: &[(&[u8], u32)]) -> Vec<u8> {
        let owned = refs(entries);
        let raw: Vec<(u32, &[u8], u32)> = owned.iter().map(|(l, n, r)| (*l, &n[..], *r)).collect();
        bam(&MAGIC_NUMBER, text, &raw)
    }

    /// Our header or error, and where the reader is left, equal noodles'. Returns our result.
    fn same_as_noodles(src: &[u8]) -> io::Result<sam::Header> {
        let mut ours_rest = src;
        let ours = read_header(&mut ours_rest);
        let mut theirs_rest = src;
        let theirs = bam::io::Reader::from(&mut theirs_rest).read_header();
        match (&ours, &theirs) {
            (Ok(a), Ok(b)) => assert_eq!(a, b),
            (Err(a), Err(b)) => {
                assert_eq!(a.kind(), b.kind(), "{a} / {b}");
                assert_eq!(a.to_string(), b.to_string());
            }
            _ => panic!("ours {ours:?}, noodles {theirs:?}"),
        }
        assert_eq!(
            ours_rest.len(),
            theirs_rest.len(),
            "position after the header"
        );
        ours
    }

    fn mismatch(src: &[u8]) {
        let e = same_as_noodles(src).unwrap_err();
        assert_eq!(e.kind(), io::ErrorKind::InvalidData);
        assert!(e.to_string().contains("dictionaries mismatch"), "{e}");
    }

    const TEXT: &[u8] = b"@HD\tVN:1.6\n@SQ\tSN:sq0\tLN:8\n@SQ\tSN:sq1\tLN:13\n";
    const ENTRIES: &[(&[u8], u32)] = &[(b"sq0", 8), (b"sq1", 13)];

    #[test]
    fn valid_headers_equal_noodles() {
        let other: &[u8] = b"@HD\tVN:1.6\n@CO\tno sequences\n";
        let crlf: &[u8] = b"@HD\tVN:1.6\r\n@SQ\tSN:sq0\tLN:8\r\n@SQ\tSN:sq1\tLN:13\r\n";
        let unterminated: &[u8] = b"@HD\tVN:1.6\n@SQ\tSN:sq0\tLN:8\n@SQ\tSN:sq1\tLN:13";
        let mut padded = TEXT.to_vec();
        padded.resize(TEXT.len() + 100, 0);
        for (text, entries) in [
            (TEXT, ENTRIES),
            // No @SQ lines: the binary list fills the dictionary.
            (other, ENTRIES),
            (b"".as_slice(), ENTRIES),
            (b"".as_slice(), &[][..]),
            (other, &[][..]),
            // noodles collapses a repeated name when the text has no @SQ lines.
            (other, &[(b"sq0".as_slice(), 8), (b"sq0", 9)][..]),
            (crlf, ENTRIES),
            (unterminated, ENTRIES),
            (&padded[..], ENTRIES),
        ] {
            let header = same_as_noodles(&bam_of(text, entries)).unwrap();
            assert_eq!(header.reference_sequences().is_empty(), entries.is_empty());
        }
    }

    #[test]
    fn repeated_binary_names_are_collapsed_as_noodles_does() {
        // Accepted by noodles: the repeated name keeps its place and takes the last length.
        for entries in [
            &[(b"sq0".as_slice(), 8), (b"sq1", 13), (b"sq1", 13)][..],
            &[(b"sq0".as_slice(), 9), (b"sq0", 8), (b"sq1", 13)][..],
            &[(b"sq0".as_slice(), 8), (b"sq1", 5), (b"sq1", 13)][..],
            &[(b"sq0".as_slice(), 8), (b"sq1", 13), (b"sq0", 8)][..],
        ] {
            same_as_noodles(&bam_of(TEXT, entries)).unwrap();
        }
        // Rejected: the last length differs, or the order of first appearance does.
        for entries in [
            &[(b"sq0".as_slice(), 8), (b"sq1", 13), (b"sq1", 5)][..],
            &[(b"sq1".as_slice(), 13), (b"sq0", 8), (b"sq1", 13)][..],
        ] {
            mismatch(&bam_of(TEXT, entries));
        }
    }

    #[test]
    fn dictionaries_that_differ_are_rejected() {
        for entries in [
            &[(b"sqX".as_slice(), 8), (b"sq1", 13)][..],
            &[(b"sq0".as_slice(), 8), (b"sqX", 13)][..],
            &[(b"sq0".as_slice(), 8), (b"sq1", 14)][..],
            &[(b"sq0".as_slice(), 9), (b"sq1", 13)][..],
            &[(b"sq1".as_slice(), 13), (b"sq0", 8)][..],
            &[(b"sq0".as_slice(), 8)][..],
            &[(b"sq0".as_slice(), 8), (b"sq1", 13), (b"sq2", 5)][..],
            &[][..],
        ] {
            mismatch(&bam_of(TEXT, entries));
        }
    }

    #[test]
    fn errors_equal_noodles() {
        let named = |name: &'static [u8], l_ref| (u32::try_from(name.len()).unwrap(), name, l_ref);
        for src in [
            bam(b"BAM\x02", TEXT, &[]),
            bam(b"CRAM", TEXT, &[]),
            // Text that does not parse.
            bam(&MAGIC_NUMBER, b"@SQ\tSN:sq0\n", &[]),
            bam(
                &MAGIC_NUMBER,
                b"@SQ\tSN:sq0\tLN:8\n@SQ\tSN:sq0\tLN:8\n",
                &[],
            ),
            // l_name 0, a name without its NUL, a NUL inside a name, l_ref 0.
            bam(&MAGIC_NUMBER, TEXT, &[(0, b"", 8)]),
            bam(&MAGIC_NUMBER, TEXT, &[named(b"sq0", 8)]),
            bam(&MAGIC_NUMBER, TEXT, &[named(b"s\0q\0", 8)]),
            bam(&MAGIC_NUMBER, TEXT, &[named(b"sq0\0", 0)]),
            bam(&MAGIC_NUMBER, b"", &[named(b"sq0", 8)]),
            bam(&MAGIC_NUMBER, b"", &[named(b"sq0\0", 0)]),
            // A bad entry after a mismatch: noodles reads the whole list before comparing.
            bam(
                &MAGIC_NUMBER,
                TEXT,
                &[named(b"sqX\0", 8), named(b"sq1\0", 0)],
            ),
            bam(&MAGIC_NUMBER, TEXT, &[named(b"sq0\0", 9), (0, b"", 13)]),
        ] {
            let e = same_as_noodles(&src).unwrap_err();
            assert!(!e.to_string().contains("mismatch"), "{e}");
        }
    }

    #[test]
    fn every_truncation_fails_as_in_noodles() {
        let mismatched = [(b"sq0".as_slice(), 9), (b"sq1", 13)];
        for (text, entries) in [
            (TEXT, ENTRIES),
            (b"@HD\tVN:1.6\n".as_slice(), ENTRIES),
            (TEXT, &mismatched[..]),
        ] {
            let src = bam_of(text, entries);
            for cut in 0..src.len() - RECORDS.len() {
                same_as_noodles(&src[..cut]).unwrap_err();
            }
        }
    }
}