Index native command meanings with deterministic state output

This commit is contained in:
gloamxun committed 2026-11-29 04:37:03 +08:00
1 parent 79bfee5ab1
commit c23dabb449
2 files changed
+63 -7

No files matched your search

+41 -7
View File
@@ -1,4 +1,4 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashMap};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::Arc;
@@ -794,14 +794,42 @@ enum PdftexRevision {
R24,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
struct CommandBindings(#[serde(with = "ordered_map")] BTreeMap<Arc<CommandName>, Meaning>);
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct CommandBindings(HashMap<Arc<CommandName>, Meaning>);
impl CommandBindings {
fn ordered(&self) -> Vec<(&Arc<CommandName>, &Meaning)> {
let mut entries: Vec<_> = self.0.iter().collect();
entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
entries
}
}
impl Hash for CommandBindings {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.ordered().hash(hasher);
}
}
impl serde::Serialize for CommandBindings {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(&self.ordered(), serializer)
}
}
impl<'de> serde::Deserialize<'de> for CommandBindings {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let entries = <Vec<(Arc<CommandName>, Meaning)> as serde::Deserialize>::deserialize(
deserializer,
)?;
Ok(Self(entries.into_iter().collect()))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct State {
// Checkpoints share the table. A write copies the ordered bindings, but
// their immutable names and macro bodies stay shared across revisions.
// Checkpoints share the table. A write copies the bindings, while names
// and macro bodies stay shared. Formats and fingerprints use key order.
commands: Arc<CommandBindings>,
catcodes: BTreeMap<char, CatCode>,
counts: BTreeMap<u16, i32>,
@@ -932,6 +960,12 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() {
let mut direct = DefaultHasher::new();
state.hash(&mut direct);
assert_eq!(state.fingerprint(), direct.finish());
let mut ordered_hash = DefaultHasher::new();
let mut table_hash = DefaultHasher::new();
let ordered: BTreeMap<_, _> = state.commands.0.iter().collect();
ordered.hash(&mut ordered_hash);
state.commands.hash(&mut table_hash);
assert_eq!(table_hash.finish(), ordered_hash.finish());
};
check(&state);
state.begin_group(GroupKind::Simple, None);
@@ -2261,7 +2295,7 @@ impl State {
.map(|meaning| (name, meaning))
}
fn command_bindings_mut(&mut self) -> &mut BTreeMap<Arc<CommandName>, Meaning> {
fn command_bindings_mut(&mut self) -> &mut HashMap<Arc<CommandName>, Meaning> {
&mut Arc::make_mut(&mut self.commands).0
}