Batch native state fingerprint writes for live editing

This commit is contained in:
gloamxun committed 2026-11-19 21:15:54 +08:00
1 parent 959dd4f24a
commit 10a08c4597
2 files changed
+100 -2

No files matched your search

+61 -2
View File
@@ -1,5 +1,5 @@
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
use std::hash::{DefaultHasher, Hash, Hasher};
use super::{
CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register,
@@ -607,6 +607,65 @@ pub struct State {
pub(super) hyphenation: super::hyphenation::HyphenationData,
}
// Batch the many small token and integer writes in a state fingerprint.
// The ordered bytes still go through the native state fingerprint's hasher.
struct FingerprintHasher {
hasher: DefaultHasher,
buffer: [u8; 4096],
used: usize,
}
impl Default for FingerprintHasher {
fn default() -> Self {
Self {
hasher: DefaultHasher::new(),
buffer: [0; 4096],
used: 0,
}
}
}
impl Hasher for FingerprintHasher {
fn write(&mut self, bytes: &[u8]) {
if bytes.len() > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
if bytes.len() > self.buffer.len() {
self.hasher.write(bytes);
} else {
let end = self.used + bytes.len();
self.buffer[self.used..end].copy_from_slice(bytes);
self.used = end;
}
}
fn finish(&self) -> u64 {
let mut hasher = self.hasher.clone();
hasher.write(&self.buffer[..self.used]);
hasher.finish()
}
}
#[test]
fn buffered_fingerprint_matches_the_ordered_state_hash() {
let mut state = State::initex().with_etex();
let check = |state: &State| {
let mut direct = DefaultHasher::new();
state.hash(&mut direct);
assert_eq!(state.fingerprint(), direct.finish());
};
check(&state);
state.begin_group(GroupKind::Simple, None);
state.define(
CommandName::Control("断字".repeat(1024)),
Meaning::Primitive(Primitive::Relax),
false,
);
state.define(CommandName::Control("μ".into()), Meaning::Count(123), true);
check(&state);
}
impl Default for State {
fn default() -> Self {
use Primitive::*;
@@ -1450,7 +1509,7 @@ impl State {
self.groups.len()
}
pub fn fingerprint(&self) -> u64 {
let mut hash = std::collections::hash_map::DefaultHasher::new();
let mut hash = FingerprintHasher::default();
self.hash(&mut hash);
hash.finish()
}