| 1 |
//! Code related to the MagicFinder |
| 2 |
|
| 3 |
use crate::result::ZipResult; |
| 4 |
use memchr::memmem::{Finder, FinderRev}; |
| 5 |
use std::io::{Read, Seek, SeekFrom}; |
| 6 |
|
| 7 |
const MAGIC_LENGTH: usize = 4; |
| 8 |
type MagicLengthByteArray = [u8; MAGIC_LENGTH]; |
| 9 |
|
| 10 |
pub(crate) trait FinderDirection<'a, B> { |
| 11 |
fn new(needle: &'a B) -> Self; |
| 12 |
fn reset_cursor(bounds: (u64, u64), window_size: usize) -> u64; |
| 13 |
fn scope_window(window: &[u8], mid_window_offset: usize) -> (&[u8], usize); |
| 14 |
fn needle(&self) -> &[u8]; |
| 15 |
fn find(&self, haystack: &[u8]) -> Option<usize>; |
| 16 |
fn move_cursor(&self, cursor: u64, bounds: (u64, u64), window_size: usize) -> Option<u64>; |
| 17 |
fn move_scope(&self, offset: usize) -> usize; |
| 18 |
} |
| 19 |
|
| 20 |
pub(crate) struct Forward<'a>(Finder<'a>); |
| 21 |
impl<'a> FinderDirection<'a, MagicLengthByteArray> for Forward<'a> { |
| 22 |
fn new(needle: &'a MagicLengthByteArray) -> Self { |
| 23 |
Self(Finder::new(needle)) |
| 24 |
} |
| 25 |
|
| 26 |
fn reset_cursor((start_inclusive, _): (u64, u64), _: usize) -> u64 { |
| 27 |
start_inclusive |
| 28 |
} |
| 29 |
|
| 30 |
fn scope_window(window: &[u8], mid_window_offset: usize) -> (&[u8], usize) { |
| 31 |
(&window[mid_window_offset..], mid_window_offset) |
| 32 |
} |
| 33 |
|
| 34 |
fn find(&self, haystack: &[u8]) -> Option<usize> { |
| 35 |
self.0.find(haystack) |
| 36 |
} |
| 37 |
|
| 38 |
fn needle(&self) -> &[u8] { |
| 39 |
self.0.needle() |
| 40 |
} |
| 41 |
|
| 42 |
fn move_cursor(&self, cursor: u64, bounds: (u64, u64), window_size: usize) -> Option<u64> { |
| 43 |
let magic_overlap = MAGIC_LENGTH.saturating_sub(1) as u64; |
| 44 |
let next = cursor.saturating_add(window_size as u64 - magic_overlap); |
| 45 |
|
| 46 |
if next >= bounds.1 { None } else { Some(next) } |
| 47 |
} |
| 48 |
|
| 49 |
fn move_scope(&self, offset: usize) -> usize { |
| 50 |
offset + MAGIC_LENGTH |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
pub(crate) struct Backwards<'a>(FinderRev<'a>); |
| 55 |
impl<'a> FinderDirection<'a, MagicLengthByteArray> for Backwards<'a> { |
| 56 |
fn new(needle: &'a MagicLengthByteArray) -> Self { |
| 57 |
Self(FinderRev::new(needle)) |
| 58 |
} |
| 59 |
|
| 60 |
fn reset_cursor(bounds: (u64, u64), window_size: usize) -> u64 { |
| 61 |
bounds |
| 62 |
.1 |
| 63 |
.saturating_sub(window_size as u64) |
| 64 |
.clamp(bounds.0, bounds.1) |
| 65 |
} |
| 66 |
|
| 67 |
fn scope_window(window: &[u8], mid_window_offset: usize) -> (&[u8], usize) { |
| 68 |
(&window[..mid_window_offset], 0) |
| 69 |
} |
| 70 |
|
| 71 |
fn find(&self, haystack: &[u8]) -> Option<usize> { |
| 72 |
self.0.rfind(haystack) |
| 73 |
} |
| 74 |
|
| 75 |
fn needle(&self) -> &[u8] { |
| 76 |
self.0.needle() |
| 77 |
} |
| 78 |
|
| 79 |
fn move_cursor(&self, cursor: u64, bounds: (u64, u64), window_size: usize) -> Option<u64> { |
| 80 |
let magic_overlap = MAGIC_LENGTH.saturating_sub(1) as u64; |
| 81 |
|
| 82 |
if cursor <= bounds.0 { |
| 83 |
None |
| 84 |
} else { |
| 85 |
Some( |
| 86 |
cursor |
| 87 |
.saturating_add(magic_overlap) |
| 88 |
.saturating_sub(window_size as u64) |
| 89 |
.clamp(bounds.0, bounds.1), |
| 90 |
) |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
fn move_scope(&self, offset: usize) -> usize { |
| 95 |
offset |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
/// The buffer size that the finder will search |
| 100 |
const BUFFER_SIZE: usize = 1024; |
| 101 |
|
| 102 |
/// A utility for finding magic symbols from the end of a seekable reader. |
| 103 |
/// |
| 104 |
/// Can be repurposed to recycle the internal buffer. |
| 105 |
pub(crate) struct MagicFinder<Direction> { |
| 106 |
buffer: [u8; BUFFER_SIZE], |
| 107 |
pub(self) finder: Direction, |
| 108 |
cursor: u64, |
| 109 |
mid_buffer_offset: Option<usize>, |
| 110 |
bounds: (u64, u64), |
| 111 |
} |
| 112 |
|
| 113 |
impl<'a, T: FinderDirection<'a, MagicLengthByteArray>> MagicFinder<T> { |
| 114 |
/// Create a new magic bytes finder to look within specific bounds. |
| 115 |
pub(crate) fn new( |
| 116 |
magic_bytes: &'a MagicLengthByteArray, |
| 117 |
start_inclusive: u64, |
| 118 |
end_exclusive: u64, |
| 119 |
) -> Self { |
| 120 |
Self { |
| 121 |
buffer: [0; BUFFER_SIZE], |
| 122 |
finder: T::new(magic_bytes), |
| 123 |
cursor: T::reset_cursor((start_inclusive, end_exclusive), BUFFER_SIZE), |
| 124 |
mid_buffer_offset: None, |
| 125 |
bounds: (start_inclusive, end_exclusive), |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
/// Repurpose the finder for different bytes or bounds. |
| 130 |
pub(crate) fn repurpose( |
| 131 |
&mut self, |
| 132 |
magic_bytes: &'a MagicLengthByteArray, |
| 133 |
bounds: (u64, u64), |
| 134 |
) -> &mut Self { |
| 135 |
self.finder = T::new(magic_bytes); |
| 136 |
self.cursor = T::reset_cursor(bounds, self.buffer.len()); |
| 137 |
self.bounds = bounds; |
| 138 |
|
| 139 |
// Reset the mid-buffer offset, to invalidate buffer content. |
| 140 |
self.mid_buffer_offset = None; |
| 141 |
|
| 142 |
self |
| 143 |
} |
| 144 |
|
| 145 |
/// Find the next magic bytes in the direction specified in the type. |
| 146 |
pub(crate) fn next<R: Read + Seek + ?Sized>( |
| 147 |
&mut self, |
| 148 |
reader: &mut R, |
| 149 |
) -> ZipResult<Option<u64>> { |
| 150 |
loop { |
| 151 |
if self.cursor < self.bounds.0 || self.cursor >= self.bounds.1 { |
| 152 |
// The finder is consumed |
| 153 |
break; |
| 154 |
} |
| 155 |
|
| 156 |
/* Position the window and ensure correct length */ |
| 157 |
let window_start = self.cursor; |
| 158 |
let window_end = self |
| 159 |
.cursor |
| 160 |
.saturating_add(self.buffer.len() as u64) |
| 161 |
.min(self.bounds.1); |
| 162 |
|
| 163 |
if window_end <= window_start { |
| 164 |
// Short-circuit on zero-sized windows to prevent loop |
| 165 |
break; |
| 166 |
} |
| 167 |
|
| 168 |
let window = &mut self.buffer[..(window_end - window_start) as usize]; |
| 169 |
|
| 170 |
if self.mid_buffer_offset.is_none() { |
| 171 |
reader.seek(SeekFrom::Start(window_start))?; |
| 172 |
if let Err(e) = reader.read_exact(window) { |
| 173 |
if e.kind() == std::io::ErrorKind::UnexpectedEof { |
| 174 |
// If we can't read the whole window, it means the bounds or file length are wrong. |
| 175 |
break; |
| 176 |
} |
| 177 |
return Err(e.into()); |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
let (window, window_start_offset) = match self.mid_buffer_offset { |
| 182 |
Some(mid_buffer_offset) => T::scope_window(window, mid_buffer_offset), |
| 183 |
None => (&*window, 0usize), |
| 184 |
}; |
| 185 |
|
| 186 |
if let Some(offset) = self.finder.find(window) { |
| 187 |
let magic_pos = window_start + window_start_offset as u64 + offset as u64; |
| 188 |
reader.seek(SeekFrom::Start(magic_pos))?; |
| 189 |
|
| 190 |
self.mid_buffer_offset = Some(self.finder.move_scope(window_start_offset + offset)); |
| 191 |
|
| 192 |
return Ok(Some(magic_pos)); |
| 193 |
} |
| 194 |
|
| 195 |
self.mid_buffer_offset = None; |
| 196 |
|
| 197 |
if let Some(new_cursor) = |
| 198 |
self.finder |
| 199 |
.move_cursor(self.cursor, self.bounds, self.buffer.len()) |
| 200 |
{ |
| 201 |
self.cursor = new_cursor; |
| 202 |
} else { |
| 203 |
// Destroy the finder when we've reached the end of the bounds. |
| 204 |
self.bounds.0 = self.bounds.1; |
| 205 |
break; |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
Ok(None) |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
/// A magic bytes finder with an optimistic guess that is tried before |
| 214 |
/// the inner finder begins searching from end. This enables much faster |
| 215 |
/// lookup in files without appended junk, because the magic bytes will be |
| 216 |
/// found directly. |
| 217 |
/// |
| 218 |
/// The guess can be marked as mandatory to produce an error. This is useful |
| 219 |
/// if the `ArchiveOffset` is known and auto-detection is not desired. |
| 220 |
pub(crate) struct OptimisticMagicFinder<Direction> { |
| 221 |
inner: MagicFinder<Direction>, |
| 222 |
initial_guess: Option<(u64, bool)>, |
| 223 |
} |
| 224 |
|
| 225 |
impl<'a, Direction: FinderDirection<'a, MagicLengthByteArray>> OptimisticMagicFinder<Direction> { |
| 226 |
/// Create a new empty optimistic magic bytes finder. |
| 227 |
pub(crate) fn new_empty() -> Self { |
| 228 |
Self { |
| 229 |
inner: MagicFinder::new(&[0, 0, 0, 0], 0, 0), |
| 230 |
initial_guess: None, |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
/// Repurpose the finder for different bytes, bounds and initial guesses. |
| 235 |
pub(crate) fn repurpose( |
| 236 |
&mut self, |
| 237 |
magic_bytes: &'a MagicLengthByteArray, |
| 238 |
bounds: (u64, u64), |
| 239 |
initial_guess: Option<(u64, bool)>, |
| 240 |
) -> &mut Self { |
| 241 |
self.inner.repurpose(magic_bytes, bounds); |
| 242 |
self.initial_guess = initial_guess; |
| 243 |
|
| 244 |
self |
| 245 |
} |
| 246 |
|
| 247 |
/// Equivalent to `next_back`, with an optional initial guess attempted before |
| 248 |
/// proceeding with reading from the back of the reader. |
| 249 |
pub(crate) fn next<R: Read + Seek + ?Sized>( |
| 250 |
&mut self, |
| 251 |
reader: &mut R, |
| 252 |
) -> ZipResult<Option<u64>> { |
| 253 |
if let Some((v, mandatory)) = self.initial_guess { |
| 254 |
reader.seek(SeekFrom::Start(v))?; |
| 255 |
|
| 256 |
let mut buffer = MagicLengthByteArray::default(); |
| 257 |
|
| 258 |
// Attempt to match only if there's enough space for the needle |
| 259 |
if v.saturating_add(buffer.len() as u64) <= self.inner.bounds.1 { |
| 260 |
if let Err(e) = reader.read_exact(&mut buffer) { |
| 261 |
if e.kind() == std::io::ErrorKind::UnexpectedEof { |
| 262 |
if mandatory { |
| 263 |
return Ok(None); |
| 264 |
} |
| 265 |
} else { |
| 266 |
return Err(e.into()); |
| 267 |
} |
| 268 |
} else if self.inner.finder.needle() == buffer { |
| 269 |
// If a match is found, yield it. |
| 270 |
self.initial_guess.take(); |
| 271 |
reader.seek(SeekFrom::Start(v))?; |
| 272 |
return Ok(Some(v)); |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
// If a match is not found, but the initial guess was mandatory, return an error. |
| 277 |
if mandatory { |
| 278 |
return Ok(None); |
| 279 |
} |
| 280 |
|
| 281 |
// If the initial guess was not mandatory, remove it, as it was not found. |
| 282 |
self.initial_guess.take(); |
| 283 |
} |
| 284 |
|
| 285 |
self.inner.next(reader) |
| 286 |
} |
| 287 |
} |