1use crate::{markov::Markov, wordlist::Wordlist};
41use rangemap::RangeInclusiveMap;
42use std::{convert::Infallible, fmt::Debug, ops::RangeInclusive, sync::Arc};
43
44pub trait State {
46 type Wordlist: Clone + Debug + PartialEq;
48 type Markov: Clone + Debug + PartialEq;
50 type Preset: Clone + Debug + PartialEq;
52 type Literal: Clone + Debug + PartialEq;
54 type Characters: Clone + Debug + PartialEq;
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
60pub struct Parsed;
61
62#[derive(Debug, Clone, PartialEq, Default)]
64pub struct Optimized;
65
66#[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 type Preset = Infallible;
92 type Literal = String;
93 type Characters = Characters;
94}
95
96#[derive(Debug, Clone, PartialEq)]
98pub enum Pattern<S: State = Parsed> {
99 Group(Group<S>),
101 Set(Set<S>),
103 Special(Special<S>),
105 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#[derive(Debug, Clone, PartialEq)]
126pub struct Literal<S: State = Parsed> {
127 pub value: S::Literal,
129}
130
131impl Literal {
132 pub fn new(value: char) -> Self {
134 Self { value }
135 }
136}
137
138#[derive(Debug, Clone, PartialEq)]
141pub struct Item<S: State = Parsed> {
142 pub pattern: Pattern<S>,
144 pub repeat: RangeInclusive<usize>,
146 pub optional: bool,
148}
149
150impl Item {
151 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 pub fn optional(mut self, optional: bool) -> Self {
162 self.optional = optional;
163 self
164 }
165
166 pub fn repeat(mut self, repeat: RangeInclusive<usize>) -> Self {
168 self.repeat = repeat;
169 self
170 }
171}
172
173#[derive(Debug, Clone, PartialEq)]
175pub struct Segment<S: State = Parsed> {
176 pub items: Vec<Item<S>>,
178 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#[derive(Debug, Clone, PartialEq, Default)]
198pub struct Group<S: State = Parsed> {
199 pub segments: Vec<Segment<S>>,
201}
202
203#[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 pub fn insert(&mut self, range: RangeInclusive<char>, count: usize) {
239 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
267const SURROGATES: RangeInclusive<u32> = 0xd800..=0xdfff;
269
270#[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: usize,
290 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 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 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 pub fn total(&self) -> usize {
338 self.ranges.last().map(|range| range.total).unwrap_or(0)
339 }
340
341 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 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 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 pub(crate) fn single(&self) -> Option<char> {
375 self.characters.single()
376 }
377}
378
379impl Set<Prepared> {
380 pub fn total(&self) -> usize {
382 self.total
383 }
384
385 pub fn characters(&self) -> impl Iterator<Item = (RangeInclusive<char>, usize)> + '_ {
387 self.characters.iter()
388 }
389
390 pub fn get(&self, index: usize) -> (char, usize) {
392 self.characters.get(index)
393 }
394
395 pub fn single(&self) -> bool {
397 self.characters.single().is_some()
398 }
399}
400
401#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
403pub struct MarkovRef {
404 pub name: String,
406 pub depth: usize,
409}
410
411impl MarkovRef {
412 pub fn new(name: impl Into<String>) -> Self {
414 Self {
415 name: name.into(),
416 depth: crate::markov::DEPTH_DEFAULT,
417 }
418 }
419
420 pub fn depth(mut self, depth: usize) -> Self {
422 self.depth = depth;
423 self
424 }
425}
426
427#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
429pub enum Special<S: State = Parsed> {
430 Wordlist(S::Wordlist),
432 Markov(S::Markov),
434 Preset(S::Preset),
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441 use test_strategy::*;
442
443 #[proptest]
445 fn test_set_total(ranges: Vec<(RangeInclusive<char>, u32)>) {
446 let total: usize = ranges
448 .iter()
449 .map(|(r, count)| *count as usize * r.clone().count())
450 .sum();
451
452 let mut set = Set::<Parsed>::default();
454 ranges
455 .into_iter()
456 .for_each(|(range, count)| set.insert(range, count as usize));
457
458 assert_eq!(set.total, total);
460 }
461
462 #[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 #[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 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 #[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}