Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use BufReader for reading BAM files with file-like objects #68

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions oxbow/src/bam.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,22 @@ use noodles::{bam, bgzf, csi, sam};

use crate::batch_builder::{write_ipc_err, BatchBuilder};

pub fn index_from_reader<R>(mut read: R) -> io::Result<csi::Index>
pub fn index_from_reader<R>(read: R) -> io::Result<csi::Index>
where
R: Read + Seek,
{
// Unlike .tbi and .csi, .bai is not bgzf-compressed
// so we read off the magic directly.
let mut buf_read = std::io::BufReader::with_capacity(1024 * 1024, read);

let mut magic = [0; 4];
read.read_exact(&mut magic)?;
read.seek(io::SeekFrom::Start(0))?;
buf_read.read_exact(&mut magic)?;
buf_read.seek(io::SeekFrom::Start(0))?;
if magic == b"BAI\x01" as &[u8] {
let mut bai_reader = bam::bai::Reader::new(read);
let mut bai_reader = bam::bai::Reader::new(buf_read);
bai_reader.read_index()
} else {
let mut csi_reader = csi::Reader::new(read);
let mut csi_reader = csi::Reader::new(buf_read);
csi_reader.read_index()
}
}
Expand Down Expand Up @@ -71,10 +73,11 @@ impl BamReader<BufReader<File>> {
}
}

impl<R: Read + Seek> BamReader<R> {
impl<R: Read + Seek> BamReader<BufReader<R>> {
/// Creates a BAM reader.
pub fn new(read: R, index: csi::Index) -> std::io::Result<Self> {
let mut reader = bam::Reader::new(read);
let buf_read = std::io::BufReader::with_capacity(1024 * 1024, read);
let mut reader = bam::Reader::new(buf_read);
let header = reader.read_header()?;
Ok(Self {
reader,
Expand Down