Skip to content

Commit

Permalink
bam/io/reader/header/magic_number: Split read and validation
Browse files Browse the repository at this point in the history
  • Loading branch information
zaeleus committed Dec 10, 2024
1 parent a19e023 commit 85c0434
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
8 changes: 4 additions & 4 deletions noodles-bam/src/io/reader/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ where
}

fn read_magic_number(&mut self) -> io::Result<[u8; MAGIC_NUMBER.len()]> {
let mut buf = [0; MAGIC_NUMBER.len()];
self.inner.read_exact(&mut buf)?;
Ok(buf)
read_magic_number(self.inner)
}

fn raw_sam_header_reader(&mut self) -> io::Result<sam_header::Reader<R>> {
Expand All @@ -50,7 +48,9 @@ fn read_header_inner<R>(reader: &mut Reader<R>) -> io::Result<sam::Header>
where
R: Read,
{
read_magic_number(reader)?;
reader
.read_magic_number()
.and_then(magic_number::validate)?;

let mut raw_sam_header_reader = reader.raw_sam_header_reader()?;
let mut header = read_sam_header(&mut raw_sam_header_reader)?;
Expand Down
41 changes: 24 additions & 17 deletions noodles-bam/src/io/reader/header/magic_number.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
use std::io::{self, Read};

use super::Reader;
use crate::MAGIC_NUMBER;

pub(super) fn read_magic_number<R>(reader: &mut Reader<R>) -> io::Result<()>
type Buf = [u8; MAGIC_NUMBER.len()];

pub(super) fn read_magic_number<R>(reader: &mut R) -> io::Result<Buf>
where
R: Read,
{
let magic_number = reader.read_magic_number()?;
let mut buf = [0; MAGIC_NUMBER.len()];
reader.read_exact(&mut buf)?;
Ok(buf)
}

if magic_number == MAGIC_NUMBER {
pub(super) fn validate(buf: Buf) -> io::Result<()> {
if is_valid(buf) {
Ok(())
} else {
Err(io::Error::new(
Expand All @@ -19,30 +24,32 @@ where
}
}

fn is_valid(buf: Buf) -> bool {
buf == MAGIC_NUMBER
}

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

#[test]
fn test_read_magic_number() -> io::Result<()> {
let mut src = &b"BAM\x01"[..];
let mut reader = Reader::new(&mut src);
assert!(read_magic_number(&mut reader).is_ok());
let src = b"BAM\x01";
let mut reader = &src[..];
assert_eq!(read_magic_number(&mut reader)?, *b"BAM\x01");

let mut src = &[][..];
let mut reader = Reader::new(&mut src);
assert!(matches!(
read_magic_number(&mut reader),
Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof
));

let mut src = &b"MThd"[..];
let mut reader = Reader::new(&mut src);
assert!(matches!(
read_magic_number(&mut reader),
Err(ref e) if e.kind() == io::ErrorKind::InvalidData
read_magic_number(&mut src),
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof
));

Ok(())
}

#[test]
fn test_is_valid() {
assert!(is_valid(*b"BAM\x01"));
assert!(!is_valid([0x00, 0x00, 0x00, 0x00]));
}
}

0 comments on commit 85c0434

Please sign in to comment.