Skip to main content

passgen/
pattern.rs

1//! Data structures for patterns.
2//!
3//! A [Pattern] is a tree: a [Group] has [Segment]s, which have [Item]s, which are groups
4//! again, or a [Set], a [Literal] or a [Special].
5//!
6//! ## Stages
7//!
8//! A pattern goes through three stages, which have the same structure with some different
9//! types in it:
10//!
11//! * [Parsed] is what [parsing](Pattern::parse) gives. It names the wordlists and presets
12//!   that it uses.
13//! * [Optimized] has data structures that are chosen for generating, and is simplified where
14//!   that does not change what is generated. [Optimizing](Pattern::optimize) also gives the
15//!   names of what the pattern uses.
16//! * [Prepared] is ready for generating. [Preparing](Pattern::prepare) puts the wordlists and
17//!   Markov chains into it, and replaces presets with their patterns.
18//!
19//! ## Example
20//!
21//! Parsing, optimizing and preparing a pattern, and generating a passphrase from it.
22//!
23//! ```
24//! use passgen::pattern::Pattern;
25//!
26//! // parse pattern (only contains literals)
27//! let pattern = Pattern::parse("abc").unwrap();
28//!
29//! // optimize pattern
30//! let pattern = pattern.optimize().0;
31//!
32//! // prepare pattern
33//! let pattern = pattern.prepare(&()).unwrap();
34//!
35//! // generate passphrase
36//! let output = pattern.generate(&mut passgen::random::Zero).unwrap();
37//! assert_eq!(output, "abc");
38//! ```
39
40use crate::{markov::Markov, wordlist::Wordlist};
41use rangemap::RangeInclusiveMap;
42use std::{convert::Infallible, fmt::Debug, ops::RangeInclusive, sync::Arc};
43
44/// Stage that a pattern is in, which decides the types that some of its parts have.
45pub trait State {
46    /// Type used to represent wordlists.
47    type Wordlist: Clone + Debug + PartialEq;
48    /// Type used to represent Markov chains.
49    type Markov: Clone + Debug + PartialEq;
50    /// Type used to represent presets.
51    type Preset: Clone + Debug + PartialEq;
52    /// Type used to represent literals.
53    type Literal: Clone + Debug + PartialEq;
54    /// Type used to represent sets of characters.
55    type Characters: Clone + Debug + PartialEq;
56}
57
58/// State where the pattern is parsed.
59#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
60pub struct Parsed;
61
62/// State where the pattern is optimized for generation.
63#[derive(Debug, Clone, PartialEq, Default)]
64pub struct Optimized;
65
66/// State where the pattern is ready for generation: it has its wordlists and Markov chains,
67/// and presets are replaced with their patterns.
68#[derive(Debug, Clone, PartialEq, Default)]
69pub struct Prepared;
70
71impl State for Parsed {
72    type Wordlist = String;
73    type Markov = MarkovRef;
74    type Preset = String;
75    type Literal = char;
76    type Characters = RangeInclusiveMap<u32, usize>;
77}
78
79impl State for Optimized {
80    type Wordlist = String;
81    type Markov = MarkovRef;
82    type Preset = String;
83    type Literal = String;
84    type Characters = Characters;
85}
86
87impl State for Prepared {
88    type Wordlist = Arc<Wordlist>;
89    type Markov = Arc<Markov>;
90    /// A prepared pattern has no presets left in it.
91    type Preset = Infallible;
92    type Literal = String;
93    type Characters = Characters;
94}
95
96/// A pattern, or a part of one.
97#[derive(Debug, Clone, PartialEq)]
98pub enum Pattern<S: State = Parsed> {
99    /// One of several segments, as in `(a|b)`.
100    Group(Group<S>),
101    /// One character out of a set, as in `[a-z]`.
102    Set(Set<S>),
103    /// A word from a wordlist or a Markov chain, or a preset.
104    Special(Special<S>),
105    /// Characters that are output as they are.
106    Literal(Literal<S>),
107}
108
109macro_rules! impl_from {
110    ($type:ident) => {
111        impl<S: State> From<$type<S>> for Pattern<S> {
112            fn from(group: $type<S>) -> Self {
113                Self::$type(group)
114            }
115        }
116    };
117}
118
119impl_from!(Group);
120impl_from!(Literal);
121impl_from!(Set);
122impl_from!(Special);
123
124/// Character or sequence of characters that is output unchanged.
125#[derive(Debug, Clone, PartialEq)]
126pub struct Literal<S: State = Parsed> {
127    /// What is output: one character when parsed, and any number of them after that.
128    pub value: S::Literal,
129}
130
131impl Literal {
132    /// Creates a literal of a character.
133    pub fn new(value: char) -> Self {
134        Self { value }
135    }
136}
137
138/// Part of a pattern with its modifiers: how many times it is repeated, and whether it is
139/// optional.
140#[derive(Debug, Clone, PartialEq)]
141pub struct Item<S: State = Parsed> {
142    /// What is repeated or left out.
143    pub pattern: Pattern<S>,
144    /// How many times it is repeated: a fixed number, or a random one from a range.
145    pub repeat: RangeInclusive<usize>,
146    /// Whether it is left out half of the time.
147    pub optional: bool,
148}
149
150impl Item {
151    /// Creates an item that is there once.
152    pub fn new<T: Into<Pattern>>(pattern: T) -> Self {
153        Self {
154            pattern: pattern.into(),
155            repeat: 1..=1,
156            optional: false,
157        }
158    }
159
160    /// The same item, optional or not.
161    pub fn optional(mut self, optional: bool) -> Self {
162        self.optional = optional;
163        self
164    }
165
166    /// The same item, repeated a number of times from the range.
167    pub fn repeat(mut self, repeat: RangeInclusive<usize>) -> Self {
168        self.repeat = repeat;
169        self
170    }
171}
172
173/// One of the segments of a [Group], which is a sequence of [Item]s.
174#[derive(Debug, Clone, PartialEq)]
175pub struct Segment<S: State = Parsed> {
176    /// What is generated, one after the other.
177    pub items: Vec<Item<S>>,
178    /// How likely this segment is to be chosen, relative to the other segments of the group.
179    /// Set with a multiplier at the start of the segment, as in `({3}a|b)`.
180    pub weight: usize,
181}
182
183impl<S: State> Default for Segment<S> {
184    fn default() -> Self {
185        Self {
186            items: Vec::new(),
187            weight: 1,
188        }
189    }
190}
191
192/// Segments, one of which is chosen at random according to their weights, as in `(a|b)`. A
193/// pattern itself is a group as well.
194///
195/// With a single segment there is nothing to choose, which uses no randomness. A group
196/// without segments generates nothing.
197#[derive(Debug, Clone, PartialEq, Default)]
198pub struct Group<S: State = Parsed> {
199    /// The segments to choose from.
200    pub segments: Vec<Segment<S>>,
201}
202
203/// Set of characters, one of which is chosen at random, as in `[a-z]`. A character that is
204/// listed more than once is more likely. With a single character there is nothing to choose,
205/// which uses no randomness.
206#[derive(Debug, Clone, PartialEq, Default)]
207pub struct Set<S: State = Parsed> {
208    characters: S::Characters,
209    total: usize,
210}
211
212impl From<Set<Parsed>> for Set<Optimized> {
213    fn from(set: Set<Parsed>) -> Self {
214        let characters = Characters::new(
215            set.characters
216                .iter()
217                .map(|(range, weight)| (range.clone(), *weight)),
218        );
219        Self {
220            total: characters.total(),
221            characters,
222        }
223    }
224}
225
226impl From<Set<Optimized>> for Set<Prepared> {
227    fn from(set: Set<Optimized>) -> Self {
228        Self {
229            characters: set.characters,
230            total: set.total,
231        }
232    }
233}
234
235impl Set {
236    /// Adds a range of characters to the set. Characters that are in the set already become
237    /// more likely.
238    pub fn insert(&mut self, range: RangeInclusive<char>, count: usize) {
239        // the number of characters, which is less than the number of codepoints for a range
240        // that has the surrogates in it.
241        let length = range.clone().count();
242        if length == 0 {
243            return;
244        }
245        let range = (*range.start() as u32)..=(*range.end() as u32);
246
247        let overlapping = self
248            .characters
249            .overlapping(&range)
250            .map(|(range, value)| (range.clone(), *value))
251            .collect::<Vec<_>>();
252        for (subrange, previous) in overlapping.into_iter() {
253            let subrange =
254                (*subrange.start().max(range.start()))..=(*subrange.end().min(range.end()));
255            self.characters.insert(subrange, previous + count);
256        }
257
258        let gaps = self.characters.gaps(&range).collect::<Vec<_>>();
259        for range in gaps.into_iter() {
260            self.characters.insert(range, count);
261        }
262
263        self.total += length * count;
264    }
265}
266
267/// Codepoints that are not characters, which are used to encode others in UTF-16.
268const SURROGATES: RangeInclusive<u32> = 0xd800..=0xdfff;
269
270/// Characters of a set with their weights, stored for choosing one of them.
271///
272/// This is a list of ranges of characters that have the same weight, in the order of their
273/// codepoints. The order decides which character a random number stands for, so it must stay
274/// like this: a set is its characters in the order of their codepoints, each as many times as
275/// it is listed.
276///
277/// Every range knows the total of the weights up to its end, so that a character is found
278/// with a binary search, however many characters the ranges have.
279#[derive(Debug, Clone, PartialEq, Eq, Default)]
280pub struct Characters {
281    ranges: Vec<CharacterRange>,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
285struct CharacterRange {
286    start: char,
287    end: char,
288    /// Weight of every character in the range.
289    weight: usize,
290    /// Total of the weights of the characters in this range and in those before it.
291    total: usize,
292}
293
294impl CharacterRange {
295    fn len(&self) -> usize {
296        self.end as usize - self.start as usize + 1
297    }
298}
299
300impl Characters {
301    /// Creates this from ranges of codepoints with their weights, which have to be sorted and
302    /// must not overlap. Codepoints that are not characters are left out.
303    fn new(ranges: impl Iterator<Item = (RangeInclusive<u32>, usize)>) -> Self {
304        let mut characters = Self::default();
305        for (range, weight) in ranges {
306            let (start, end) = (*range.start(), *range.end());
307
308            // around the surrogates, a range is split into the part before and after them.
309            let before = start..=end.min(SURROGATES.start() - 1);
310            let after = start.max(SURROGATES.end() + 1)..=end;
311            for part in [before, after] {
312                let bounds = (char::from_u32(*part.start()), char::from_u32(*part.end()));
313                if let (Some(start), Some(end)) = bounds
314                    && start <= end
315                    && weight > 0
316                {
317                    characters.push(start, end, weight);
318                }
319            }
320        }
321        characters
322    }
323
324    fn push(&mut self, start: char, end: char, weight: usize) {
325        debug_assert!(self.ranges.last().is_none_or(|last| last.end < start));
326        let mut range = CharacterRange {
327            start,
328            end,
329            weight,
330            total: 0,
331        };
332        range.total = self.total() + range.len() * weight;
333        self.ranges.push(range);
334    }
335
336    /// Total of the weights of all characters.
337    pub fn total(&self) -> usize {
338        self.ranges.last().map(|range| range.total).unwrap_or(0)
339    }
340
341    /// The character, if there is only one, whatever its weight is.
342    pub fn single(&self) -> Option<char> {
343        match &self.ranges[..] {
344            [range] if range.start == range.end => Some(range.start),
345            _ => None,
346        }
347    }
348
349    /// Ranges of characters, with the weight that every character in them has.
350    pub fn iter(&self) -> impl Iterator<Item = (RangeInclusive<char>, usize)> + '_ {
351        self.ranges
352            .iter()
353            .map(|range| (range.start..=range.end, range.weight))
354    }
355
356    /// The character at an index, with its weight. The characters are in the order of their
357    /// codepoints, and a character with a weight is there that many times in a row.
358    ///
359    /// # Panics
360    ///
361    /// This will panic if the index is not below the total.
362    pub fn get(&self, index: usize) -> (char, usize) {
363        let position = self.ranges.partition_point(|range| range.total <= index);
364        let range = &self.ranges[position];
365        let offset = (index - (range.total - range.len() * range.weight)) / range.weight;
366        let character = char::from_u32(range.start as u32 + offset as u32)
367            .expect("a range has no surrogates in it");
368        (character, range.weight)
369    }
370}
371
372impl Set<Optimized> {
373    /// The character of the set, if it only has a single one.
374    pub(crate) fn single(&self) -> Option<char> {
375        self.characters.single()
376    }
377}
378
379impl Set<Prepared> {
380    /// Total of the weights of all characters in the set.
381    pub fn total(&self) -> usize {
382        self.total
383    }
384
385    /// Ranges of characters in the set, with the weight that every character in them has.
386    pub fn characters(&self) -> impl Iterator<Item = (RangeInclusive<char>, usize)> + '_ {
387        self.characters.iter()
388    }
389
390    /// The character at an index below the total, with its weight.
391    pub fn get(&self, index: usize) -> (char, usize) {
392        self.characters.get(index)
393    }
394
395    /// Whether the set only has a single character, so that there is nothing to choose.
396    pub fn single(&self) -> bool {
397        self.characters.single().is_some()
398    }
399}
400
401/// Which Markov chain a pattern uses, as in `\m{english:3}`.
402#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
403pub struct MarkovRef {
404    /// Name of the wordlist that the chain is built from.
405    pub name: String,
406    /// Depth of the chain. This is [DEPTH_DEFAULT](crate::markov::DEPTH_DEFAULT) when the
407    /// pattern does not say.
408    pub depth: usize,
409}
410
411impl MarkovRef {
412    /// The chain for a wordlist with the default depth.
413    pub fn new(name: impl Into<String>) -> Self {
414        Self {
415            name: name.into(),
416            depth: crate::markov::DEPTH_DEFAULT,
417        }
418    }
419
420    /// The same chain with another depth.
421    pub fn depth(mut self, depth: usize) -> Self {
422        self.depth = depth;
423        self
424    }
425}
426
427/// Something that a pattern uses by name: a wordlist, a Markov chain or a preset.
428#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
429pub enum Special<S: State = Parsed> {
430    /// A word from a wordlist, as in `\w{name}`.
431    Wordlist(S::Wordlist),
432    /// A made-up word from a Markov chain, as in `\m{name:3}`.
433    Markov(S::Markov),
434    /// The pattern of a preset, as in `\p{name}`. Not in a prepared pattern.
435    Preset(S::Preset),
436}
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441    use test_strategy::*;
442
443    /// The total counts every character as often as it was inserted.
444    #[proptest]
445    fn test_set_total(ranges: Vec<(RangeInclusive<char>, u32)>) {
446        // calculate total independently from ranges
447        let total: usize = ranges
448            .iter()
449            .map(|(r, count)| *count as usize * r.clone().count())
450            .sum();
451
452        // load into set
453        let mut set = Set::<Parsed>::default();
454        ranges
455            .into_iter()
456            .for_each(|(range, count)| set.insert(range, count as usize));
457
458        // total in set should match calculated value
459        assert_eq!(set.total, total);
460    }
461
462    /// The same, with overlapping ranges inserted.
463    #[proptest]
464    fn test_set_counts(ranges: Vec<(RangeInclusive<char>, u32)>) {
465        let total: usize = ranges
466            .iter()
467            .map(|(r, count)| *count as usize * r.clone().count())
468            .sum();
469        let mut set = Set::<Parsed>::default();
470        ranges
471            .into_iter()
472            .for_each(|(range, count)| set.insert(range, count as usize));
473        assert_eq!(set.total, total);
474    }
475
476    fn build(ranges: &[(RangeInclusive<char>, usize)]) -> Characters {
477        let mut set = Set::<Parsed>::default();
478        for (range, count) in ranges {
479            set.insert(range.clone(), *count);
480        }
481        Set::<Optimized>::from(set).characters
482    }
483
484    #[test]
485    fn characters_get() {
486        let characters = build(&[('a'..='c', 1), ('x'..='x', 1), ('b'..='b', 1)]);
487        assert_eq!(characters.total(), 5);
488        let all: Vec<_> = (0..5).map(|index| characters.get(index)).collect();
489        assert_eq!(all, [('a', 1), ('b', 2), ('b', 2), ('c', 1), ('x', 1)]);
490        let ranges: Vec<_> = characters.iter().collect();
491        assert_eq!(
492            ranges,
493            [
494                ('a'..='a', 1),
495                ('b'..='b', 2),
496                ('c'..='c', 1),
497                ('x'..='x', 1)
498            ]
499        );
500    }
501
502    #[test]
503    fn characters_weights() {
504        let characters = build(&[('a'..='b', 3), ('b'..='c', 2)]);
505        assert_eq!(characters.total(), 10);
506        let all: String = (0..10).map(|index| characters.get(index).0).collect();
507        assert_eq!(all, "aaabbbbbcc");
508        assert_eq!(characters.get(3), ('b', 5));
509    }
510
511    /// Codepoints between the last character before the surrogates and the first one after
512    /// them are not characters.
513    #[test]
514    fn characters_surrogates() {
515        let characters = build(&[('\u{d7fe}'..='\u{e001}', 1)]);
516        assert_eq!(characters.total(), 4);
517        let all: Vec<_> = (0..4).map(|index| characters.get(index).0).collect();
518        assert_eq!(all, ['\u{d7fe}', '\u{d7ff}', '\u{e000}', '\u{e001}']);
519
520        let everything = build(&[('\0'..=char::MAX, 1)]);
521        assert_eq!(everything.total(), 0x110000 - 0x800);
522
523        // the total is the same before optimizing.
524        let mut set = Set::<Parsed>::default();
525        set.insert('\0'..=char::MAX, 2);
526        assert_eq!(set.total, 2 * (0x110000 - 0x800));
527        assert_eq!(Set::<Optimized>::from(set).total, 2 * (0x110000 - 0x800));
528        assert_eq!(everything.get(0xd7ff).0, '\u{d7ff}');
529        assert_eq!(everything.get(0xd800).0, '\u{e000}');
530        assert_eq!(everything.get(everything.total() - 1).0, char::MAX);
531    }
532
533    /// Is the same as a list of all the characters, each as many times as its weight.
534    #[proptest]
535    fn characters_same_as_list(
536        #[strategy(proptest::collection::vec(("[a-h\u{d7fd}-\u{e002}]", 0u32..6, 1usize..4), 0..8))]
537        ranges: Vec<(String, u32, usize)>,
538    ) {
539        use std::collections::BTreeMap;
540
541        let ranges: Vec<(RangeInclusive<char>, usize)> = ranges
542            .into_iter()
543            .filter_map(|(start, length, count)| {
544                let start = start.chars().next().unwrap();
545                let end = (start..=char::MAX).nth(length as usize)?;
546                Some((start..=end, count))
547            })
548            .collect();
549
550        let mut weights = BTreeMap::<char, usize>::new();
551        for (range, count) in &ranges {
552            for character in range.clone() {
553                *weights.entry(character).or_default() += count;
554            }
555        }
556        let list: Vec<(char, usize)> = weights
557            .iter()
558            .flat_map(|(character, weight)| std::iter::repeat_n((*character, *weight), *weight))
559            .collect();
560
561        let characters = build(&ranges);
562        assert_eq!(characters.total(), list.len());
563        let all: Vec<_> = (0..list.len()).map(|index| characters.get(index)).collect();
564        assert_eq!(all, list);
565    }
566}