Skip to content

Commit

Permalink
bam/async/io/reader/header: Add magic number reader
Browse files Browse the repository at this point in the history
  • Loading branch information
zaeleus committed Dec 16, 2024
1 parent 90beb32 commit 8da1688
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
12 changes: 8 additions & 4 deletions noodles-bam/src/async/io/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -427,8 +432,7 @@ async fn read_magic<R>(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(())
Expand Down
1 change: 1 addition & 0 deletions noodles-bam/src/async/io/reader/header.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub(super) mod magic_number;
mod reference_sequences;

use noodles_sam as sam;
Expand Down
32 changes: 32 additions & 0 deletions noodles-bam/src/async/io/reader/header/magic_number.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use tokio::io::{self, AsyncRead, AsyncReadExt};

use crate::MAGIC_NUMBER;

pub(crate) async fn read_magic_number<R>(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(())
}
}

0 comments on commit 8da1688

Please sign in to comment.