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

✨ Add libpna::read_as_chunks #1193

Merged
merged 2 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions lib/src/archive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
compress::CompressionWriter,
};
pub use header::*;
pub(crate) use read::*;
use std::io::prelude::*;

/// An object providing access to a PNA file.
Expand Down
2 changes: 1 addition & 1 deletion lib/src/archive/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::{
mem::swap,
};

fn read_pna_header<R: Read>(mut reader: R) -> io::Result<()> {
pub(crate) fn read_pna_header<R: Read>(mut reader: R) -> io::Result<()> {
let mut header = [0u8; PNA_HEADER.len()];
reader.read_exact(&mut header)?;
if &header != PNA_HEADER {
Expand Down
46 changes: 45 additions & 1 deletion lib/src/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub(crate) use self::{
pub use self::{traits::*, types::*};
use std::{
borrow::Cow,
io::{self, Write},
io::{self, prelude::*},
mem,
ops::Deref,
};
Expand Down Expand Up @@ -281,6 +281,50 @@ pub(crate) fn chunk_data_split(
)
}

/// Read archive as chunks
///
/// # Example
///
/// ```no_run
/// # use std::{io, fs};
/// use libpna::{prelude::*, read_as_chunks};
/// # fn main() -> io::Result<()> {
/// let archive = fs::File::open("foo.pna")?;
/// for chunk in read_as_chunks(archive)? {
/// let chunk = chunk?;
/// println!("chunk type: {}, chunk data size: {}", chunk.ty(), chunk.length());
/// }
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn read_as_chunks<R: Read>(
mut archive: R,
) -> io::Result<impl Iterator<Item = io::Result<impl Chunk>>> {
struct Chunks<R> {
reader: ChunkReader<R>,
eoa: bool,
}
impl<R: Read> Iterator for Chunks<R> {
type Item = io::Result<RawChunk>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.eoa {
return None;
}
Some(self.reader.read_chunk().inspect(|chunk| {
self.eoa = chunk.ty() == ChunkType::AEND;
}))
}
}
crate::archive::read_pna_header(&mut archive)?;

Ok(Chunks {
reader: ChunkReader::from(archive),
eoa: false,
})
}
Fixed Show fixed Hide fixed

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