sbircio 0.1.0

A lightweight, Unicode-aware BufRead wrapper with peek-ahead for building parsers and lexers
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
//! A lightweight `BufRead` wrapper with Unicode-aware peek-ahead and
//! character-level scanning, designed for building parsers and lexers.
//!
//! # Quick start
//!
//! ```
//! use sbircio::Input;
//! use std::io::Cursor;
//!
//! # fn main() -> Result<(), sbircio::InputError> {
//! let source = Cursor::new("42 + hello");
//! let mut input = Input::new(source);
//!
//! let num = input.consume_while(|c| c.is_ascii_digit())?;
//! input.skip_whitespace()?;
//! input.expect("+")?;
//! input.skip_whitespace()?;
//! let word = input.consume_while(|c| c.is_alphabetic())?;
//!
//! assert_eq!(num, "42");
//! assert_eq!(word, "hello");
//! # Ok(())
//! # }
//! ```

use std::{io::BufRead, str::Utf8Error};

use thiserror::Error;

/// Errors that can occur while reading input.
#[derive(Error, Debug)]
pub enum InputError {
    /// The byte sequence read is not valid UTF-8.
    #[error("Invalid string: {0}")]
    InvalidString(#[from] Utf8Error),

    /// The stream ended in the middle of a multi-byte character.
    #[error("Unexpected EOF")]
    UnexpectedEof,

    /// The stream ended unexpectedly before a complete character or sequence could be read.
    #[error("Unsatisfied expectation: expected '{expected}', found '{found}'")]
    UnsatisfiedExpectation { expected: String, found: String },

    /// An underlying I/O error occurred.
    #[error("I/O error: {0}")]
    IO(#[from] std::io::Error),
}

impl PartialEq for InputError {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (InputError::InvalidString(a), InputError::InvalidString(b)) => a == b,
            (InputError::UnexpectedEof, InputError::UnexpectedEof) => true,
            (InputError::IO(a), InputError::IO(b)) => a.kind() == b.kind(),
            (
                InputError::UnsatisfiedExpectation {
                    expected: a1,
                    found: a2,
                },
                InputError::UnsatisfiedExpectation {
                    expected: b1,
                    found: b2,
                },
            ) => a1 == b1 && a2 == b2,
            _ => false,
        }
    }
}

