2 use std::collections::{BTreeMap, BTreeSet, HashMap};
3 use std::convert::TryFrom;
4 use std::fmt::{self, Write};
8 pub struct RawEmitter {
11 pub bytes_used: usize,
15 pub fn new() -> RawEmitter {
16 RawEmitter { file: String::new(), bytes_used: 0, desc: String::new() }
19 fn blank_line(&mut self) {
20 if self.file.is_empty() || self.file.ends_with("\n\n") {
23 writeln!(&mut self.file).unwrap();
26 fn emit_bitset(&mut self, ranges: &[Range<u32>]) -> Result<(), String> {
27 let last_code_point = ranges.last().unwrap().end;
28 // bitset for every bit in the codepoint range
30 // + 2 to ensure an all zero word to use for padding
31 let mut buckets = vec![0u64; (last_code_point as usize / 64) + 2];
33 for codepoint in range.clone() {
34 let bucket = codepoint as usize / 64;
35 let bit = codepoint as u64 % 64;
36 buckets[bucket] |= 1 << bit;
40 let mut words = buckets;
41 // Ensure that there's a zero word in the dataset, used for padding and
45 words.iter().cloned().collect::<BTreeSet<_>>().into_iter().collect::<Vec<_>>();
46 if unique_words.len() > u8::MAX as usize {
47 return Err(format!("cannot pack {} into 8 bits", unique_words.len()));
49 // needed for the chunk mapping to work
50 assert_eq!(unique_words[0], 0, "has a zero word");
51 let canonicalized = Canonicalized::canonicalize(&unique_words);
53 let word_indices = canonicalized.unique_mapping.clone();
54 let compressed_words = words.iter().map(|w| word_indices[w]).collect::<Vec<u8>>();
57 for length in 1..=64 {
58 let mut temp = self.clone();
59 temp.emit_chunk_map(word_indices[&0], &compressed_words, length);
60 if let Some((_, size)) = best {
61 if temp.bytes_used < size {
62 best = Some((length, temp.bytes_used));
65 best = Some((length, temp.bytes_used));
68 self.emit_chunk_map(word_indices[&0], &compressed_words, best.unwrap().0);
71 impl fmt::Debug for Bits {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 write!(f, "0b{:064b}", self.0)
79 "static BITSET_CANONICAL: [u64; {}] = [{}];",
80 canonicalized.canonical_words.len(),
81 fmt_list(canonicalized.canonical_words.iter().map(|v| Bits(*v))),
84 self.bytes_used += 8 * canonicalized.canonical_words.len();
87 "static BITSET_MAPPING: [(u8, u8); {}] = [{}];",
88 canonicalized.canonicalized_words.len(),
89 fmt_list(&canonicalized.canonicalized_words),
92 // 8 bit index into shifted words, 7 bits for shift + optional flip
93 // We only need it for the words that we removed by applying a shift and
95 self.bytes_used += 2 * canonicalized.canonicalized_words.len();
99 writeln!(&mut self.file, "pub fn lookup(c: char) -> bool {{").unwrap();
100 writeln!(&mut self.file, " super::bitset_search(",).unwrap();
101 writeln!(&mut self.file, " c as u32,").unwrap();
102 writeln!(&mut self.file, " &BITSET_CHUNKS_MAP,").unwrap();
103 writeln!(&mut self.file, " &BITSET_INDEX_CHUNKS,").unwrap();
104 writeln!(&mut self.file, " &BITSET_CANONICAL,").unwrap();
105 writeln!(&mut self.file, " &BITSET_MAPPING,").unwrap();
106 writeln!(&mut self.file, " )").unwrap();
107 writeln!(&mut self.file, "}}").unwrap();
112 fn emit_chunk_map(&mut self, zero_at: u8, compressed_words: &[u8], chunk_length: usize) {
113 let mut compressed_words = compressed_words.to_vec();
114 for _ in 0..(chunk_length - (compressed_words.len() % chunk_length)) {
115 // pad out bitset index with zero words so we have all chunks of
117 compressed_words.push(zero_at);
120 let mut chunks = BTreeSet::new();
121 for chunk in compressed_words.chunks(chunk_length) {
122 chunks.insert(chunk);
124 let chunk_map = chunks
128 .map(|(idx, chunk)| (chunk, idx))
129 .collect::<HashMap<_, _>>();
130 let mut chunk_indices = Vec::new();
131 for chunk in compressed_words.chunks(chunk_length) {
132 chunk_indices.push(chunk_map[chunk]);
137 "static BITSET_CHUNKS_MAP: [u8; {}] = [{}];",
139 fmt_list(&chunk_indices),
142 self.bytes_used += chunk_indices.len();
145 "static BITSET_INDEX_CHUNKS: [[u8; {}]; {}] = [{}];",
148 fmt_list(chunks.iter()),
151 self.bytes_used += chunk_length * chunks.len();
155 pub fn emit_codepoints(emitter: &mut RawEmitter, ranges: &[Range<u32>]) {
156 emitter.blank_line();
158 let mut bitset = emitter.clone();
159 let bitset_ok = bitset.emit_bitset(&ranges).is_ok();
161 let mut skiplist = emitter.clone();
162 skiplist.emit_skiplist(&ranges);
164 if bitset_ok && bitset.bytes_used <= skiplist.bytes_used {
166 emitter.desc = String::from("bitset");
169 emitter.desc = String::from("skiplist");
173 struct Canonicalized {
174 canonical_words: Vec<u64>,
175 canonicalized_words: Vec<(u8, u8)>,
177 /// Maps an input unique word to the associated index (u8) which is into
178 /// canonical_words or canonicalized_words (in order).
179 unique_mapping: HashMap<u64, u8>,
183 fn canonicalize(unique_words: &[u64]) -> Self {
184 #[derive(Copy, Clone, Debug)]
188 RotateAndInvert(u32),
192 // key is the word being mapped to
193 let mut mappings: BTreeMap<u64, Vec<(u64, Mapping)>> = BTreeMap::new();
194 for &a in unique_words {
195 'b: for &b in unique_words {
201 // All possible distinct rotations
202 for rotation in 1..64 {
203 if a.rotate_right(rotation) == b {
204 mappings.entry(b).or_default().push((a, Mapping::Rotate(rotation)));
205 // We're not interested in further mappings between a and b
211 mappings.entry(b).or_default().push((a, Mapping::Invert));
212 // We're not interested in further mappings between a and b
216 // All possible distinct rotations, inverted
217 for rotation in 1..64 {
218 if (!a.rotate_right(rotation)) == b {
222 .push((a, Mapping::RotateAndInvert(rotation)));
223 // We're not interested in further mappings between a and b
228 // All possible shifts
229 for shift_by in 1..64 {
230 if a == (b >> shift_by) {
234 .push((a, Mapping::ShiftRight(shift_by as u32)));
235 // We're not interested in further mappings between a and b
241 // These are the bitset words which will be represented "raw" (as a u64)
242 let mut canonical_words = Vec::new();
243 // These are mapped words, which will be represented by an index into
244 // the canonical_words and a Mapping; u16 when encoded.
245 let mut canonicalized_words = Vec::new();
246 let mut unique_mapping = HashMap::new();
248 #[derive(Debug, PartialEq, Eq)]
251 Canonicalized(usize),
254 // Map 0 first, so that it is the first canonical word.
255 // This is realistically not inefficient because 0 is not mapped to by
256 // anything else (a shift pattern could do it, but would be wasteful).
258 // However, 0s are quite common in the overall dataset, and it is quite
259 // wasteful to have to go through a mapping function to determine that
262 // FIXME: Experiment with choosing most common words in overall data set
263 // for canonical when possible.
264 while let Some((&to, _)) = mappings
266 .find(|(&to, _)| to == 0)
267 .or_else(|| mappings.iter().max_by_key(|m| m.1.len()))
269 // Get the mapping with the most entries. Currently, no mapping can
270 // only exist transitively (i.e., there is no A, B, C such that A
271 // does not map to C and but A maps to B maps to C), so this is
272 // guaranteed to be acceptable.
274 // In the future, we may need a more sophisticated algorithm to
275 // identify which keys to prefer as canonical.
276 let mapped_from = mappings.remove(&to).unwrap();
277 for (from, how) in &mapped_from {
278 // Remove the entries which mapped to this one.
279 // Noting that it should be associated with the Nth canonical word.
281 // We do not assert that this is present, because there may be
282 // no mappings to the `from` word; that's fine.
283 mappings.remove(from);
286 .insert(*from, UniqueMapping::Canonicalized(canonicalized_words.len())),
289 canonicalized_words.push((canonical_words.len(), *how));
291 // Remove the now-canonicalized word from other mappings,
292 // to ensure that we deprioritize them in the next iteration of
294 for mapped in mappings.values_mut() {
296 while i != mapped.len() {
297 if mapped[i].0 == *from {
307 .insert(to, UniqueMapping::Canonical(canonical_words.len()))
310 canonical_words.push(to);
312 // Remove the now-canonical word from other mappings, to ensure that
313 // we deprioritize them in the next iteration of the while loop.
314 for mapped in mappings.values_mut() {
316 while i != mapped.len() {
317 if mapped[i].0 == to {
326 // Any words which we couldn't shrink, just stick into the canonical
329 // FIXME: work harder -- there are more possibilities for mapping
330 // functions (e.g., multiplication, shifting instead of rotation, etc.)
331 // We'll probably always have some slack though so this loop will still
333 for &w in unique_words {
334 if !unique_mapping.contains_key(&w) {
337 .insert(w, UniqueMapping::Canonical(canonical_words.len()))
340 canonical_words.push(w);
343 assert_eq!(canonicalized_words.len() + canonical_words.len(), unique_words.len());
344 assert_eq!(unique_mapping.len(), unique_words.len());
346 let unique_mapping = unique_mapping
348 .map(|(key, value)| {
352 UniqueMapping::Canonicalized(idx) => {
353 u8::try_from(canonical_words.len() + idx).unwrap()
355 UniqueMapping::Canonical(idx) => u8::try_from(idx).unwrap(),
359 .collect::<HashMap<_, _>>();
361 let mut distinct_indices = BTreeSet::new();
362 for &w in unique_words {
363 let idx = unique_mapping.get(&w).unwrap();
364 assert!(distinct_indices.insert(idx));
367 const LOWER_6: u32 = (1 << 6) - 1;
369 let canonicalized_words = canonicalized_words
373 u8::try_from(v.0).unwrap(),
375 Mapping::RotateAndInvert(amount) => {
376 assert_eq!(amount, amount & LOWER_6);
377 1 << 6 | (amount as u8)
379 Mapping::Rotate(amount) => {
380 assert_eq!(amount, amount & LOWER_6);
383 Mapping::Invert => 1 << 6,
384 Mapping::ShiftRight(shift_by) => {
385 assert_eq!(shift_by, shift_by & LOWER_6);
386 1 << 7 | (shift_by as u8)
391 .collect::<Vec<(u8, u8)>>();
392 Canonicalized { unique_mapping, canonical_words, canonicalized_words }