use std::collections::HashMap;
const WINDOW: usize = 64;
const MASK_BITS: u32 = 13;
const MASK: u32 = (1 << MASK_BITS) - 1;
const MIN_CHUNK: usize = 2 * 1024;
pub(crate) const MAX_CHUNK: usize = 64 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Run {
Copy { source_offset: u64, length: u64 },
Payload { target_offset: u64, length: u64 },
}
#[derive(Debug, Default)]
pub(crate) struct Plan {
pub(crate) runs: Vec<Run>,
pub(crate) copied: u64,
}
pub(crate) fn plan(source: &[u8], target: &[u8]) -> Plan {
let index = index_source(source);
let mut plan = Plan::default();
for (offset, len) in chunks(target) {
let chunk = &target[offset..offset + len];
let contiguous = match plan.runs.last() {
Some(&Run::Copy {
source_offset,
length,
}) => Some((source_offset + length) as usize),
_ => None,
};
let hit = contiguous
.filter(|off| source[*off..].starts_with(chunk))
.or_else(|| {
index
.get(&digest_of(chunk))
.into_iter()
.flatten()
.copied()
.find(|&off| source[off..].starts_with(chunk))
});
match hit {
Some(src_off) => plan.push_copy(src_off as u64, len as u64),
None => plan.push_payload(offset as u64, len as u64),
}
}
plan
}
impl Plan {
fn push_copy(&mut self, source_offset: u64, length: u64) {
self.copied += length;
if let Some(Run::Copy {
source_offset: prev_off,
length: prev_len,
}) = self.runs.last_mut()
&& *prev_off + *prev_len == source_offset
{
*prev_len += length;
return;
}
self.runs.push(Run::Copy {
source_offset,
length,
});
}
fn push_payload(&mut self, target_offset: u64, length: u64) {
if let Some(Run::Payload {
target_offset: prev_off,
length: prev_len,
}) = self.runs.last_mut()
&& *prev_off + *prev_len == target_offset
{
*prev_len += length;
return;
}
self.runs.push(Run::Payload {
target_offset,
length,
});
}
}
fn index_source(source: &[u8]) -> HashMap<u64, Vec<usize>> {
let mut index: HashMap<u64, Vec<usize>> = HashMap::new();
for (offset, len) in chunks(source) {
index
.entry(digest_of(&source[offset..offset + len]))
.or_default()
.push(offset);
}
index
}
fn digest_of(chunk: &[u8]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325u64;
for &byte in chunk {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
fn chunks(data: &[u8]) -> impl Iterator<Item = (usize, usize)> + '_ {
let mut start = 0usize;
std::iter::from_fn(move || {
if start >= data.len() {
return None;
}
let len = chunk_len(&data[start..]);
let out = (start, len);
start += len;
Some(out)
})
}
fn chunk_len(data: &[u8]) -> usize {
let mut roll = Rollsum::default();
let limit = data.len().min(MAX_CHUNK);
for (i, &byte) in data[..limit].iter().enumerate() {
roll.push(byte, i);
if i + 1 >= MIN_CHUNK && roll.at_boundary() {
return i + 1;
}
}
limit
}
struct Rollsum {
a: u32,
b: u32,
window: [u8; WINDOW],
}
impl Default for Rollsum {
fn default() -> Self {
Rollsum {
a: 0,
b: 0,
window: [0; WINDOW],
}
}
}
impl Rollsum {
fn push(&mut self, byte: u8, pos: usize) {
let slot = pos % WINDOW;
let dropped = self.window[slot];
self.window[slot] = byte;
self.a = self
.a
.wrapping_add(u32::from(byte))
.wrapping_sub(u32::from(dropped));
self.b = self
.b
.wrapping_add(self.a)
.wrapping_sub(WINDOW as u32 * u32::from(dropped));
}
fn at_boundary(&self) -> bool {
self.b & MASK == MASK
}
}
#[cfg(test)]
mod tests {
use super::*;
fn data(len: usize, seed: u64) -> Vec<u8> {
let mut x = seed | 1;
(0..len)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
(x & 0xff) as u8
})
.collect()
}
fn reconstruct(plan: &Plan, source: &[u8], target: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
for run in &plan.runs {
match *run {
Run::Copy {
source_offset,
length,
} => {
let start = source_offset as usize;
out.extend_from_slice(&source[start..start + length as usize]);
}
Run::Payload {
target_offset,
length,
} => {
let start = target_offset as usize;
out.extend_from_slice(&target[start..start + length as usize]);
}
}
}
out
}
#[test]
fn chunks_cover_the_input_exactly_once() {
let bytes = data(500_000, 7);
let mut position = 0;
for (offset, len) in chunks(&bytes) {
assert_eq!(offset, position);
assert!(len > 0 && len <= MAX_CHUNK);
position += len;
}
assert_eq!(position, bytes.len());
}
#[test]
fn identical_input_plans_one_copy_run() {
let bytes = data(300_000, 11);
let plan = plan(&bytes, &bytes);
assert_eq!(
plan.runs,
vec![Run::Copy {
source_offset: 0,
length: bytes.len() as u64
}]
);
assert_eq!(plan.copied, bytes.len() as u64);
}
#[test]
fn an_in_place_edit_keeps_the_surrounding_runs() {
let source = data(400_000, 13);
let mut target = source.clone();
for byte in &mut target[200_000..200_512] {
*byte = !*byte;
}
let plan = plan(&source, &target);
assert_eq!(reconstruct(&plan, &source, &target), target);
assert!(plan.copied > 300_000, "copied only {}", plan.copied);
assert!(plan.runs.len() <= 5, "runs: {:?}", plan.runs);
}
#[test]
fn an_insertion_resynchronizes() {
let source = data(400_000, 17);
let mut target = source[..150_000].to_vec();
target.extend_from_slice(&data(1_000, 19));
target.extend_from_slice(&source[150_000..]);
let plan = plan(&source, &target);
assert_eq!(reconstruct(&plan, &source, &target), target);
assert!(plan.copied > 300_000, "copied only {}", plan.copied);
}
#[test]
fn repetitive_content_plans_one_copy_run() {
let bytes = vec![0u8; 16 * MAX_CHUNK];
let plan = plan(&bytes, &bytes);
assert_eq!(reconstruct(&plan, &bytes, &bytes), bytes);
assert_eq!(
plan.runs,
vec![Run::Copy {
source_offset: 0,
length: bytes.len() as u64
}]
);
assert_eq!(plan.copied, bytes.len() as u64);
}
#[test]
fn a_contiguous_continuation_copies_without_a_digest_match() {
let source = data(300_000, 41);
let target = &source[..source.len() - 1];
let (offset, len) = chunks(target).last().unwrap();
assert!(
!index_source(&source).contains_key(&digest_of(&target[offset..offset + len])),
"the last chunk's digest is in the index, so the case is not exercised"
);
let plan = plan(&source, target);
assert_eq!(reconstruct(&plan, &source, target), target);
assert_eq!(
plan.runs,
vec![Run::Copy {
source_offset: 0,
length: target.len() as u64
}]
);
assert_eq!(plan.copied, target.len() as u64);
}
#[test]
fn a_zero_padded_tail_survives_an_edit_before_it() {
let mut source = data(200_000, 37);
source.resize(200_000 + 8 * MAX_CHUNK, 0);
let mut target = source.clone();
for byte in &mut target[100_000..100_512] {
*byte = !*byte;
}
let plan = plan(&source, &target);
assert_eq!(reconstruct(&plan, &source, &target), target);
assert!(
plan.copied > (7 * MAX_CHUNK) as u64,
"copied only {}",
plan.copied
);
assert!(plan.runs.len() <= 5, "runs: {:?}", plan.runs);
}
#[test]
fn unrelated_input_plans_payload_only() {
let source = data(100_000, 23);
let target = data(100_000, 29);
let plan = plan(&source, &target);
assert_eq!(plan.copied, 0);
assert_eq!(reconstruct(&plan, &source, &target), target);
}
#[test]
fn empty_target_plans_nothing() {
let plan = plan(&data(1_000, 31), &[]);
assert!(plan.runs.is_empty());
assert_eq!(plan.copied, 0);
}
}