kalosm_sample/structured_parser/
sentence.rs1use std::ops::{Deref, DerefMut};
2
3use crate::{CreateParserState, Parse, SendCreateParserState};
4use crate::{ParseStatus, Parser, StringParser};
5
6#[derive(Clone, Debug)]
7pub struct Sentence<const MIN_LENGTH: usize = 1, const MAX_LENGTH: usize = 200>(pub String);
9
10impl<const MIN_LENGTH: usize, const MAX_LENGTH: usize> Sentence<MIN_LENGTH, MAX_LENGTH> {
11 pub fn new(word: String) -> Self {
13 assert!(word.len() >= MIN_LENGTH);
14 assert!(word.len() <= MAX_LENGTH);
15 Self(word)
16 }
17}
18
19impl<const MIN_LENGTH: usize, const MAX_LENGTH: usize> From<Sentence<MIN_LENGTH, MAX_LENGTH>>
20 for String
21{
22 fn from(word: Sentence<MIN_LENGTH, MAX_LENGTH>) -> Self {
23 word.0
24 }
25}
26
27impl<const MIN_LENGTH: usize, const MAX_LENGTH: usize> From<String>
28 for Sentence<MIN_LENGTH, MAX_LENGTH>
29{
30 fn from(word: String) -> Self {
31 Self(word)
32 }
33}
34
35impl<const MIN_LENGTH: usize, const MAX_LENGTH: usize> Deref for Sentence<MIN_LENGTH, MAX_LENGTH> {
36 type Target = String;
37
38 fn deref(&self) -> &Self::Target {
39 &self.0
40 }
41}
42
43impl<const MIN_LENGTH: usize, const MAX_LENGTH: usize> DerefMut
44 for Sentence<MIN_LENGTH, MAX_LENGTH>
45{
46 fn deref_mut(&mut self) -> &mut Self::Target {
47 &mut self.0
48 }
49}
50
51pub struct SentenceParser<const MIN_LENGTH: usize = 1, const MAX_LENGTH: usize = 200> {
53 parser: StringParser<fn(char) -> bool>,
54}
55
56impl SentenceParser {
57 pub fn new() -> Self {
59 Self::default()
60 }
61}
62
63impl<const MIN_LENGTH: usize, const MAX_LENGTH: usize> Default
64 for SentenceParser<MIN_LENGTH, MAX_LENGTH>
65{
66 fn default() -> Self {
67 Self {
68 parser: StringParser::new(MIN_LENGTH..=MAX_LENGTH).with_allowed_characters(|c| {
69 c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | ';' | ',')
70 }),
71 }
72 }
73}
74
75impl<const MIN_LENGTH: usize, const MAX_LENGTH: usize> CreateParserState
76 for SentenceParser<MIN_LENGTH, MAX_LENGTH>
77{
78 fn create_parser_state(&self) -> <Self as Parser>::PartialState {
79 self.parser.create_parser_state()
80 }
81}
82
83impl<const MIN_LENGTH: usize, const MAX_LENGTH: usize> Parser
84 for SentenceParser<MIN_LENGTH, MAX_LENGTH>
85{
86 type Output = Sentence<MIN_LENGTH, MAX_LENGTH>;
87 type PartialState = <StringParser<fn(char) -> bool> as Parser>::PartialState;
88
89 fn parse<'a>(
90 &self,
91 state: &Self::PartialState,
92 input: &'a [u8],
93 ) -> crate::ParseResult<ParseStatus<'a, Self::PartialState, Self::Output>> {
94 self.parser
95 .parse(state, input)
96 .map(|result| result.map(Into::into))
97 }
98}
99
100impl<const MIN_LENGTH: usize, const MAX_LENGTH: usize> Parse for Sentence<MIN_LENGTH, MAX_LENGTH> {
101 fn new_parser() -> impl SendCreateParserState<Output = Self> {
102 SentenceParser::default()
103 }
104}