1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
//! Async BGZF reader.
mod builder;
mod inflate;
mod inflater;
use std::{
cmp, io,
num::NonZeroUsize,
pin::Pin,
task::{ready, Context, Poll},
};
use futures::{stream::TryBuffered, Stream, TryStreamExt};
use pin_project_lite::pin_project;
use tokio::io::{AsyncBufRead, AsyncRead, AsyncSeek, ReadBuf};
pub use self::builder::Builder;
use self::inflater::Inflater;
use crate::{gzi, Block, VirtualPosition};
pin_project! {
/// An async BGZF reader.
pub struct Reader<R>
where
R: AsyncRead,
{
#[pin]
stream: Option<TryBuffered<Inflater<R>>>,
block: Block,
position: u64,
worker_count: NonZeroUsize,
}
}
impl<R> Reader<R>
where
R: AsyncRead,
{
/// Creates an async BGZF reader.
///
/// # Examples
///
/// ```
/// use noodles_bgzf as bgzf;
/// let data = [];
/// let reader = bgzf::AsyncReader::new(&data[..]);
/// ```
pub fn new(inner: R) -> Self {
Builder::default().build_from_reader(inner)
}
/// Returns a reference to the underlying reader.
///
/// # Examples
///
/// ```
/// use noodles_bgzf as bgzf;
/// let data = [];
/// let reader = bgzf::AsyncReader::new(&data[..]);
/// assert!(reader.get_ref().is_empty());
/// ```
pub fn get_ref(&self) -> &R {
let stream = self.stream.as_ref().expect("missing stream");
stream.get_ref().get_ref()
}
/// Returns a mutable reference to the underlying stream.
///
/// # Examples
///
/// ```
/// use noodles_bgzf as bgzf;
/// let data = [];
/// let mut reader = bgzf::AsyncReader::new(&data[..]);
/// assert!(reader.get_mut().is_empty());
/// ```
pub fn get_mut(&mut self) -> &mut R {
let stream = self.stream.as_mut().expect("missing stream");
stream.get_mut().get_mut()
}
/// Returns a pinned mutable reference to the underlying stream.
///
/// # Examples
///
/// ```
/// # use std::pin::Pin;
/// use noodles_bgzf as bgzf;
/// let data = [];
/// let mut reader = bgzf::AsyncReader::new(&data[..]);
/// let mut pinned_reader = Pin::new(&mut reader);
/// assert!(pinned_reader.get_pin_mut().get_mut().is_empty());
/// ```
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R> {
let stream = self.project().stream.as_pin_mut().expect("missing stream");
stream.get_pin_mut().get_pin_mut()
}
/// Unwraps and returns the underlying stream.
///
/// # Examples
///
/// ```
/// use noodles_bgzf as bgzf;
/// let data = [];
/// let reader = bgzf::AsyncReader::new(&data[..]);
/// assert!(reader.into_inner().is_empty());
/// ```
pub fn into_inner(self) -> R {
let stream = self.stream.expect("missing stream");
stream.into_inner().into_inner()
}
/// Returns the current virtual position of the stream.
///
/// # Examples
///
/// ```
/// # use std::io;
/// use noodles_bgzf as bgzf;
/// let data = [];
/// let reader = bgzf::AsyncReader::new(&data[..]);
/// assert_eq!(reader.virtual_position(), bgzf::VirtualPosition::from(0));
/// # Ok::<(), io::Error>(())
/// ```
pub fn virtual_position(&self) -> VirtualPosition {
self.block.virtual_position()
}
}
impl<R> Reader<R>
where
R: AsyncRead + AsyncSeek + Unpin,
{
/// Seeks the stream to the given virtual position.
///
/// # Examples
///
/// ```
/// # use std::io::{self, Cursor};
/// #
/// # #[tokio::main]
/// # async fn main() -> io::Result<()> {
/// use noodles_bgzf as bgzf;
/// let mut reader = bgzf::AsyncReader::new(Cursor::new(Vec::new()));
/// let virtual_position = bgzf::VirtualPosition::from(102334155);
/// reader.seek(virtual_position).await?;
/// # Ok(())
/// # }
/// ```
pub async fn seek(&mut self, pos: VirtualPosition) -> io::Result<VirtualPosition> {
let stream = self.stream.take().expect("missing stream");
let mut blocks = stream.into_inner();
blocks.seek(pos).await?;
let mut stream = blocks.try_buffered(self.worker_count.get());
self.block = match stream.try_next().await? {
Some(mut block) => {
let (cpos, upos) = pos.into();
self.position = cpos + block.size();
block.set_position(cpos);
block.data_mut().set_position(usize::from(upos));
block
}
None => Block::default(),
};
self.stream.replace(stream);
Ok(pos)
}
/// Seeks the stream to the given uncompressed position.
///
/// # Examples
///
/// ```
/// # use std::io::Cursor;
///
/// # #[tokio::main]
/// # async fn main() -> tokio::io::Result<()> {
/// use noodles_bgzf as bgzf;
/// use tokio::io;
///
/// let mut reader = bgzf::AsyncReader::new(Cursor::new(Vec::new()));
///
/// let index = vec![(0, 0)];
/// reader.seek_by_uncompressed_position(&index, 0).await?;
/// # Ok(())
/// # }
/// ```
pub async fn seek_by_uncompressed_position(
&mut self,
index: &gzi::Index,
pos: u64,
) -> io::Result<u64> {
assert!(!index.is_empty());
let i = index.partition_point(|r| r.1 <= pos);
// SAFETY: `i` is > 0.
let record = index[i - 1];
let cpos = record.0;
let upos = u16::try_from(pos - record.1)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let virtual_position = VirtualPosition::try_from((cpos, upos))
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
self.seek(virtual_position).await?;
Ok(pos)
}
}
impl<R> AsyncRead for Reader<R>
where
R: AsyncRead,
{
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let src = ready!(self.as_mut().poll_fill_buf(cx))?;
let amt = cmp::min(src.len(), buf.remaining());
buf.put_slice(&src[..amt]);
self.consume(amt);
Poll::Ready(Ok(()))
}
}
impl<R> AsyncBufRead for Reader<R>
where
R: AsyncRead,
{
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
let this = self.project();
if !this.block.data().has_remaining() {
let mut stream = this.stream.as_pin_mut().expect("missing stream");
loop {
match ready!(stream.as_mut().poll_next(cx)) {
Some(Ok(mut block)) => {
block.set_position(*this.position);
*this.position += block.size();
let data_len = block.data().len();
*this.block = block;
if data_len > 0 {
break;
}
}
Some(Err(e)) => return Poll::Ready(Err(e)),
None => return Poll::Ready(Ok(&[])),
}
}
}
return Poll::Ready(Ok(this.block.data().as_ref()));
}
fn consume(self: Pin<&mut Self>, amt: usize) {
let this = self.project();
this.block.data_mut().consume(amt);
}
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use tokio::io::AsyncReadExt;
use super::*;
#[tokio::test]
async fn test_read_with_empty_block() -> io::Result<()> {
#[rustfmt::skip]
let data = [
// block 0 (b"noodles")
0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43,
0x02, 0x00, 0x22, 0x00, 0xcb, 0xcb, 0xcf, 0x4f, 0xc9, 0x49, 0x2d, 0x06, 0x00, 0xa1,
0x58, 0x2a, 0x80, 0x07, 0x00, 0x00, 0x00,
// block 1 (b"")
0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43,
0x02, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// block 2 (b"bgzf")
0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43,
0x02, 0x00, 0x1f, 0x00, 0x4b, 0x4a, 0xaf, 0x4a, 0x03, 0x00, 0x20, 0x68, 0xf2, 0x8c,
0x04, 0x00, 0x00, 0x00,
// EOF block
0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43,
0x02, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
let mut reader = Reader::new(&data[..]);
let mut buf = Vec::new();
reader.read_to_end(&mut buf).await?;
assert_eq!(buf, b"noodlesbgzf");
Ok(())
}
#[tokio::test]
async fn test_seek() -> Result<(), Box<dyn std::error::Error>> {
#[rustfmt::skip]
let data = [
// block 0, udata = b"noodles"
0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43,
0x02, 0x00, 0x22, 0x00, 0xcb, 0xcb, 0xcf, 0x4f, 0xc9, 0x49, 0x2d, 0x06, 0x00, 0xa1,
0x58, 0x2a, 0x80, 0x07, 0x00, 0x00, 0x00,
// EOF block
0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43,
0x02, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
let mut reader = Reader::new(Cursor::new(&data));
let mut buf = Vec::new();
reader.read_to_end(&mut buf).await?;
let eof = VirtualPosition::try_from((63, 0))?;
assert_eq!(reader.virtual_position(), eof);
let position = VirtualPosition::try_from((0, 3))?;
reader.seek(position).await?;
assert_eq!(reader.virtual_position(), position);
buf.clear();
reader.read_to_end(&mut buf).await?;
assert_eq!(buf, b"dles");
assert_eq!(reader.virtual_position(), eof);
Ok(())
}
}