diff --git a/noodles-bam/src/async/io/reader.rs b/noodles-bam/src/async/io/reader.rs index f5a5055d2..016189248 100644 --- a/noodles-bam/src/async/io/reader.rs +++ b/noodles-bam/src/async/io/reader.rs @@ -10,9 +10,14 @@ use noodles_bgzf as bgzf; use noodles_core::Region; use noodles_csi::BinningIndex; use noodles_sam::{self as sam, alignment::RecordBuf}; -use tokio::io::{self, AsyncRead, AsyncReadExt, AsyncSeek}; +use tokio::io::{self, AsyncRead, AsyncSeek}; -use self::{header::read_header, query::query, record::read_record, record_buf::read_record_buf}; +use self::{ + header::{magic_number::read_magic_number, read_header}, + query::query, + record::read_record, + record_buf::read_record_buf, +}; use crate::{io::reader::resolve_region, Record, MAGIC_NUMBER}; /// An async BAM reader. @@ -427,8 +432,7 @@ async fn read_magic(reader: &mut R) -> io::Result<()> where R: AsyncRead + Unpin, { - let mut magic = [0; 4]; - reader.read_exact(&mut magic).await?; + let magic = read_magic_number(reader).await?; if magic == MAGIC_NUMBER { Ok(()) diff --git a/noodles-bam/src/async/io/reader/header.rs b/noodles-bam/src/async/io/reader/header.rs index 0eecc8dd8..9536b9a96 100644 --- a/noodles-bam/src/async/io/reader/header.rs +++ b/noodles-bam/src/async/io/reader/header.rs @@ -1,3 +1,4 @@ +pub(super) mod magic_number; mod reference_sequences; use noodles_sam as sam; diff --git a/noodles-bam/src/async/io/reader/header/magic_number.rs b/noodles-bam/src/async/io/reader/header/magic_number.rs new file mode 100644 index 000000000..7228827e2 --- /dev/null +++ b/noodles-bam/src/async/io/reader/header/magic_number.rs @@ -0,0 +1,32 @@ +use tokio::io::{self, AsyncRead, AsyncReadExt}; + +use crate::MAGIC_NUMBER; + +pub(crate) async fn read_magic_number(reader: &mut R) -> io::Result<[u8; MAGIC_NUMBER.len()]> +where + R: AsyncRead + Unpin, +{ + let mut buf = [0; MAGIC_NUMBER.len()]; + reader.read_exact(&mut buf).await?; + Ok(buf) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_read_magic_number() -> io::Result<()> { + let src = b"BAM\x01"; + let mut reader = &src[..]; + assert_eq!(read_magic_number(&mut reader).await?, *b"BAM\x01"); + + let mut src = &[][..]; + assert!(matches!( + read_magic_number(&mut src).await, + Err(e) if e.kind() == io::ErrorKind::UnexpectedEof + )); + + Ok(()) + } +}