Debian Codegraph @

src/base/read/stream.rs

raw symbols SCIP
1 // Copyright (c) 2023 Harry [Majored] [[email protected]]
2 // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE)
3
4 //! A ZIP reader which acts over a non-seekable source.
5 //!
6 //! # API Design
7 //! As opposed to other readers provided by this crate, it's important that the data of an entry is fully read before
8 //! the proceeding entry is read. This is as a result of not being able to seek forwards or backwards, so we must end
9 //! up at the start of the next entry.
10 //!
11 //! **We encode this invariant within Rust's type system so that it can be enforced at compile time.**
12 //!
13 //! This requires that any transition methods between these encoded types consume the reader and provide a new owned
14 //! reader back. This is certainly something to keep in mind when working with this reader, but idiomatic code can
15 //! still be produced nevertheless.
16 //!
17 //! # Considerations
18 //! As the central directory of a ZIP archive is stored at the end of it, a non-seekable reader doesn't have access
19 //! to it. We have to rely on information provided within the local file header which may not be accurate or complete.
20 //! This results in:
21 //! - The inability to read ZIP entries using the combination of a data descriptor and the Stored compression method.
22 //! - No file comment being available (defaults to an empty string).
23 //! - No internal or external file attributes being available (defaults to 0).
24 //! - The extra field data potentially being inconsistent with what's stored in the central directory.
25 //! - None of the following being available when the entry was written with a data descriptor (defaults to 0):
26 //! - CRC
27 //! - compressed size
28 //! - uncompressed size
29 //!
30 //! # Example
31 //! ```no_run
32 //! # use futures_lite::io::Cursor;
33 //! # use async_zip::error::Result;
34 //! # use async_zip::base::read::stream::ZipFileReader;
35 //! #
36 //! # async fn run() -> Result<()> {
37 //! let mut zip = ZipFileReader::new(Cursor::new([0; 0]));
38 //!
39 //! // Print the name of every file in a ZIP archive.
40 //! while let Some(entry) = zip.next_with_entry().await? {
41 //! println!("File: {}", entry.reader().entry().filename().as_str().unwrap());
42 //! zip = entry.skip().await?;
43 //! }
44 //! #
45 //! # Ok(())
46 //! # }
47 //! ```
48
49 use crate::base::read::io::entry::ZipEntryReader;
50 use crate::error::Result;
51 use crate::error::ZipError;
52
53 use crate::spec::consts::DATA_DESCRIPTOR_LENGTH;
54 use crate::spec::consts::DATA_DESCRIPTOR_SIGNATURE;
55 use crate::spec::consts::SIGNATURE_LENGTH;
56 #[cfg(feature = "tokio")]
57 use crate::tokio::read::stream::Ready as TokioReady;
58
59 use futures_lite::io::AsyncBufRead;
60 use futures_lite::io::AsyncReadExt;
61
62 #[cfg(feature = "tokio")]
63 use tokio_util::compat::TokioAsyncReadCompatExt;
64
65 use super::io::entry::WithEntry;
66 use super::io::entry::WithoutEntry;
67
68 /// A type which encodes that [`ZipFileReader`] is ready to open a new entry.
69 pub struct Ready<R>(R);
70
71 /// A type which encodes that [`ZipFileReader`] is currently reading an entry.
72 pub struct Reading<'a, R, E>(ZipEntryReader<'a, R, E>, bool);
73
74 /// A ZIP reader which acts over a non-seekable source.
75 ///
76 /// See the [module-level docs](.) for more information.
77 #[derive(Clone)]
78 pub struct ZipFileReader<S>(S);
79
80 impl<'a, R> ZipFileReader<Ready<R>>
81 where
82 R: AsyncBufRead + Unpin + 'a,
83 {
84 /// Constructs a new ZIP reader from a non-seekable source.
85 pub fn new(reader: R) -> Self {
86 Self(Ready(reader))
87 }
88
89 /// Opens the next entry for reading if the central directory hasn’t yet been reached.
90 pub async fn next_without_entry(mut self) -> Result<Option<ZipFileReader<Reading<'a, R, WithoutEntry>>>> {
91 let entry = match crate::base::read::lfh(&mut self.0 .0).await? {
92 Some(entry) => entry,
93 None => return Ok(None),
94 };
95
96 let length = if entry.data_descriptor { u64::MAX } else { entry.compressed_size };
97 let reader = ZipEntryReader::new_with_owned(self.0 .0, entry.compression, length);
98
99 Ok(Some(ZipFileReader(Reading(reader, entry.data_descriptor))))
100 }
101
102 /// Opens the next entry for reading if the central directory hasn’t yet been reached.
103 pub async fn next_with_entry(mut self) -> Result<Option<ZipFileReader<Reading<'a, R, WithEntry<'a>>>>> {
104 let entry = match crate::base::read::lfh(&mut self.0 .0).await? {
105 Some(entry) => entry,
106 None => return Ok(None),
107 };
108
109 let length = if entry.data_descriptor { u64::MAX } else { entry.compressed_size };
110 let reader = ZipEntryReader::new_with_owned(self.0 .0, entry.compression, length);
111 let data_descriptor = entry.data_descriptor;
112
113 Ok(Some(ZipFileReader(Reading(reader.into_with_entry_owned(entry), data_descriptor))))
114 }
115
116 /// Consumes the `ZipFileReader` returning the original `reader`
117 pub async fn into_inner(self) -> R {
118 self.0 .0
119 }
120 }
121
122 #[cfg(feature = "tokio")]
123 impl<R> ZipFileReader<TokioReady<R>>
124 where
125 R: tokio::io::AsyncBufRead + Unpin,
126 {
127 /// Constructs a new tokio-specific ZIP reader from a non-seekable source.
128 pub fn with_tokio(reader: R) -> ZipFileReader<TokioReady<R>> {
129 Self(Ready(reader.compat()))
130 }
131 }
132
133 impl<'a, R, E> ZipFileReader<Reading<'a, R, E>>
134 where
135 R: AsyncBufRead + Unpin,
136 {
137 /// Returns an immutable reference to the inner entry reader.
138 pub fn reader(&self) -> &ZipEntryReader<'a, R, E> {
139 &self.0 .0
140 }
141
142 /// Returns a mutable reference to the inner entry reader.
143 pub fn reader_mut(&mut self) -> &mut ZipEntryReader<'a, R, E> {
144 &mut self.0 .0
145 }
146
147 /// Converts the reader back into the Ready state if EOF has been reached.
148 pub async fn done(mut self) -> Result<ZipFileReader<Ready<R>>> {
149 if self.0 .0.read(&mut [0; 1]).await? != 0 {
150 return Err(ZipError::EOFNotReached);
151 }
152
153 let mut inner = self.0 .0.into_inner();
154
155 // Has data descriptor.
156 if self.0 .1 {
157 consume_data_descriptor(&mut inner).await?;
158 }
159
160 Ok(ZipFileReader(Ready(inner)))
161 }
162
163 /// Reads until EOF and converts the reader back into the Ready state.
164 pub async fn skip(mut self) -> Result<ZipFileReader<Ready<R>>> {
165 while self.0 .0.read(&mut [0; 2048]).await? != 0 {}
166 let mut inner = self.0 .0.into_inner();
167
168 // Has data descriptor.
169 if self.0 .1 {
170 consume_data_descriptor(&mut inner).await?;
171 }
172
173 Ok(ZipFileReader(Ready(inner)))
174 }
175 }
176
177 async fn consume_data_descriptor<R: AsyncBufRead + Unpin>(reader: &mut R) -> Result<()> {
178 let mut descriptor: [u8; DATA_DESCRIPTOR_LENGTH] = [0; DATA_DESCRIPTOR_LENGTH];
179 reader.read_exact(&mut descriptor).await?;
180
181 if descriptor[0..SIGNATURE_LENGTH] == DATA_DESCRIPTOR_SIGNATURE.to_le_bytes() {
182 let mut tail: [u8; SIGNATURE_LENGTH] = [0; SIGNATURE_LENGTH];
183 reader.read_exact(&mut tail).await?;
184 }
185
186 Ok(())
187 }