//! Deduplicate execution reads before producing the ordered public evidence. use super::Dependency; use std::collections::{BTreeSet, HashSet}; #[derive(Clone, Default)] pub(super) struct DependencyReads { byte_catcodes: [u64; 4], other: HashSet, } impl DependencyReads { pub(super) fn catcode(&mut self, character: char) { let index = character as usize; if let Some(bits) = self.byte_catcodes.get_mut(index / 64) { *bits |= 1 << (index % 64); } else { self.other.insert(Dependency::CatCode(character)); } } pub(super) fn insert(&mut self, dependency: Dependency) { if let Dependency::CatCode(character) = dependency { self.catcode(character); } else { self.other.insert(dependency); } } pub(super) fn observed_statistics(&self) -> bool { self.other.contains(&Dependency::ResourceStatistics) } pub(super) fn into_ordered(self) -> BTreeSet { let byte_catcodes = (0..=u8::MAX) .filter(|&index| { let index = usize::from(index); self.byte_catcodes[index / 64] & (1 << (index % 64)) != 0 }) .map(|index| Dependency::CatCode(char::from(index))); self.other.into_iter().chain(byte_catcodes).collect() } } impl Extend for DependencyReads { fn extend>(&mut self, dependencies: T) { for dependency in dependencies { self.insert(dependency); } } } #[cfg(test)] mod tests { use super::*; #[test] fn cloned_record_preserves_byte_and_unicode_dependencies() { let mut read = DependencyReads::default(); for character in ['\0', '@', 'ÿ', 'Ā', '文'] { read.catcode(character); read.insert(Dependency::CatCode(character)); } read.insert(Dependency::EndLineChar); let early = read.clone(); read.extend([Dependency::EndLineChar, Dependency::ParagraphToken]); let mut expected = BTreeSet::from([ Dependency::CatCode('\0'), Dependency::CatCode('@'), Dependency::CatCode('ÿ'), Dependency::CatCode('Ā'), Dependency::CatCode('文'), Dependency::EndLineChar, ]); assert_eq!(early.into_ordered(), expected); expected.insert(Dependency::ParagraphToken); assert_eq!(read.into_ordered(), expected); } }