winnow/stream/
stateful.rs

1use crate::error::Needed;
2use crate::stream::AsBStr;
3use crate::stream::AsBytes;
4use crate::stream::Checkpoint;
5use crate::stream::Compare;
6use crate::stream::CompareResult;
7use crate::stream::FindSlice;
8use crate::stream::Location;
9use crate::stream::Offset;
10#[cfg(feature = "unstable-recover")]
11#[cfg(feature = "std")]
12use crate::stream::Recover;
13use crate::stream::SliceLen;
14use crate::stream::Stream;
15use crate::stream::StreamIsPartial;
16use crate::stream::UpdateSlice;
17
18/// Thread global state through your parsers
19///
20/// Use cases
21/// - Recursion checks
22/// - Error recovery
23/// - Debugging
24///
25/// # Example
26///
27/// ```
28/// # use std::cell::Cell;
29/// # use winnow::prelude::*;
30/// # use winnow::stream::Stateful;
31/// # use winnow::ascii::alpha1;
32/// # type Error = ();
33///
34/// #[derive(Debug)]
35/// struct State<'s>(&'s mut u32);
36///
37/// impl<'s> State<'s> {
38///     fn count(&mut self) {
39///         *self.0 += 1;
40///     }
41/// }
42///
43/// type Stream<'is> = Stateful<&'is str, State<'is>>;
44///
45/// fn word<'s>(i: &mut Stream<'s>) -> ModalResult<&'s str> {
46///   i.state.count();
47///   alpha1.parse_next(i)
48/// }
49///
50/// let data = "Hello";
51/// let mut state = 0;
52/// let input = Stream { input: data, state: State(&mut state) };
53/// let output = word.parse(input).unwrap();
54/// assert_eq!(state, 1);
55/// ```
56#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
57#[doc(alias = "LocatingSliceSpan")]
58pub struct Stateful<I, S> {
59    /// Inner input being wrapped in state
60    pub input: I,
61    /// User-provided state
62    pub state: S,
63}
64
65impl<I, S> AsRef<I> for Stateful<I, S> {
66    #[inline(always)]
67    fn as_ref(&self) -> &I {
68        &self.input
69    }
70}
71
72impl<I, S> crate::lib::std::ops::Deref for Stateful<I, S> {
73    type Target = I;
74
75    #[inline(always)]
76    fn deref(&self) -> &Self::Target {
77        self.as_ref()
78    }
79}
80
81impl<I: crate::lib::std::fmt::Display, S> crate::lib::std::fmt::Display for Stateful<I, S> {
82    fn fmt(&self, f: &mut crate::lib::std::fmt::Formatter<'_>) -> crate::lib::std::fmt::Result {
83        self.input.fmt(f)
84    }
85}
86
87impl<I, S> SliceLen for Stateful<I, S>
88where
89    I: SliceLen,
90{
91    #[inline(always)]
92    fn slice_len(&self) -> usize {
93        self.input.slice_len()
94    }
95}
96
97impl<I: Stream, S: crate::lib::std::fmt::Debug> Stream for Stateful<I, S> {
98    type Token = <I as Stream>::Token;
99    type Slice = <I as Stream>::Slice;
100
101    type IterOffsets = <I as Stream>::IterOffsets;
102
103    type Checkpoint = Checkpoint<I::Checkpoint, Self>;
104
105    #[inline(always)]
106    fn iter_offsets(&self) -> Self::IterOffsets {
107        self.input.iter_offsets()
108    }
109    #[inline(always)]
110    fn eof_offset(&self) -> usize {
111        self.input.eof_offset()
112    }
113
114    #[inline(always)]
115    fn next_token(&mut self) -> Option<Self::Token> {
116        self.input.next_token()
117    }
118
119    #[inline(always)]
120    fn peek_token(&self) -> Option<Self::Token> {
121        self.input.peek_token()
122    }
123
124    #[inline(always)]
125    fn offset_for<P>(&self, predicate: P) -> Option<usize>
126    where
127        P: Fn(Self::Token) -> bool,
128    {
129        self.input.offset_for(predicate)
130    }
131    #[inline(always)]
132    fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
133        self.input.offset_at(tokens)
134    }
135    #[inline(always)]
136    fn next_slice(&mut self, offset: usize) -> Self::Slice {
137        self.input.next_slice(offset)
138    }
139    #[inline(always)]
140    fn peek_slice(&self, offset: usize) -> Self::Slice {
141        self.input.peek_slice(offset)
142    }
143
144    #[inline(always)]
145    fn checkpoint(&self) -> Self::Checkpoint {
146        Checkpoint::<_, Self>::new(self.input.checkpoint())
147    }
148    #[inline(always)]
149    fn reset(&mut self, checkpoint: &Self::Checkpoint) {
150        self.input.reset(&checkpoint.inner);
151    }
152
153    #[inline(always)]
154    fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
155        &self.input
156    }
157}
158
159impl<I, S> Location for Stateful<I, S>
160where
161    I: Location,
162{
163    #[inline(always)]
164    fn previous_token_end(&self) -> usize {
165        self.input.previous_token_end()
166    }
167    #[inline(always)]
168    fn current_token_start(&self) -> usize {
169        self.input.current_token_start()
170    }
171}
172
173#[cfg(feature = "unstable-recover")]
174#[cfg(feature = "std")]
175impl<I, E, S> Recover<E> for Stateful<I, S>
176where
177    I: Recover<E>,
178    I: Stream,
179    S: Clone + crate::lib::std::fmt::Debug,
180{
181    #[inline(always)]
182    fn record_err(
183        &mut self,
184        _token_start: &Self::Checkpoint,
185        _err_start: &Self::Checkpoint,
186        err: E,
187    ) -> Result<(), E> {
188        Err(err)
189    }
190
191    /// Report whether the [`Stream`] can save off errors for recovery
192    #[inline(always)]
193    fn is_recovery_supported() -> bool {
194        false
195    }
196}
197
198impl<I, S> StreamIsPartial for Stateful<I, S>
199where
200    I: StreamIsPartial,
201{
202    type PartialState = I::PartialState;
203
204    #[inline]
205    fn complete(&mut self) -> Self::PartialState {
206        self.input.complete()
207    }
208
209    #[inline]
210    fn restore_partial(&mut self, state: Self::PartialState) {
211        self.input.restore_partial(state);
212    }
213
214    #[inline(always)]
215    fn is_partial_supported() -> bool {
216        I::is_partial_supported()
217    }
218
219    #[inline(always)]
220    fn is_partial(&self) -> bool {
221        self.input.is_partial()
222    }
223}
224
225impl<I, S> Offset for Stateful<I, S>
226where
227    I: Stream,
228    S: Clone + crate::lib::std::fmt::Debug,
229{
230    #[inline(always)]
231    fn offset_from(&self, start: &Self) -> usize {
232        self.offset_from(&start.checkpoint())
233    }
234}
235
236impl<I, S> Offset<<Stateful<I, S> as Stream>::Checkpoint> for Stateful<I, S>
237where
238    I: Stream,
239    S: crate::lib::std::fmt::Debug,
240{
241    #[inline(always)]
242    fn offset_from(&self, other: &<Stateful<I, S> as Stream>::Checkpoint) -> usize {
243        self.checkpoint().offset_from(other)
244    }
245}
246
247impl<I, S> AsBytes for Stateful<I, S>
248where
249    I: AsBytes,
250{
251    #[inline(always)]
252    fn as_bytes(&self) -> &[u8] {
253        self.input.as_bytes()
254    }
255}
256
257impl<I, S> AsBStr for Stateful<I, S>
258where
259    I: AsBStr,
260{
261    #[inline(always)]
262    fn as_bstr(&self) -> &[u8] {
263        self.input.as_bstr()
264    }
265}
266
267impl<I, S, U> Compare<U> for Stateful<I, S>
268where
269    I: Compare<U>,
270{
271    #[inline(always)]
272    fn compare(&self, other: U) -> CompareResult {
273        self.input.compare(other)
274    }
275}
276
277impl<I, S, T> FindSlice<T> for Stateful<I, S>
278where
279    I: FindSlice<T>,
280{
281    #[inline(always)]
282    fn find_slice(&self, substr: T) -> Option<crate::lib::std::ops::Range<usize>> {
283        self.input.find_slice(substr)
284    }
285}
286
287impl<I, S> UpdateSlice for Stateful<I, S>
288where
289    I: UpdateSlice,
290    S: Clone + crate::lib::std::fmt::Debug,
291{
292    #[inline(always)]
293    fn update_slice(mut self, inner: Self::Slice) -> Self {
294        self.input = I::update_slice(self.input, inner);
295        self
296    }
297}