Skip to main content

passgen/markov/
frequency.rs

1//! # Character frequency tables
2//!
3//! A frequency table has the characters that can follow a prefix, with how often each of them
4//! does. The [Frequency] trait is what a data structure for this needs to do.
5//!
6//! The order in which a table iterates its characters decides which character a random
7//! number stands for. [FrequencySorted] (the default) and [FrequencyBTree] iterate in the
8//! order of the codepoints, which is what makes generated words reproducible.
9
10use std::collections::*;
11
12/// Table of characters with how often they were seen.
13pub trait Frequency: Default {
14    /// Adds a count to that of a character.
15    fn insert(&mut self, character: char, count: usize);
16
17    /// The total of the counts of all characters.
18    fn total(&self) -> usize;
19
20    /// Iterates over the characters with their counts.
21    fn iter(&self) -> impl Iterator<Item = (char, usize)>;
22
23    /// Whether there is only one character that has a count, so that there is nothing to
24    /// choose.
25    fn single(&self) -> bool {
26        self.iter().filter(|(_, count)| *count > 0).take(2).count() == 1
27    }
28
29    /// The character at an index below the total, with its count. The characters are in the
30    /// order of the table, and a character with a count is there that many times in a row.
31    fn nth(&self, mut index: usize) -> Option<(char, usize)> {
32        for (character, count) in self.iter() {
33            if index < count {
34                return Some((character, count));
35            }
36            index -= count;
37        }
38        None
39    }
40}
41
42/// The frequency table that is used by default.
43///
44/// This is the one that needs the least memory, and its order is that of the codepoints.
45pub type FrequencyDefault = FrequencySorted;
46
47/// Sizes that a [FrequencyPerfect] can have. These are prime numbers, every one of which is
48/// greater than double the one before it. The largest is greater than any codepoint, so that
49/// it never has collisions.
50const PERFECT_SIZES: [usize; 19] = [
51    3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,
52    701819, 1403641,
53];
54
55/// Frequency table backed by a hash table without collisions.
56///
57/// A character is stored in the slot at its codepoint modulo the size of the table. When two
58/// characters would need the same slot, the table grows to the next size at which no two of
59/// them do. It is fast to insert into, but needs more memory than the other tables, and much
60/// more for scripts with many characters.
61///
62/// Characters are iterated in the order of their slots. The size of the table is always the
63/// smallest for which there are no collisions, so this order only depends on which characters
64/// are in the table, and not on the order in which they were inserted. It is not the order of
65/// the codepoints.
66#[derive(Debug, Clone, PartialEq)]
67pub struct FrequencyPerfect {
68    /// Characters with their counts. A slot with a count of zero is empty.
69    slots: Box<[(char, usize)]>,
70    total: usize,
71}
72
73impl Default for FrequencyPerfect {
74    fn default() -> Self {
75        Self::with_size(PERFECT_SIZES[0])
76    }
77}
78
79impl FrequencyPerfect {
80    fn with_size(size: usize) -> Self {
81        Self {
82            slots: vec![('\0', 0); size].into(),
83            total: 0,
84        }
85    }
86
87    fn slot(&self, character: char) -> usize {
88        character as usize % self.slots.len()
89    }
90
91    /// Moves everything into the next larger table in which neither the characters that are
92    /// in it nor the given one need the same slot.
93    fn grow(&mut self, character: char) {
94        let sizes = PERFECT_SIZES
95            .iter()
96            .filter(|size| **size > self.slots.len());
97        'sizes: for size in sizes {
98            let mut new = Self::with_size(*size);
99            for (entry, count) in self.iter() {
100                let slot = new.slot(entry);
101                if new.slots[slot].1 != 0 {
102                    continue 'sizes;
103                }
104                new.slots[slot] = (entry, count);
105            }
106            if new.slots[new.slot(character)].1 != 0 {
107                continue;
108            }
109            new.total = self.total;
110            *self = new;
111            return;
112        }
113        unreachable!("the largest size is greater than any codepoint");
114    }
115}
116
117impl Frequency for FrequencyPerfect {
118    fn insert(&mut self, character: char, count: usize) {
119        // a count of zero marks an empty slot.
120        if count == 0 {
121            return;
122        }
123
124        let (entry, existing) = self.slots[self.slot(character)];
125        if existing != 0 && entry != character {
126            self.grow(character);
127        }
128
129        let slot = self.slot(character);
130        self.slots[slot].0 = character;
131        self.slots[slot].1 += count;
132        self.total += count;
133    }
134
135    fn total(&self) -> usize {
136        self.total
137    }
138
139    fn iter(&self) -> impl Iterator<Item = (char, usize)> {
140        self.slots.iter().copied().filter(|(_, count)| *count != 0)
141    }
142}
143
144/// Frequency table backed by a [HashMap]. The order of its characters is not defined, so what
145/// is generated with it is not reproducible.
146#[derive(Debug, Clone, Default, PartialEq)]
147pub struct FrequencyHashMap {
148    table: HashMap<char, usize>,
149    total: usize,
150}
151
152impl Frequency for FrequencyHashMap {
153    fn insert(&mut self, c: char, count: usize) {
154        let value = self.table.entry(c).or_default();
155        *value += count;
156        self.total += count;
157    }
158
159    fn total(&self) -> usize {
160        self.total
161    }
162
163    fn iter(&self) -> impl Iterator<Item = (char, usize)> {
164        self.table.iter().map(|(c, count)| (*c, *count))
165    }
166}
167
168/// Frequency table backed by a [BTreeMap], with the characters in the order of their
169/// codepoints.
170#[derive(Debug, Clone, Default, PartialEq)]
171pub struct FrequencyBTree {
172    table: BTreeMap<char, usize>,
173    total: usize,
174}
175
176impl Frequency for FrequencyBTree {
177    fn insert(&mut self, c: char, count: usize) {
178        let value = self.table.entry(c).or_default();
179        *value += count;
180        self.total += count;
181    }
182
183    fn total(&self) -> usize {
184        self.total
185    }
186
187    fn iter(&self) -> impl Iterator<Item = (char, usize)> {
188        self.table.iter().map(|(c, count)| (*c, *count))
189    }
190}
191
192/// Frequency table backed by the [HashMap](hashbrown::HashMap) from the hashbrown crate. The
193/// order of its characters is not defined, so what is generated with it is not reproducible.
194#[cfg(feature = "hashbrown")]
195#[derive(Debug, Clone, Default, PartialEq)]
196pub struct FrequencyHashbrown {
197    table: hashbrown::HashMap<char, usize>,
198    total: usize,
199}
200
201#[cfg(feature = "hashbrown")]
202impl Frequency for FrequencyHashbrown {
203    fn insert(&mut self, c: char, count: usize) {
204        let value = self.table.entry(c).or_default();
205        *value += count;
206        self.total += count;
207    }
208
209    fn total(&self) -> usize {
210        self.total
211    }
212
213    fn iter(&self) -> impl Iterator<Item = (char, usize)> {
214        self.table.iter().map(|(c, count)| (*c, *count))
215    }
216}
217
218/// Frequency table backed by a sorted list.
219///
220/// The characters are kept in a list that is sorted by codepoint, with no memory allocated
221/// beyond what the entries need. Most tables only have few characters, which makes this both
222/// small and fast.
223///
224/// Characters are iterated in the order of their codepoints, so what is generated from a
225/// deterministic source of randomness only depends on the words, and is the same as with
226/// the C implementation of Passgen.
227///
228/// The count of a single character is limited to what fits into 32 bits.
229#[derive(Debug, Clone, Default, PartialEq)]
230pub struct FrequencySorted {
231    table: Vec<(char, u32)>,
232    total: usize,
233}
234
235impl Frequency for FrequencySorted {
236    fn insert(&mut self, character: char, count: usize) {
237        let count: u32 = count.try_into().expect("count fits into 32 bits");
238        match self.table.binary_search_by_key(&character, |entry| entry.0) {
239            Ok(index) => {
240                let entry = &mut self.table[index].1;
241                *entry = entry.checked_add(count).expect("count fits into 32 bits");
242            }
243            Err(index) => {
244                // new characters are rare, so this only allocates for what is needed.
245                self.table.reserve_exact(1);
246                self.table.insert(index, (character, count));
247            }
248        }
249        self.total += count as usize;
250    }
251
252    fn total(&self) -> usize {
253        self.total
254    }
255
256    fn iter(&self) -> impl Iterator<Item = (char, usize)> {
257        self.table.iter().map(|(c, count)| (*c, *count as usize))
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use proptest::prelude::*;
265
266    fn slots(frequency: &FrequencyPerfect) -> usize {
267        frequency.slots.len()
268    }
269
270    #[test]
271    fn perfect_grows_on_collision() {
272        let mut frequency = FrequencyPerfect::default();
273        assert_eq!(slots(&frequency), 3);
274
275        // 'a' is 97 and 'd' is 100, which need the same slot of three, but not of seven.
276        frequency.insert('a', 1);
277        frequency.insert('d', 2);
278        assert_eq!(slots(&frequency), 7);
279        frequency.insert('a', 4);
280        assert_eq!(slots(&frequency), 7);
281        assert_eq!(frequency.total(), 7);
282
283        // in the order of the slots: 100 % 7 is 2, and 97 % 7 is 6.
284        let entries: Vec<_> = frequency.iter().collect();
285        assert_eq!(entries, [('d', 2), ('a', 5)]);
286        assert_eq!(frequency.nth(1), Some(('d', 2)));
287        assert_eq!(frequency.nth(2), Some(('a', 5)));
288        assert_eq!(frequency.nth(7), None);
289    }
290
291    #[test]
292    fn perfect_ignores_empty_counts() {
293        let mut frequency = FrequencyPerfect::default();
294        frequency.insert('a', 0);
295        assert_eq!(frequency, FrequencyPerfect::default());
296    }
297
298    #[test]
299    fn perfect_holds_any_characters() {
300        let mut frequency = FrequencyPerfect::default();
301        for character in ['\0', char::MAX, '\u{10fffe}', 'a', '日'] {
302            frequency.insert(character, 1);
303        }
304        assert_eq!(frequency.iter().count(), 5);
305    }
306
307    proptest! {
308        /// Has the same entries as a [FrequencyBTree], in the same order.
309        #[test]
310        fn sorted_same_as_btree(entries: Vec<(char, u8)>) {
311            let mut sorted = FrequencySorted::default();
312            let mut btree = FrequencyBTree::default();
313            for (character, count) in &entries {
314                sorted.insert(*character, *count as usize);
315                btree.insert(*character, *count as usize);
316            }
317
318            prop_assert_eq!(sorted.total(), btree.total());
319            let entries: Vec<_> = sorted.iter().collect();
320            let expected: Vec<_> = btree.iter().collect();
321            prop_assert_eq!(entries, expected);
322        }
323
324        /// Has the same counts as the other tables, in an order that does not depend on the
325        /// order of insertion.
326        #[test]
327        fn perfect_same_as_btree(entries: Vec<(char, u8)>) {
328            let mut perfect = FrequencyPerfect::default();
329            let mut reverse = FrequencyPerfect::default();
330            let mut btree = FrequencyBTree::default();
331            for (character, count) in &entries {
332                perfect.insert(*character, *count as usize);
333                btree.insert(*character, *count as usize);
334            }
335            for (character, count) in entries.iter().rev() {
336                reverse.insert(*character, *count as usize);
337            }
338
339            prop_assert_eq!(&perfect, &reverse);
340            prop_assert_eq!(perfect.total(), btree.total());
341            let mut sorted: Vec<_> = perfect.iter().collect();
342            sorted.sort();
343            let expected: Vec<_> = btree.iter().filter(|(_, count)| *count != 0).collect();
344            prop_assert_eq!(sorted, expected);
345        }
346    }
347}