slk-tokenstream 0.4.0

A small crate for handling look ahead, consumption, and otherwise manipulating an array of tokens
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use crate::{bookmark::Mark, span::TokenstreamSpan};

/// A generic TokenStream struct that manages a stream of tokens with cursor and bookmark functionality.
///
/// # Examples
///
/// ``` rust
/// use slk_tokenstream::TokenStream;
/// use slk_tokenstream::Mark;
/// 
/// let tokens = &[1, 2, 3];
/// let mut token_stream = TokenStream::new(tokens);
///
/// assert_eq!(token_stream.consume(), Some(&1));
/// assert_eq!(token_stream.peek(), Some(&2));
/// assert_eq!(token_stream.tokens_remaining(), 2);
/// ```
#[derive(Debug)]
pub struct TokenStream<'a, T> {
    data: &'a [T],
    cursor: usize,
}

impl<'a, T> TokenStream<'a, T> {
    /// Creates a new TokenStream from a vector of tokens. Sets cursor to 0.
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.peek(), Some(&1));
    /// assert_eq!(token_stream.peek_offset(1), Some(&2));
    /// assert_eq!(token_stream.peek_offset(2), Some(&3));
    /// ```
    pub fn new(data: &'a [T]) -> Self {
        TokenStream { data, cursor: 0 }
    }
    /// Advances the cursor and returns the next token if available, otherwise returns None.
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.consume(), Some(&1));
    /// assert_eq!(token_stream.consume(), Some(&2));
    /// assert_eq!(token_stream.consume(), Some(&3));
    /// assert_eq!(token_stream.consume(), None);
    /// ```
    pub fn consume(&mut self) -> Option<&T> {
        self.data.get(self.cursor).inspect(|_| self.cursor += 1)
    }
    /// Peeks at the token at the current cursor position without advancing the cursor.
    /// 
    /// # Examples
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.peek(), Some(&1));
    /// ```
    pub fn peek(&self) -> Option<&T> {
        self.peek_offset(0)
    }
    /// Peeks at the current cursor position plus an offset without advancing the cursor.
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.peek(), Some(&1));
    /// assert_eq!(token_stream.peek_offset(1), Some(&2));
    /// assert_eq!(token_stream.peek_offset(2), Some(&3));
    /// ```
    pub fn peek_offset(&self, offset: usize) -> Option<&T> {
        self.data.get(self.cursor.saturating_add(offset))
    }
    /// Moves the cursor back by one position, saturating at zero.
    /// 
    /// # Examples
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.consume(), Some(&1));
    /// token_stream.rewind();
    /// assert_eq!(token_stream.consume(), Some(&1));
    /// ```
    pub fn rewind(&mut self) {
        self.rewind_offset(1);
    }
    /// Rewinds the cursor a specified amount of times, saturating at 0.
    /// 
    /// # Examples
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.consume(), Some(&1));
    /// assert_eq!(token_stream.consume(), Some(&2));
    /// assert_eq!(token_stream.consume(), Some(&3));
    /// assert_eq!(token_stream.consume(), None);
    /// token_stream.rewind_offset(2);
    /// assert_eq!(token_stream.consume(), Some(&2));
    /// ```
    pub fn rewind_offset(&mut self, offset: usize) {
        self.cursor = self.cursor.saturating_sub(offset);
    }
    /// Returns a mark to the current cursor position.
    /// 
    /// # Examples
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// let mark = token_stream.mark();
    /// 
    /// token_stream.advance(5);
    /// assert_eq!(token_stream.peek(), None);
    /// token_stream.reset(&mark);
    /// assert_eq!(token_stream.peek(), Some(&1));
    /// ```
    pub fn mark(&self) -> Mark {
        Mark::new(self.cursor)
    }
    /// Moves the cursor to the position of a previously registered bookmark by handle and returns the previous position
    /// 
    /// # Examples
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// let mark = token_stream.mark();
    /// 
    /// token_stream.advance(3);
    /// assert_eq!(token_stream.peek(), None);
    /// assert_eq!(token_stream.reset(&mark), 3);
    /// assert_eq!(token_stream.peek(), Some(&1));
    /// ```
    pub fn reset(&mut self, bookmark: &Mark) -> usize {
        let old = self.cursor;
        self.cursor = bookmark.position();
        old
    }
    /// Returns the amount of tokens remaining, including the current token
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.tokens_remaining(), 3);
    /// assert_eq!(token_stream.consume(), Some(&1));
    /// assert_eq!(token_stream.tokens_remaining(), 2);
    /// assert_eq!(token_stream.consume(), Some(&2));
    /// assert_eq!(token_stream.tokens_remaining(), 1);
    /// ```
    pub fn tokens_remaining(&self) -> usize {
        self.data.len().saturating_sub(self.cursor)
    }
    /// Returns if the current token is the end of file
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert!(!token_stream.is_eof());
    /// assert_eq!(token_stream.consume(), Some(&1));
    /// assert_eq!(token_stream.consume(), Some(&2));
    /// assert_eq!(token_stream.consume(), Some(&3));
    /// assert!(token_stream.is_eof());
    /// ```
    pub fn is_eof(&self) -> bool {
        self.peek().is_none()
    }
    /// Returns a slice from a span
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// let mark_1 = token_stream.mark();
    /// token_stream.advance(3);
    /// let mark_2 = token_stream.mark();
    /// 
    /// let span = token_stream.span_from_marks(mark_1, mark_2);
    /// 
    /// assert_eq!(token_stream.slice_from_span(&span), &[1, 2, 3]);
    /// ```
    pub fn slice_from_span(&self, span: &TokenstreamSpan) -> &[T] {
        let idx_1 = span.start().position();
        let idx_2 = span.end().position();
        &self.data[idx_1..idx_2]
    }
    /// Advances the cursor by specified amount
    ///
    /// Cursor is clamped to the length of the data
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// token_stream.advance(2);
    /// assert_eq!(token_stream.peek(), Some(&3));
    /// ```
    pub fn advance(&mut self, offset: usize) {
        self.cursor = self.data.len().min(self.cursor.saturating_add(offset));
    }
    /// Returns the next item if it exists and the closure returns true
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.peek_if(|token| *token == 1), Some(&1));
    /// assert_eq!(token_stream.peek_if(|token| *token == 2), None);
    /// ```
    pub fn peek_if<F: Fn(&T) -> bool>(&self, f: F) -> Option<&T> {
        match self.peek() {
            Some(v) if f(v) => Some(v),
            _ => None,
        }
    }
    /// Returns the next item and advances the cursor if the item exists and the closure returns true
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.consume_if(|token| *token == 1), Some(&1));
    /// assert_eq!(token_stream.consume_if(|token| *token == 2), Some(&2));
    /// ```
    pub fn consume_if<F: Fn(&T) -> bool>(&mut self, f: F) -> Option<&T> {
        let ok = match self.peek() {
            Some(v) if f(v) => true,
            _ => false,
        };
        if ok { self.consume() } else { None }
    }
    /// Returns a slice of items starting from the cursor and ending when the closure returns false. The cursor remains on the first item failing the test
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.consume_while(|token| *token < 3), &[1, 2]);
    /// assert_eq!(token_stream.peek(), Some(&3));
    /// ```
    pub fn consume_while<F: Fn(&T) -> bool>(&mut self, f: F) -> &[T] {
        let m1 = self.mark();
        while self.consume_if(&f).is_some() {}
        let m2 = self.mark();
        let slice = self.slice_from_span(&self.span_from_marks(m1, m2));
        slice
    }
    /// Returns a slice of items starting from the cursor and ending when the closure returns false. The cursor remains in the original position
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.peek_while(|token| *token < 3), &[1, 2]);
    /// assert_eq!(token_stream.peek(), Some(&1));
    /// ```
    pub fn peek_while<F: Fn(&T) -> bool>(&self, f: F) -> &[T] {
        let len = self.data[self.cursor..]
            .iter().take_while(|item| f(item))
            .count();
        &self.data[self.cursor..self.cursor + len]
    }
    /// Advances the cursor 1 step
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// token_stream.skip();
    /// assert_eq!(token_stream.peek(), Some(&2));
    /// token_stream.skip();
    /// assert_eq!(token_stream.peek(), Some(&3));
    /// ```
    pub fn skip(&mut self) {
        self.advance(1);
    }
    /// Advances the cursor one step if the closure returns true
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// token_stream.skip_if(|token| *token == 1);
    /// assert_eq!(token_stream.peek(), Some(&2));
    /// token_stream.skip_if(|token| *token == 1);
    /// assert_eq!(token_stream.peek(), Some(&2));
    /// ```
    pub fn skip_if<F: Fn(&T) -> bool>(&mut self, f: F) {
        match self.peek_if(f) {
            Some(_) => self.skip(),
            None => {}
        }
    }
    /// Advances the cursor until the closure returns false
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// 
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// token_stream.skip_while(|token| *token < 3);
    /// assert_eq!(token_stream.peek(), Some(&3));
    /// ```
    pub fn skip_while<F: Fn(&T) -> bool>(&mut self, f: F) {
        while self.peek_if(&f).is_some() {
            self.advance(1);
        }
    }

    /// Returns the current position of the cursor
    /// 
    /// # Examples
    /// 
    /// ``` rust
    /// use slk_tokenstream::TokenStream;
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// assert_eq!(token_stream.position(), 0);
    /// assert_eq!(token_stream.consume(), Some(&1));
    /// assert_eq!(token_stream.position(), 1);
    /// assert_eq!(token_stream.consume(), Some(&2));
    /// assert_eq!(token_stream.position(), 2);
    /// assert_eq!(token_stream.consume(), Some(&3));
    /// assert_eq!(token_stream.position(), 3);
    /// ```
    pub fn position(&self) -> usize {
        self.cursor
    }

    /// Creates a span from two marks
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// use slk_tokenstream::TokenStream;
    /// let tokens = &[1, 2, 3];
    /// let mut token_stream = TokenStream::new(tokens);
    /// 
    /// let m1 = token_stream.mark();
    /// token_stream.consume();
    /// let m2 = token_stream.mark();
    /// 
    /// let span = token_stream.span_from_marks(m1, m2);
    /// 
    /// assert_eq!(token_stream.slice_from_span(&span), &[1]);
    /// ```
    pub fn span_from_marks(&self, start: Mark, end: Mark) -> TokenstreamSpan {
        TokenstreamSpan::new(start, end)
    }
}