| 1 |
use alloc::{ |
| 2 |
alloc::{alloc, handle_alloc_error, Layout}, |
| 3 |
boxed::Box, |
| 4 |
}; |
| 5 |
use core::ptr::{addr_of, addr_of_mut, NonNull}; |
| 6 |
|
| 7 |
use crate::util::{ZOPFLI_MIN_MATCH, ZOPFLI_WINDOW_MASK, ZOPFLI_WINDOW_SIZE}; |
| 8 |
|
| 9 |
const HASH_SHIFT: i32 = 5; |
| 10 |
const HASH_MASK: u16 = 32767; |
| 11 |
|
| 12 |
#[derive(Copy, Clone, PartialEq, Eq)] |
| 13 |
pub enum Which { |
| 14 |
Hash1, |
| 15 |
Hash2, |
| 16 |
} |
| 17 |
|
| 18 |
#[derive(Clone)] |
| 19 |
pub struct SmallerHashThing { |
| 20 |
prev: u16, /* Index to index of prev. occurrence of same hash. */ |
| 21 |
hashval: Option<u16>, /* Index to hash value at this index. */ |
| 22 |
} |
| 23 |
|
| 24 |
#[derive(Clone)] |
| 25 |
pub struct HashThing { |
| 26 |
head: [i16; 65536], /* Hash value to index of its most recent occurrence. */ |
| 27 |
prev_and_hashval: [SmallerHashThing; ZOPFLI_WINDOW_SIZE], |
| 28 |
val: u16, /* Current hash value. */ |
| 29 |
} |
| 30 |
|
| 31 |
impl HashThing { |
| 32 |
fn update(&mut self, hpos: usize) { |
| 33 |
let hashval = self.val; |
| 34 |
let index = self.val as usize; |
| 35 |
let head_index = self.head[index]; |
| 36 |
let prev = if head_index >= 0 |
| 37 |
&& self.prev_and_hashval[head_index as usize].hashval == Some(self.val) |
| 38 |
{ |
| 39 |
head_index as u16 |
| 40 |
} else { |
| 41 |
hpos as u16 |
| 42 |
}; |
| 43 |
|
| 44 |
self.prev_and_hashval[hpos] = SmallerHashThing { |
| 45 |
prev, |
| 46 |
hashval: Some(hashval), |
| 47 |
}; |
| 48 |
self.head[index] = hpos as i16; |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
#[derive(Clone)] |
| 53 |
pub struct ZopfliHash { |
| 54 |
hash1: HashThing, |
| 55 |
hash2: HashThing, |
| 56 |
pub same: [u16; ZOPFLI_WINDOW_SIZE], /* Amount of repetitions of same byte after this .*/ |
| 57 |
} |
| 58 |
|
| 59 |
impl ZopfliHash { |
| 60 |
pub fn new() -> Box<Self> { |
| 61 |
const LAYOUT: Layout = Layout::new::<ZopfliHash>(); |
| 62 |
|
| 63 |
let ptr = NonNull::new(unsafe { alloc(LAYOUT) }.cast::<Self>()) |
| 64 |
.unwrap_or_else(|| handle_alloc_error(LAYOUT)); |
| 65 |
|
| 66 |
unsafe { |
| 67 |
Self::init(ptr); |
| 68 |
Box::from_raw(ptr.as_ptr()) |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
/// Initializes the [`ZopfliHash`] instance pointed by `hash` to an initial state. |
| 73 |
/// |
| 74 |
/// ## Safety |
| 75 |
/// `hash` must point to aligned, valid memory for writes. |
| 76 |
unsafe fn init(hash: NonNull<Self>) { |
| 77 |
let hash = hash.as_ptr(); |
| 78 |
|
| 79 |
// SAFETY: addr_of(_mut) macros are used to avoid creating intermediate references, which |
| 80 |
// are undefined behavior when data is uninitialized. Note that it also is UB to |
| 81 |
// assume that integer values and arrays can be read after allocating their memory: |
| 82 |
// the allocator returns valid, but uninitialized pointers that are not guaranteed |
| 83 |
// to hold a fixed bit pattern (c.f. core::mem::MaybeUnit docs and |
| 84 |
// https://doc.rust-lang.org/std/ptr/index.html#safety). |
| 85 |
|
| 86 |
for i in 0..ZOPFLI_WINDOW_SIZE { |
| 87 |
// Arrays are guaranteed to be laid out with their elements placed in consecutive |
| 88 |
// memory positions: https://doc.rust-lang.org/reference/type-layout.html#array-layout. |
| 89 |
// Therefore, a pointer to an array has the same address as the pointer to its first |
| 90 |
// element, and adding size_of::<N>() bytes to that address yields the address of the |
| 91 |
// second element, and so on. |
| 92 |
let prev_and_hashval = addr_of_mut!((*hash).hash1.prev_and_hashval) |
| 93 |
.cast::<SmallerHashThing>() |
| 94 |
.add(i); |
| 95 |
addr_of_mut!((*prev_and_hashval).prev).write(i as u16); |
| 96 |
addr_of_mut!((*prev_and_hashval).hashval).write(None); |
| 97 |
} |
| 98 |
|
| 99 |
// Rust signed integers are guaranteed to be represented in two's complement notation: |
| 100 |
// https://doc.rust-lang.org/reference/types/numeric.html#integer-types |
| 101 |
// In this notation, -1 is expressed as an all-ones value. Therefore, writing |
| 102 |
// size_of::<[i16; N]> all-ones bytes initializes all of them to -1. |
| 103 |
addr_of_mut!((*hash).hash1.head).write_bytes(0xFF, 1); |
| 104 |
addr_of_mut!((*hash).hash1.val).write(0); |
| 105 |
|
| 106 |
addr_of_mut!((*hash).hash2).copy_from_nonoverlapping(addr_of!((*hash).hash1), 1); |
| 107 |
|
| 108 |
// Zero-initializes all the array elements |
| 109 |
addr_of_mut!((*hash).same).write_bytes(0, 1); |
| 110 |
} |
| 111 |
|
| 112 |
pub fn reset(&mut self) { |
| 113 |
unsafe { Self::init(NonNull::new(self).unwrap()) } |
| 114 |
} |
| 115 |
|
| 116 |
pub fn warmup(&mut self, arr: &[u8], pos: usize, end: usize) { |
| 117 |
let c = arr[pos]; |
| 118 |
self.update_val(c); |
| 119 |
|
| 120 |
if pos + 1 < end { |
| 121 |
let c = arr[pos + 1]; |
| 122 |
self.update_val(c); |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
/// Update the sliding hash value with the given byte. All calls to this function |
| 127 |
/// must be made on consecutive input characters. Since the hash value exists out |
| 128 |
/// of multiple input bytes, a few warmups with this function are needed initially. |
| 129 |
fn update_val(&mut self, c: u8) { |
| 130 |
self.hash1.val = ((self.hash1.val << HASH_SHIFT) ^ u16::from(c)) & HASH_MASK; |
| 131 |
} |
| 132 |
|
| 133 |
pub fn update(&mut self, array: &[u8], pos: usize) { |
| 134 |
let hash_value = array.get(pos + ZOPFLI_MIN_MATCH - 1).copied().unwrap_or(0); |
| 135 |
self.update_val(hash_value); |
| 136 |
|
| 137 |
let hpos = pos & ZOPFLI_WINDOW_MASK; |
| 138 |
|
| 139 |
self.hash1.update(hpos); |
| 140 |
|
| 141 |
// Update "same". |
| 142 |
let mut amount = 0; |
| 143 |
let same = self.same[pos.wrapping_sub(1) & ZOPFLI_WINDOW_MASK]; |
| 144 |
if same > 1 { |
| 145 |
amount = same - 1; |
| 146 |
} |
| 147 |
|
| 148 |
let mut another_index = pos + amount as usize + 1; |
| 149 |
let array_pos = array[pos]; |
| 150 |
while another_index < array.len() && array_pos == array[another_index] && amount < u16::MAX |
| 151 |
{ |
| 152 |
amount += 1; |
| 153 |
another_index += 1; |
| 154 |
} |
| 155 |
|
| 156 |
self.same[hpos] = amount; |
| 157 |
|
| 158 |
self.hash2.val = (amount.wrapping_sub(ZOPFLI_MIN_MATCH as u16) & 255) ^ self.hash1.val; |
| 159 |
|
| 160 |
self.hash2.update(hpos); |
| 161 |
} |
| 162 |
|
| 163 |
pub fn prev_at(&self, index: usize, which: Which) -> usize { |
| 164 |
(match which { |
| 165 |
Which::Hash1 => self.hash1.prev_and_hashval[index].prev, |
| 166 |
Which::Hash2 => self.hash2.prev_and_hashval[index].prev, |
| 167 |
}) as usize |
| 168 |
} |
| 169 |
|
| 170 |
pub fn hash_val_at(&self, index: usize, which: Which) -> i32 { |
| 171 |
let hashval = match which { |
| 172 |
Which::Hash1 => self.hash1.prev_and_hashval[index].hashval, |
| 173 |
Which::Hash2 => self.hash2.prev_and_hashval[index].hashval, |
| 174 |
}; |
| 175 |
hashval.map_or(-1, i32::from) |
| 176 |
} |
| 177 |
|
| 178 |
pub fn val(&self, which: Which) -> u16 { |
| 179 |
match which { |
| 180 |
Which::Hash1 => self.hash1.val, |
| 181 |
Which::Hash2 => self.hash2.val, |
| 182 |
} |
| 183 |
} |
| 184 |
} |