/// Attempts to decode `bytes` as UTF-8, returning the longest valid prefix.
///
/// Unlike [`std::str::from_utf8`], this function does not fail on incomplete
/// multi-byte sequences at the end of the buffer: it returns the valid prefix
/// and the number of bytes consumed. It does fail if it encounters a
/// definitively invalid UTF-8 sequence.
fn try_from_utf8(bytes: &[u8]) -> Result<(&str, usize), Utf8Error> {
    match std::str::from_utf8(bytes) {
        Ok(s) => Ok((s, bytes.len())),
        Err(e) => {
            if e.error_len().is_some() {
                // Invalid UTF-8 sequence
                Err(e)
            } else {
                // Partial valid UTF-8 string
                let valid_up_to = e.valid_up_to();
                let valid_bytes = &bytes[..valid_up_to];
                // SAFETY: `valid_up_to` is guaranteed by `Utf8Error::valid_up_to` to be
                // a valid UTF-8 character boundary.
                let partial = unsafe { std::str::from_utf8_unchecked(valid_bytes) };
                Ok((partial, valid_up_to))
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Coordinates {
    line: usize,
    column: usize,
}

impl Default for Coordinates {
    /// Returns the starting position: line 1, column 1.
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Coordinates;
    ///
    /// let coords = Coordinates::default();
    /// assert_eq!(coords, Coordinates::new(1, 1));
    /// ```
    fn default() -> Self {
        Self { line: 1, column: 1 }
    }
}

impl Coordinates {
    /// Creates a new [`Coordinates`] from an explicit line and column.
    ///
    /// Both values are 1-based, matching the convention used by [`Input::coordinates`].
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Coordinates;
    ///
    /// let coords = Coordinates::new(3, 7);
    /// assert_eq!(coords.line(), 3);
    /// assert_eq!(coords.column(), 7);
    /// ```
    pub fn new(line: usize, column: usize) -> Self {
        Self { line, column }
    }

    /// Returns the 1-based line number.
    pub fn line(&self) -> usize {
        self.line
    }

    /// Returns the 1-based column number.
    pub fn column(&self) -> usize {
        self.column
    }

    fn evaluate(&mut self, ch: char) {
        if ch == '\n' {
            self.line += 1;
            self.column = 1;
        } else {
            self.column += 1;
        }
    }
}

impl std::fmt::Display for Coordinates {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.line, self.column)
    }
}

/// A reader that can peek ahead without consuming characters.
///
/// Wraps any [`BufRead`] and allows inspecting up to N Unicode characters
/// in advance, which is useful for implementing parsers and lexers.
/// Peeked characters are cached internally until explicitly consumed.
pub struct Input<R> {
    rdr: R,
    peeked: String,
    pending: Vec<u8>,
    position: usize,
    coordinates: Coordinates,
}

impl<R: BufRead> Input<R> {
    /// Creates a new `Input` that reads from the given reader.
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Input;
    /// use std::io::Cursor;
    ///
    /// let mut input = Input::new(Cursor::new("hello"));
    /// assert_eq!(input.peek().unwrap(), Some('h'));
    /// ```
    pub fn new(rdr: R) -> Self {
        Self {
            rdr,
            peeked: String::new(),
            pending: vec![],
            position: 0,
            coordinates: Coordinates::default(),
        }
    }

    /// Returns the next character without consuming it.
    ///
    /// Equivalent to `peek_n(1).map(|s| s.and_then(|s| s.chars().next()))`.
    /// Returns `None` if the stream is exhausted.
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Input;
    /// use std::io::Cursor;
    ///
    /// let mut input = Input::new(Cursor::new("hello"));
    ///
    /// // peek is idempotent: repeated calls don't consume the character
    /// assert_eq!(input.peek().unwrap(), Some('h'));
    /// assert_eq!(input.peek().unwrap(), Some('h'));
    ///
    /// assert_eq!(input.consume_char().unwrap(), Some('h'));
    /// assert_eq!(input.peek().unwrap(), Some('e'));
    /// ```
    pub fn peek(&mut self) -> Result<Option<char>, InputError> {
        let s = self.peek_n(1)?;
        Ok(s.and_then(|s| s.chars().next()))
    }

    /// Returns the next `required` characters without consuming them.
    ///
    /// Returns `None` if the stream contains fewer than `required` characters.
    /// Subsequent calls with the same or smaller values reuse the internal
    /// cache without reading from the underlying reader again.
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Input;
    /// use std::io::Cursor;
    ///
    /// let mut input = Input::new(Cursor::new("hello"));
    /// assert_eq!(input.peek_n(3).unwrap(), Some("hel"));
    /// assert_eq!(input.peek_n(5).unwrap(), Some("hello")); // cache riusata
    /// ```
    pub fn peek_n(&mut self, required: usize) -> Result<Option<&str>, InputError> {
        let missing_chars = required.saturating_sub(self.peeked.chars().count());
        if missing_chars > 0 {
            let mut decoded = 0;
            let mut delta = String::with_capacity(missing_chars);
            loop {
                let mut curr = [0u8; 256];
                let found = self.rdr.read(&mut curr)?;
                if found == 0 {
                    break;
                }
                self.pending.extend(&curr[..found]);
                let (partial, used) = try_from_utf8(&self.pending)?;
                delta.push_str(partial);
                decoded += partial.chars().count();
                self.pending.drain(..used);
                if decoded >= missing_chars {
                    break;
                }
            }
            if !self.pending.is_empty() {
                return Err(InputError::UnexpectedEof);
            }
            self.peeked.push_str(&delta);
        }

        // index of required chars if found
        let end = self
            .peeked
            .char_indices()
            .map(|(i, _)| i)
            .chain(std::iter::once(self.peeked.len()))
            .nth(required);

        Ok(end.map(|l| &self.peeked[..l]))
    }

    /// Consumes `expected` from the input
    ///
    /// The method peeks ahead and verifies that the next characters exactly match
    /// `expected`. On success, the matched characters are removed from the internal
    /// buffer.
    ///
    /// If the input does not match `expected`, or if the end of input is reached
    /// before a complete match can be established, an
    /// [`InputError::UnsatisfiedExpectation`] is returned and no input is consumed.
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Input;
    /// use std::io::Cursor;
    ///
    /// let mut input = Input::new(Cursor::new("hello world"));
    ///
    /// input.expect("hello").unwrap();
    /// assert_eq!(input.peek_n(6).unwrap(), Some(" world"));
    ///
    /// // A failed match does not consume any input
    /// assert!(input.expect("bye").is_err());
    /// assert_eq!(input.peek_n(6).unwrap(), Some(" world"));
    /// ```
    pub fn expect(&mut self, expected: &str) -> Result<(), InputError> {
        let found = self.peek_n(expected.chars().count())?;
        let found = found.ok_or_else(|| InputError::UnsatisfiedExpectation {
            expected: expected.to_string(),
            found: String::new(),
        })?;

        if found != expected {
            Err(InputError::UnsatisfiedExpectation {
                expected: expected.to_string(),
                found: found.to_string(),
            })
        } else {
            for ch in expected.chars() {
                self.coordinates.evaluate(ch);
            }
            self.peeked.drain(..expected.len());
            self.position += expected.len();
            Ok(())
        }
    }

    /// Consumes and returns consecutive characters while `predicate` evaluates to
    /// `true`.
    ///
    /// Stops at the first character for which `predicate` returns `false`, leaving
    /// it available for subsequent reads.
    ///
    /// Returns all consumed characters as a `String`.
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Input;
    /// use std::io::Cursor;
    ///
    /// let mut input = Input::new(Cursor::new("123abc"));
    ///
    /// let digits = input.consume_while(|c| c.is_ascii_digit()).unwrap();
    /// assert_eq!(digits, "123");
    /// assert_eq!(input.peek_n(3).unwrap(), Some("abc"));
    /// ```
    pub fn consume_while<P>(&mut self, predicate: P) -> Result<String, InputError>
    where
        P: Fn(char) -> bool,
    {
        let mut found = String::new();
        loop {
            let next = self.peek()?;
            if let Some(ch) = next {
                if !predicate(ch) {
                    break;
                }
                found.push(ch);
                // TODO: Ottimizzare
                self.peeked.drain(..ch.len_utf8());
            } else {
                break;
            }
        }
        self.position += found.len();

        for ch in found.chars() {
            self.coordinates.evaluate(ch);
        }

        Ok(found)
    }

    /// Consumes and returns characters until `predicate` evaluates to `true`.
    ///
    /// The first character for which `predicate` returns `true` is not consumed
    /// and remains available for subsequent reads.
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Input;
    /// use std::io::Cursor;
    ///
    /// let mut input = Input::new(Cursor::new("hello,world"));
    ///
    /// let word = input.consume_until(|c| c == ',').unwrap();
    /// assert_eq!(word, "hello");
    /// assert_eq!(input.peek().unwrap(), Some(','));
    /// ```
    pub fn consume_until<P>(&mut self, predicate: P) -> Result<String, InputError>
    where
        P: Fn(char) -> bool,
    {
        let mut found = String::new();
        loop {
            let next = self.peek()?;
            if let Some(ch) = next {
                if predicate(ch) {
                    break;
                }
                found.push(ch);
                // TODO: Ottimizzare
                self.peeked.drain(..ch.len_utf8());
            } else {
                break;
            }
        }

        for ch in found.chars() {
            self.coordinates.evaluate(ch);
        }

        self.position += found.len();
        Ok(found)
    }

    /// Consumes and returns the next character from the input.
    ///
    /// Returns `Ok(None)` if the end of input has been reached.
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Input;
    /// use std::io::Cursor;
    ///
    /// let mut input = Input::new(Cursor::new("èa"));
    ///
    /// assert_eq!(input.consume_char().unwrap(), Some('è'));
    /// assert_eq!(input.consume_char().unwrap(), Some('a'));
    /// assert_eq!(input.consume_char().unwrap(), None);
    /// ```
    pub fn consume_char(&mut self) -> Result<Option<char>, InputError> {
        let found = self.peek()?;
        if let Some(ch) = found {
            self.peeked.drain(..ch.len_utf8());
        }

        if let Some(ch) = found {
            self.coordinates.evaluate(ch);
            self.position += ch.len_utf8();
        }

        Ok(found)
    }

    /// Ensures that the next character in the input matches `expected`.
    ///
    /// On success, the character is consumed. Otherwise, an
    /// [`InputError::UnsatisfiedExpectation`] is returned and no input is consumed.
    ///
    /// # Examples
    ///
    /// ```
    /// use sbircio::Input;
    /// use std::io::Cursor;
    ///
    /// let mut input = Input::new(Cursor::new("abc"));
    ///
    /// input.expect_char('a').unwrap();
    /// assert_eq!(input.peek().unwrap(), Some('b'));
    ///
    /// // A failed match does not consume any input
    /// assert!(input.expect_char('z').is_err());
    /// assert_eq!(input.peek().unwrap(), Some('b'));
    /// ```
    pub fn expect_char(&mut self, expected: char) -> Result<(), InputError> {
        let found = self.peek()?;
        if let Some(ch) = found {
            if expected != ch {
                Err(InputError::UnsatisfiedExpectation {
                    expected: expected.to_string(),
                    found: ch.to_string(),
                })
            } else {
                self.peeked.drain(..ch.len_utf8());
                self.coordinates.evaluate(ch);
                self.position += ch.len_utf8();
                Ok(())
            }
        } else {
            Err(InputError::UnsatisfiedExpectation {
                expected: expected.to_string(),
                found: String::new(),
            })
        }
    }

    /// Returns `true` if the end of input has been reached.
    pub fn is_eof(&mut self) -> Result<bool, InputError> {
        Ok(self.peek()?.is_none())
    }

    /// Consumes consecutive whitespace characters from the input.
    pub fn skip_whitespace(&mut self) -> Result<(), InputError> {
        self.consume_while(char::is_whitespace)?;
        Ok(())
    }

    /// Returns the current byte offset from the beginning of the stream.
    ///
    /// The offset counts bytes, not Unicode characters — for multi-byte
    /// characters (e.g. `'è'` which is 2 bytes) the position advances
    /// accordingly.
    pub fn position(&self) -> usize {
        self.position
    }

    /// Returns the current position in the input as line and column numbers.
    ///
    /// Both line and column are 1-based: the first character of the stream
    /// is at line 1, column 1. The column advances by one for each Unicode
    /// character consumed; a newline (`'\n'`) resets the column to 1 and
    /// increments the line counter.
    pub fn coordinates(&self) -> Coordinates {
        self.coordinates
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn peek_on_empty_input_returns_none() {
        let cursor = Cursor::new(Vec::<u8>::new());
        let mut input = Input::new(cursor);

        assert_eq!(input.peek().unwrap(), None);
    }

    #[test]
    fn peek_returns_first_char() {
        let cursor = Cursor::new(b"hello");
        let mut input = Input::new(cursor);

        assert_eq!(input.peek().unwrap(), Some('h'));
    }

    #[test]
    fn peek_is_idempotent() {
        let cursor = Cursor::new(b"hello");
        let mut input = Input::new(cursor);

        assert_eq!(input.peek().unwrap(), Some('h'));
        assert_eq!(input.peek().unwrap(), Some('h'));
        assert_eq!(input.peek().unwrap(), Some('h'));
    }

    #[test]
    fn peek_n_returns_prefix() {
        let cursor = Cursor::new(b"hello");
        let mut input = Input::new(cursor);

        assert_eq!(input.peek_n(3).unwrap(), Some("hel"));
    }

    #[test]
    fn peek_n_returns_full_string_when_exact_length() {
        let cursor = Cursor::new(b"hello");
        let mut input = Input::new(cursor);

        assert_eq!(input.peek_n(5).unwrap(), Some("hello"));
    }

    #[test]
    fn peek_n_beyond_eof_returns_none() {
        let cursor = Cursor::new(b"hi");
        let mut input = Input::new(cursor);

        assert_eq!(input.peek_n(3).unwrap(), None);
    }

    #[test]
    fn peek_n_handles_utf8_characters() {
        let cursor = Cursor::new("èabc".as_bytes());
        let mut input = Input::new(cursor);

        assert_eq!(input.peek_n(1).unwrap(), Some("è"));
        assert_eq!(input.peek_n(2).unwrap(), Some("èa"));
        assert_eq!(input.peek_n(4).unwrap(), Some("èabc"));
    }

    #[test]
    fn peek_handles_utf8_character() {
        let cursor = Cursor::new("èabc".as_bytes());
        let mut input = Input::new(cursor);

        let result = input.peek();

        assert!(result.is_ok());
    }

    #[test]
    fn peek_n_invalid_utf8_returns_error() {
        let cursor = Cursor::new(vec![0xff, 0xfe]);
        let mut input = Input::new(cursor);

        let err = input.peek_n(2).unwrap_err();

        matches!(err, InputError::InvalidString(_));
    }

    #[test]
    fn expect_success() {
        let cursor = Cursor::new(b"hello");
        let mut input = Input::new(cursor);

        assert!(input.expect("hell").is_ok());
        assert!(input.expect("o").is_ok());
        assert_eq!(input.peek().unwrap(), None);
    }

    #[test]
    fn expect_failure() {
        let cursor = Cursor::new(b"hello");
        let mut input = Input::new(cursor);

        let got = input.expect("ciao");
        assert_eq!(
            got,
            Err(InputError::UnsatisfiedExpectation {
                expected: "ciao".to_string(),
                found: "hell".to_string(),
            })
        );
    }

    #[test]
    fn expect_utf8() {
        let cursor = Cursor::new("è".as_bytes());
        let mut input = Input::new(cursor);

        assert!(input.expect("è").is_ok());
    }

    #[test]
    fn expect_eof() {
        let cursor = Cursor::new(b"he");
        let mut input = Input::new(cursor);

        assert_eq!(
            input.expect("hello"),
            Err(InputError::UnsatisfiedExpectation {
                expected: "hello".to_string(),
                found: String::new(),
            })
        );
    }

    #[test]
    fn expect_failure_does_not_consume() {
        let cursor = Cursor::new(b"hello");
        let mut input = Input::new(cursor);

        assert!(input.expect("ciao").is_err());

        assert_eq!(input.peek_n(5).unwrap(), Some("hello"));
    }

    #[test]
    fn expect_consumes_only_matched_text() {
        let cursor = Cursor::new(b"hello world");
        let mut input = Input::new(cursor);

        input.expect("hello").unwrap();

        assert_eq!(input.peek_n(6).unwrap(), Some(" world"));
    }

    #[test]
    fn consume_while_whitespace() {
        let cursor = Cursor::new(b"\t \nhello world");
        let mut input = Input::new(cursor);

        let x = input.consume_while(char::is_whitespace).unwrap();
        assert_eq!(x, "\t \n".to_string());
        input.expect("hello").unwrap();
    }

    #[test]
    fn consume_while_stops_before_first_non_matching() {
        let mut input = Input::new(Cursor::new("123abc"));

        let consumed = input.consume_while(|c| c.is_ascii_digit()).unwrap();

        assert_eq!(consumed, "123");
        assert_eq!(input.peek_n(3).unwrap(), Some("abc"));
    }

    #[test]
    fn consume_while_utf8_until_eof() {
        let mut input = Input::new(Cursor::new("èéà"));

        let consumed = input.consume_while(|_| true).unwrap();

        assert_eq!(consumed, "èéà");
        assert_eq!(input.peek().unwrap(), None);
    }

    #[test]
    fn consume_while_utf8() {
        let mut input = Input::new(Cursor::new("èéabc"));

        let consumed = input.consume_while(|c| !c.is_ascii()).unwrap();

        assert_eq!(consumed, "èé");
        assert_eq!(input.peek_n(3).unwrap(), Some("abc"));
    }

    #[test]
    fn consume_while_until_eof() {
        let mut input = Input::new(Cursor::new("123"));

        let consumed = input.consume_while(|c| c.is_ascii_digit()).unwrap();

        assert_eq!(consumed, "123");
        assert_eq!(input.peek().unwrap(), None);
    }

    #[test]
    fn consume_while_matches_nothing() {
        let mut input = Input::new(Cursor::new("hello"));

        let consumed = input.consume_while(char::is_whitespace).unwrap();

        assert_eq!(consumed, "");
        assert_eq!(input.peek_n(5).unwrap(), Some("hello"));
    }

    #[test]
    fn consume_until_utf8() {
        let mut input = Input::new(Cursor::new("èéà!abc"));

        let consumed = input.consume_until(|c| c == '!').unwrap();

        assert_eq!(consumed, "èéà");
        assert_eq!(input.peek().unwrap(), Some('!'));
    }

    #[test]
    fn consume_until_eof() {
        let mut input = Input::new(Cursor::new("hello"));

        let consumed = input.consume_until(|c| c == ',').unwrap();

        assert_eq!(consumed, "hello");
        assert_eq!(input.peek().unwrap(), None);
    }

    #[test]
    fn consume_until_immediate_match() {
        let mut input = Input::new(Cursor::new(",world"));

        let consumed = input.consume_until(|c| c == ',').unwrap();

        assert_eq!(consumed, "");
        assert_eq!(input.peek().unwrap(), Some(','));
    }

    #[test]
    fn consume_until_stops_before_match() {
        let mut input = Input::new(Cursor::new("hello,world"));

        let consumed = input.consume_until(|c| c == ',').unwrap();

        assert_eq!(consumed, "hello");
        assert_eq!(input.peek().unwrap(), Some(','));
    }

    #[test]
    fn consume_char_handles_utf8() {
        let mut input = Input::new(Cursor::new("èa"));

        assert_eq!(input.consume_char().unwrap(), Some('è'));
        assert_eq!(input.consume_char().unwrap(), Some('a'));
        assert_eq!(input.consume_char().unwrap(), None);
    }

    #[test]
    fn consume_char_returns_none_at_eof() {
        let mut input = Input::new(Cursor::new(""));

        assert_eq!(input.consume_char().unwrap(), None);
    }

    #[test]
    fn consume_char_returns_next_character() {
        let mut input = Input::new(Cursor::new("abc"));

        assert_eq!(input.consume_char().unwrap(), Some('a'));
        assert_eq!(input.consume_char().unwrap(), Some('b'));
        assert_eq!(input.consume_char().unwrap(), Some('c'));
    }

    #[test]
    fn expect_char_utf8() {
        let mut input = Input::new(Cursor::new("èabc"));

        assert!(input.expect_char('è').is_ok());
        assert_eq!(input.peek().unwrap(), Some('a'));
    }

    #[test]
    fn expect_char_failure() {
        let mut input = Input::new(Cursor::new("abc"));

        assert!(input.expect_char('z').is_err());

        // non deve consumare nulla
        assert_eq!(input.peek().unwrap(), Some('a'));
    }

    #[test]
    fn expect_char_success() {
        let mut input = Input::new(Cursor::new("abc"));

        assert!(input.expect_char('a').is_ok());
        assert_eq!(input.peek().unwrap(), Some('b'));
    }

    #[test]
    fn is_eof_after_consuming_utf8_input() {
        let mut input = Input::new(Cursor::new("è"));

        input.consume_char().unwrap();

        assert!(input.is_eof().unwrap());
    }

    #[test]
    fn is_eof_after_consuming_all_input() {
        let mut input = Input::new(Cursor::new("abc"));

        input.consume_char().unwrap();
        input.consume_char().unwrap();
        input.consume_char().unwrap();

        assert!(input.is_eof().unwrap());
    }

    #[test]
    fn is_eof_on_non_empty_input() {
        let mut input = Input::new(Cursor::new("abc"));

        assert!(!input.is_eof().unwrap());
    }

    #[test]
    fn is_eof_on_empty_input() {
        let mut input = Input::new(Cursor::new(""));

        assert!(input.is_eof().unwrap());
    }

    #[test]
    fn position_starts_at_zero() {
        let input = Input::new(Cursor::new("abc"));
        assert_eq!(input.position(), 0);
    }

    #[test]
    fn position_advances_by_bytes_ascii() {
        let mut input = Input::new(Cursor::new("abc"));
        input.consume_char().unwrap();
        assert_eq!(input.position(), 1);
        input.consume_char().unwrap();
        assert_eq!(input.position(), 2);
    }

    #[test]
    fn position_advances_by_bytes_utf8() {
        let mut input = Input::new(Cursor::new("èa"));
        input.consume_char().unwrap(); // 'è' = 2 byte
        assert_eq!(input.position(), 2);
        input.consume_char().unwrap(); // 'a' = 1 byte
        assert_eq!(input.position(), 3);
    }

    #[test]
    fn position_unchanged_at_eof() {
        let mut input = Input::new(Cursor::new("a"));
        input.consume_char().unwrap();
        input.consume_char().unwrap(); // EOF, non deve spostarsi
        assert_eq!(input.position(), 1);
    }

    #[test]
    fn coordinates_starts_at_line_1_col_1() {
        let input = Input::new(Cursor::new("abc"));
        assert_eq!(input.coordinates(), Coordinates::new(1, 1));
    }

    #[test]
    fn coordinates_advances_column() {
        let mut input = Input::new(Cursor::new("abc"));
        input.consume_char().unwrap();
        assert_eq!(input.coordinates(), Coordinates::new(1, 2));
    }

    #[test]
    fn coordinates_advances_line_on_newline() {
        let mut input = Input::new(Cursor::new("a\nb"));
        input.consume_char().unwrap(); // 'a'
        input.consume_char().unwrap(); // '\n'
        assert_eq!(input.coordinates(), Coordinates::new(2, 1));
        input.consume_char().unwrap(); // 'b'
        assert_eq!(input.coordinates(), Coordinates::new(2, 2));
    }
}