Debian Codegraph @

src/base/read/io/locator.rs

raw symbols SCIP
1 // Copyright (c) 2022 Harry [Majored] [[email protected]]
2 // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE)
3
4 //! <https://github.com/Majored/rs-async-zip/blob/main/SPECIFICATION.md#4316>
5 //!
6 //! As with other ZIP libraries, we face the predicament that the end of central directory record may contain a
7 //! variable-length file comment. As a result, we cannot just make the assumption that the start of this record is
8 //! 18 bytes (the length of the EOCDR) offset from the end of the data - we must locate it ourselves.
9 //!
10 //! The `zip-rs` crate handles this by reading in reverse from the end of the data. This involves seeking backwards
11 //! by a single byte each iteration and reading 4 bytes into a u32. Whether this is performant/acceptable within a
12 //! a non-async context, I'm unsure, but it isn't desirable within an async context. Especially since we cannot just
13 //! place a [`BufReader`] infront of the upstream reader (as its internal buffer is invalidated on each seek).
14 //!
15 //! Reading in reverse is still desirable as the use of file comments is limited and they're unlikely to be large.
16 //!
17 //! The below method is one that compromises on these two contention points. Please submit an issue or PR if you know
18 //! of a better algorithm for this (and have tested/verified its performance).
19
20 #[cfg(doc)]
21 use futures_lite::io::BufReader;
22
23 use crate::error::{Result as ZipResult, ZipError};
24 use crate::spec::consts::{EOCDR_LENGTH, EOCDR_SIGNATURE, SIGNATURE_LENGTH};
25
26 use futures_lite::io::{AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt, SeekFrom};
27
28 /// The buffer size used when locating the EOCDR, equal to 2KiB.
29 const BUFFER_SIZE: usize = 2048;
30
31 /// The upper bound of where the EOCDR signature cannot be located.
32 const EOCDR_UPPER_BOUND: u64 = EOCDR_LENGTH as u64;
33
34 /// The lower bound of where the EOCDR signature cannot be located.
35 const EOCDR_LOWER_BOUND: u64 = EOCDR_UPPER_BOUND + SIGNATURE_LENGTH as u64 + u16::MAX as u64;
36
37 /// Locate the `end of central directory record` offset, if one exists.
38 /// The returned offset excludes the signature (4 bytes)
39 ///
40 /// This method involves buffered reading in reverse and reverse linear searching along those buffers for the EOCDR
41 /// signature. As a result of this buffered approach, we reduce seeks when compared to `zip-rs`'s method by a factor
42 /// of the buffer size. We also then don't have to do individual u32 reads against the upstream reader.
43 ///
44 /// Whilst I haven't done any in-depth benchmarks, when reading a ZIP file with the maximum length comment, this method
45 /// saw a reduction in location time by a factor of 500 when compared with the `zip-rs` method.
46 pub async fn eocdr<R>(mut reader: R) -> ZipResult<u64>
47 where
48 R: AsyncRead + AsyncSeek + Unpin,
49 {
50 let length = reader.seek(SeekFrom::End(0)).await?;
51 let signature = &EOCDR_SIGNATURE.to_le_bytes();
52 let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
53
54 let mut position = length.saturating_sub(BUFFER_SIZE as u64);
55 reader.seek(SeekFrom::Start(position)).await?;
56
57 loop {
58 let mut read = 0;
59
60 // Read repeatedly until eof or the buffer is full.
61 while read < BUFFER_SIZE {
62 let bytes_read = reader.read(&mut buffer[read..]).await?;
63 if bytes_read == 0 {
64 break;
65 }
66 read += bytes_read;
67 }
68
69 if let Some(match_index) = reverse_search_buffer(&buffer[..read], signature) {
70 return Ok(position + (match_index + 1) as u64);
71 }
72
73 // If we hit the start of the data or the lower bound, we're unable to locate the EOCDR.
74 if position == 0 || position <= length.saturating_sub(EOCDR_LOWER_BOUND) {
75 return Err(ZipError::UnableToLocateEOCDR);
76 }
77
78 // To handle the case where the EOCDR signature crosses buffer boundaries, we simply overlap reads by the
79 // signature length. This significantly reduces the complexity of handling partial matches with very little
80 // overhead.
81 position = position.saturating_sub((BUFFER_SIZE - SIGNATURE_LENGTH) as u64);
82 reader.seek(SeekFrom::Start(position)).await?;
83 }
84 }
85
86 /// A naive reverse linear search along the buffer for the specified signature bytes.
87 ///
88 /// This is already surprisingly performant. For instance, using memchr::memchr() to match for the first byte of the
89 /// signature, and then manual byte comparisons for the remaining signature bytes was actually slower by a factor of
90 /// 2.25. This method was explored as tokio's `read_until()` implementation uses memchr::memchr().
91 pub(crate) fn reverse_search_buffer(buffer: &[u8], signature: &[u8]) -> Option<usize> {
92 'outer: for index in (0..buffer.len()).rev() {
93 for (signature_index, signature_byte) in signature.iter().rev().enumerate() {
94 if let Some(next_index) = index.checked_sub(signature_index) {
95 if buffer[next_index] != *signature_byte {
96 continue 'outer;
97 }
98 } else {
99 break 'outer;
100 }
101 }
102 return Some(index);
103 }
104 None
105 }