sipp 0.2.1

Simple parser package
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
use std::io::{Error, ErrorKind, Read};

// TODO: MAKE THE BUFFER SIZE CONFIGURABLE. (This larger size gives better performance, but some
// applications may not want or need a large buffer.)
const BUFFER_SIZE: usize = 65_536;

// Guarantee that peek will reveal at least eight bytes,
// to allow for checking of byte-order marks, etc.
const MIN_PEEK_REQUIREMENT: usize = 8;

/**
A buffered wrapper around a `Read` type, providing read and peek methods.

One byte can be read at a time, and the peek will give at least eight bytes unless the
input ends before that.

# Examples

If you need to read from a file (or any other `Read` type) one byte at a time, with execution
flow depending on the first few bytes which are received from the file, then you could use something
like this:

```
# use sipp::buffer::ByteBuffer;
use std::fs::File;
use std::io::Error;

const BOM_UTF8: &[u8] = &[0xEF, 0xBB, 0xBF];

fn main() -> Result<(), Error> {
    let file = File::open("test_resources/xml_utf8_BOM.xml")?;
    let mut byte_buffer = ByteBuffer::wrap(file);
    let first_bytes = byte_buffer.peek()?;
    if first_bytes.len() > 2 && first_bytes[0..3] == *BOM_UTF8 {
        println!("Found input which starts with UTF-8 byte order mark!");
        // Now read past the three bytes which make up the UTF-8 BOM.
        assert_eq!(byte_buffer.read_next()?, Some(0xEF));
        assert_eq!(byte_buffer.read_next()?, Some(0xBB));
        assert_eq!(byte_buffer.read_next()?, Some(0xBF));
        while let Some(b) = byte_buffer.read_next()? {
            // Do something with each byte from within the file content proper.
        }
    } else {
        println!("Found some other sort of file.");
    }
    Ok(())
}
```

Note that the `byte_buffer` variable needs to be mutable, and that the methods of ByteBuffer will
return an `std::io::Error` if anything goes wrong while trying to work with the input `Read` type.

*/
#[derive(Debug)]
pub struct ByteBuffer<R> {
    reader: R,
    buffer: [u8; BUFFER_SIZE],
    next_byte_index: usize,
    stop_byte_index: usize,
}

impl<R> ByteBuffer<R>
where
    R: Read,
{
    /**
    Returns a new `ByteBuffer` which wraps the given `Read` type.

    # Examples

    You can wrap a hardcoded string in Rust by taking a byte slice of it, using `as_bytes()`,
    because byte slices implement the trait `Read`.

    ```
    # use sipp::buffer::ByteBuffer;
    # use std::io::Error;
    #
    # fn main() -> Result<(), Error> {
    let input = "abc123<*>";
    let buffer = ByteBuffer::wrap(input.as_bytes());
    #    Ok(())
    # }
    ```

    And the Rust type `std::fs::File` also implements `Read` so you can wrap a `File` with
    `ByteBuffer` too:

    ```
    # use sipp::buffer::ByteBuffer;
    # use std::fs::File;
    # use std::io::Error;
    #
    # fn main() -> Result<(), Error> {
    let file = File::open("test_resources/xml_utf8_BOM.xml")?;
    let mut byte_buffer = ByteBuffer::wrap(file);
    #    Ok(())
    # }
    ```

    Note that `wrap` does not return a `Result`, because no attempt is made to read from the
    given `Read` type while wrapping it.

    # Warning

    Note that Rust std also allows you to pass a mutable (exclusive) reference to a `Read` type.
    However, note that because the `ByteBuffer` will read as much as possible to fill its buffer
    (every time the buffer is found to be empty) it's very probably a bad idea to return control
    to the underlying `Read` type/source, as any `read` calls made to the underlying source
    will not be able to return bytes which are sitting in the `ByteBuffer`, so those bytes will
    be skipped/ignored/lost.
    */
    pub fn wrap(reader: R) -> ByteBuffer<R> {
        ByteBuffer {
            reader,
            buffer: [0_u8; BUFFER_SIZE],
            next_byte_index: 0,
            stop_byte_index: 0,
        }
    }

    fn is_buffer_empty(&self) -> bool {
        self.stop_byte_index == self.next_byte_index
    }

    fn fill_buffer(&mut self) -> Result<(), Error> {
        loop {
            let outcome = self.reader.read(&mut self.buffer);
            if let Err(e) = outcome {
                if e.kind() == ErrorKind::Interrupted {
                    // println!("Read was interrupted. Trying again.");
                    continue;
                } else {
                    return Err(e);
                }
            } else {
                self.stop_byte_index = outcome?;
                self.next_byte_index = 0;
                return Ok(());
            }
        }
    }

    /**
    Removes and returns the next byte of content from the input, if there is any content
    available. Returns `None` if there is no content available.

    # Errors

    If something goes wrong while reading from the stream then this method will return an
    `std::io::Error` variant.

    # Examples

    Rust strings are encoded in UTF-8, so you can read the bytes from such a string and confirm
    that they are encoded as expected.

    ```
    # use sipp::buffer::ByteBuffer;
    # use std::io::Error;
    #
    # fn main() -> Result<(), Error> {
    let input = "a å 本 𐄋";
    let mut buffer = ByteBuffer::wrap(input.as_bytes());
    // Lowercase letter 'a' is codepoint U+0061, encoded in UTF-8 as one byte 0x61
    assert_eq!(buffer.read_next()?, Some(0x61));
    // Space character is codepoint U+0020, encoded in UTF-8 as one byte 0x20
    assert_eq!(buffer.read_next()?, Some(0x20));
    // 'å' is codepoint U+00E5, encoded in UTF-8 as two bytes 0xC3 0xA5
    assert_eq!(buffer.read_next()?, Some(0xC3));
    assert_eq!(buffer.read_next()?, Some(0xA5));
    // Space
    assert_eq!(buffer.read_next()?, Some(0x20));
    // '本' is codepoint U+672C, encoded in UTF-8 as three bytes 0xE6 0x9C 0xAC
    assert_eq!(buffer.read_next()?, Some(0xE6));
    assert_eq!(buffer.read_next()?, Some(0x9C));
    assert_eq!(buffer.read_next()?, Some(0xAC));
    // Space
    assert_eq!(buffer.read_next()?, Some(0x20));
    // '𐄋' is codepoint U+1010B, encoded in UTF-8 as four bytes 0xF0 0x90 0x84 0x8B
    assert_eq!(buffer.read_next()?, Some(0xF0));
    assert_eq!(buffer.read_next()?, Some(0x90));
    assert_eq!(buffer.read_next()?, Some(0x84));
    assert_eq!(buffer.read_next()?, Some(0x8B));
    // Nothing left, so any further reads will return None:
    assert_eq!(buffer.read_next()?, None);
    assert_eq!(buffer.read_next()?, None);
    assert_eq!(buffer.read_next()?, None);
    #    Ok(())
    # }
    ```
    */
    pub fn read_next(&mut self) -> Result<Option<u8>, Error> {
        if self.is_buffer_empty() {
            self.fill_buffer()?;
        }
        if self.is_buffer_empty() {
            return Ok(None);
        }
        let byte = self.buffer[self.next_byte_index];
        self.next_byte_index += 1;
        Ok(Some(byte))
    }

    /**
    Returns some number of not-yet-read bytes from the buffer, without removing them from the
    input buffer. This method promises to give at least eight bytes of content unless there are
    fewer than eight bytes remaining in the input.

    The intended use of `peek` is to check the initial bytes of input, to match them against
    some pattern such as a UTF-8 or UTF-16 BOM (byte order mark) and/or some other recognised
    sequence of bytes which will reveal the character encoding, or file format, or some other
    information which is vital before you actually attempt to start reading bytes from the
    input.

    # Errors

    If anything goes wrong while reading from the stream then this method will return an
    `std::io::Error` variant.

    # Warning

    Using `peek` at the very start of the input allows you to make decisions about character
    encoding, file format, etc. But once you've actually started reading bytes from the input,
    converted them into characters, and passed them to a parser, there is likely to be another
    buffer (of characters, rather than bytes) used by the parser, and this means that
    using `ByteBuffer.peek()` *after* parsing has begun may lead to your checking bytes which
    come after characters you've already decoded and handed to the parser. (In other words:
    `peek` cannot see bytes which have already been decoded and held in a separate buffer.) So
    it's probably best to avoid calling `peek` once you've already passed this `ByteBuffer` to a
    decoder or parser.

    # Examples

    If you know that your application will only receive UTF-8 encoded files (with no BOM), and
    only of two types, one type starting with a '<' character (encoded as 0x3C in UTF-8), and
    the other type starting with a '{' character (encoded as 0x7B in UTF-8) then you can use
    `peek` to detect the file format without actually removing anything from the buffer.

    ```
    # use sipp::buffer::ByteBuffer;
    # use std::io::Error;
    #
    # fn main() -> Result<(), Error> {
    # // I don't have a UTF-8 file without a BOM as the initial byte sequence, so let's just use
    # // a hardcoded string here (won't be visible in the documentation HTML page).
    # let file_content = "<?xml version='1.0' encoding='UTF-8'?><root></root>";
    # let some_file = file_content.as_bytes();
    let mut buffer = ByteBuffer::wrap(some_file);
    let first_bytes = buffer.peek()?;
    if first_bytes.is_empty() {
        println!("Input is completely empty!");
    } else {
        match first_bytes[0] {
            0x3C => println!("Found an XML file!"),
            0x7B => println!("Found a JSON file!"),
            _ => println!("Uh oh, found some unexpected starting byte!")
        }
    }
    # assert_eq!(first_bytes[0], 0x3C);
    #    Ok(())
    # }
    ```

    (Note that this is greatly simplified. In reality, an XML file permits any amount of
    whitespace before the '<' makes an appearance.)

    */
    pub fn peek(&mut self) -> Result<&[u8], Error> {
        if self.is_buffer_empty() {
            self.fill_buffer()?;
        }
        if self.is_buffer_empty() {
            return Ok(&[0_u8; 0]);
        }
        if (BUFFER_SIZE - self.next_byte_index) < MIN_PEEK_REQUIREMENT {
            // Move the buffer content to the start of the array, to make
            // enough room to fit in the minimum peek length.
            self.shunt_to_left();
        }
        while (self.stop_byte_index - self.next_byte_index) < MIN_PEEK_REQUIREMENT {
            // Keep topping up the buffer until we meet the minimum peek length, or run out of content.
            if self.top_up_buffer()? == 0 {
                break;
            }
        }
        Ok(&self.buffer[self.next_byte_index..self.stop_byte_index])
    }

    // Shunt (copy) all unread buffer content back to index zero.
    fn shunt_to_left(&mut self) {
        let length = self.stop_byte_index - self.next_byte_index;
        for i in 0..length {
            self.buffer[i] = self.buffer[self.next_byte_index + i];
        }
        self.next_byte_index = 0;
        self.stop_byte_index = length;
    }

    // Read content into the end of the buffer, without first clearing the buffer.
    fn top_up_buffer(&mut self) -> Result<usize, Error> {
        // println!("Entered top_up_buffer method!");
        loop {
            let outcome = self
                .reader
                .read(&mut self.buffer[self.stop_byte_index..BUFFER_SIZE]);
            if let Err(e) = outcome {
                if e.kind() == ErrorKind::Interrupted {
                    // println!("Top-up read was interrupted. Trying again.");
                    continue;
                } else {
                    return Err(e);
                }
            } else {
                let read_count = outcome?;
                self.stop_byte_index += read_count;
                return Ok(read_count);
            }
        }
    }
}

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

    // Note this useful idiom: importing names from outer (for mod tests) scope.
    use super::*;

    #[test]
    fn test_read_next() -> Result<(), Error> {
        let bytes = [0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20];
        let mut buffer = ByteBuffer::wrap(&bytes[..]);
        assert_eq!(buffer.read_next()?, Some(0xEF));
        assert_eq!(buffer.read_next()?, Some(0xBB));
        assert_eq!(buffer.read_next()?, Some(0xBF));
        assert_eq!(buffer.read_next()?, Some(0x3C));
        assert_eq!(buffer.read_next()?, Some(0x3F));
        assert_eq!(buffer.read_next()?, Some(0x78));
        assert_eq!(buffer.read_next()?, Some(0x6D));
        assert_eq!(buffer.read_next()?, Some(0x6C));
        assert_eq!(buffer.read_next()?, Some(0x20));
        assert_eq!(buffer.read_next()?, None);
        Ok(())
    }

    #[test]
    fn accepts_mut_ref_read() -> Result<(), Error> {
        let mut cursor = Cursor::new("some input");
        // Rust allows `&mut R` to be used where `R: Read` is the
        // expected method argument type.
        let mut buffer = ByteBuffer::wrap(&mut cursor);
        assert_eq!(buffer.read_next()?, Some(0x73));
        // Now stop using the ByteBuffer and relinquish the borrow
        // so that the Cursor can finish operating on the stream.
        let mut mini_buffer = [0_u8; 1];
        let read_count = cursor.read(&mut mini_buffer)?;
        // Important: the ByteBuffer has read from the Cursor to
        // fill its own buffer, so there's probably nothing left
        // in the Cursor, and so returning control the Cursor is
        // probably a bad idea.
        assert!(read_count < 2);
        Ok(())
    }

    #[test]
    fn test_read_next_empty_input() -> Result<(), Error> {
        let bytes: [u8; 0] = [];
        let mut buffer = ByteBuffer::wrap(&bytes[..]);
        assert_eq!(buffer.read_next()?, None);
        Ok(())
    }

    #[test]
    fn test_peek_input_exceeds_buffer_size() -> Result<(), Error> {
        let start_of_xml_bytes: [u8; 22] = [
            0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
            0x6F, 0x6E, 0x3D, 0x22, 0x31, 0x2E, 0x30, 0x22,
        ];
        let mut bytes: Vec<u8> = Vec::with_capacity(BUFFER_SIZE + start_of_xml_bytes.len());
        bytes.resize(BUFFER_SIZE, 0x20);
        for b in start_of_xml_bytes {
            bytes.push(b);
        }
        let mut buffer = ByteBuffer::wrap(&bytes[..]);
        for _ in 0..(BUFFER_SIZE - 4) {
            assert_eq!(buffer.read_next()?, Some(0x20));
        }
        // These index assertions rely on slice reading being greedy.
        assert_eq!(buffer.next_byte_index, BUFFER_SIZE - 4);
        assert_eq!(buffer.stop_byte_index, BUFFER_SIZE);
        let peek = buffer.peek()?;
        assert!(peek.len() >= MIN_PEEK_REQUIREMENT);
        assert_eq!(peek[0], 0x20);
        assert_eq!(peek[1], 0x20);
        assert_eq!(peek[2], 0x20);
        assert_eq!(peek[3], 0x20);
        assert_eq!(peek[4], 0xEF);
        assert_eq!(peek[5], 0xBB);
        assert_eq!(peek[6], 0xBF);
        assert_eq!(peek[7], 0x3C);
        Ok(())
    }

    #[test]
    fn test_peek() -> Result<(), Error> {
        // Input contains fewer bytes than the guaranteed minimum peek length.
        let bytes = [0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D];
        assert!(bytes.len() < MIN_PEEK_REQUIREMENT);
        let mut buffer = ByteBuffer::wrap(&bytes[..]);
        // There's nothing more to give, so the peek length will simply be
        // limited to the total input length.
        let peek = buffer.peek()?;
        assert_eq!(peek.len(), 7);
        assert_eq!(peek, &bytes);
        Ok(())
    }

    #[test]
    fn test_peek_after_read() -> Result<(), Error> {
        let bytes = [0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D];
        let mut buffer = ByteBuffer::wrap(&bytes[..]);
        // Skip past byte-order mark.
        buffer.read_next()?;
        buffer.read_next()?;
        buffer.read_next()?;
        // Peek will now only see the bytes after the byte-order mark.
        let peek = buffer.peek()?;
        assert_eq!(peek.len(), 4);
        assert_eq!(peek, &bytes[3..]);
        Ok(())
    }

    #[test]
    fn test_peek_minimum() -> Result<(), Error> {
        // Input contains more than the guaranteed minimum peek length.
        let bytes = [0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20];
        assert!(bytes.len() > MIN_PEEK_REQUIREMENT);
        let mut buffer = ByteBuffer::wrap(&bytes[..]);
        let peek = buffer.peek()?;
        // Peek may return more than the minimum, so we can only test for the minimum.
        assert!(peek.len() >= MIN_PEEK_REQUIREMENT);
        assert_eq!(
            &peek[0..MIN_PEEK_REQUIREMENT],
            &bytes[0..MIN_PEEK_REQUIREMENT]
        );
        Ok(())
    }

    #[test]
    fn test_peek_after_shunt() -> Result<(), Error> {
        // Input contains more than the guaranteed minimum peek length.
        let bytes = [
            0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
            0x6F, 0x6E, 0x3D, 0x22, 0x31, 0x2E, 0x30, 0x22,
        ];
        assert!(bytes.len() > MIN_PEEK_REQUIREMENT);
        let mut buffer = ByteBuffer::wrap(&bytes[..]);
        let initial_read_size = 8;
        for _ in 0..initial_read_size {
            buffer.read_next()?;
        }
        let previous_next_index = buffer.next_byte_index;
        let previous_stop_index = buffer.stop_byte_index;
        buffer.shunt_to_left();
        assert_eq!(buffer.next_byte_index, 0);
        assert_eq!(
            buffer.stop_byte_index,
            previous_stop_index - previous_next_index
        );
        let peek = buffer.peek()?;
        // Peek may return more than the minimum, so we can only test for the minimum.
        assert!(peek.len() >= MIN_PEEK_REQUIREMENT);
        assert_eq!(
            &peek[0..MIN_PEEK_REQUIREMENT],
            &bytes[initial_read_size..(MIN_PEEK_REQUIREMENT + initial_read_size)]
        );
        assert_eq!(buffer.read_next()?, Some(bytes[initial_read_size]));
        Ok(())
    }

    // Define a reader which will only ever return one byte at a time.
    struct SlowReader {
        content: Vec<u8>,
        next_index: usize,
    }

    impl SlowReader {
        fn new(content: Vec<u8>) -> Self {
            SlowReader {
                content,
                next_index: 0,
            }
        }
    }

    impl Read for SlowReader {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            if self.next_index == self.content.len() {
                Ok(0)
            } else {
                buf[0] = self.content[self.next_index];
                self.next_index += 1;
                Ok(1)
            }
        }
    }

    #[test]
    fn test_peek_slow_read() -> Result<(), Error> {
        // Input contains fewer bytes than the guaranteed minimum peek length.
        let bytes = vec![0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D];
        let slow_reader = SlowReader::new(bytes.clone());
        let mut buffer = ByteBuffer::wrap(slow_reader);
        // There's nothing more to give, so the peek length will simply be
        // limited to the total input length.
        let peek = buffer.peek()?;
        assert_eq!(peek.len(), 7);
        assert_eq!(peek, &bytes);
        Ok(())
    }

    #[test]
    fn test_peek_after_read_slow_read() -> Result<(), Error> {
        let bytes = vec![0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D];
        let slow_reader = SlowReader::new(bytes.clone());
        let mut buffer = ByteBuffer::wrap(slow_reader);
        // Skip past byte-order mark.
        buffer.read_next()?;
        buffer.read_next()?;
        buffer.read_next()?;
        // Peek will now only see the bytes after the byte-order mark.
        let peek = buffer.peek()?;
        assert_eq!(peek.len(), 4);
        assert_eq!(peek, &bytes[3..]);
        Ok(())
    }

    #[test]
    fn test_peek_minimum_slow_read() -> Result<(), Error> {
        // Input contains more than the guaranteed minimum peek length.
        let bytes = vec![0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20];
        let slow_reader = SlowReader::new(bytes.clone());
        let mut buffer = ByteBuffer::wrap(slow_reader);
        // Because SlowReader only returns one byte at a time, peek() will
        // stop as soon as it reaches the minimum requirement, so we can be sure
        // that the peek length will be exactly equal to the MIN_PEEK_REQUIREMENT.
        let peek = buffer.peek()?;
        assert_eq!(peek.len(), MIN_PEEK_REQUIREMENT);
        assert_eq!(peek, &bytes[0..MIN_PEEK_REQUIREMENT]);
        Ok(())
    }

    #[test]
    fn test_peek_after_shunt_slow_read() -> Result<(), Error> {
        // Input contains more than the guaranteed minimum peek length.
        let bytes = vec![
            0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
            0x6F, 0x6E, 0x3D, 0x22, 0x31, 0x2E, 0x30, 0x22,
        ];
        assert!(bytes.len() > MIN_PEEK_REQUIREMENT);
        let slow_reader = SlowReader::new(bytes.clone());
        let mut buffer = ByteBuffer::wrap(slow_reader);
        let initial_read_size = 8;
        for _ in 0..initial_read_size {
            buffer.read_next()?;
        }
        let previous_next_index = buffer.next_byte_index;
        let previous_stop_index = buffer.stop_byte_index;
        buffer.shunt_to_left();
        assert_eq!(buffer.next_byte_index, 0);
        assert_eq!(
            buffer.stop_byte_index,
            previous_stop_index - previous_next_index
        );
        let peek = buffer.peek()?;
        assert!(peek.len() == MIN_PEEK_REQUIREMENT);
        assert_eq!(
            &peek[0..MIN_PEEK_REQUIREMENT],
            &bytes[initial_read_size..(MIN_PEEK_REQUIREMENT + initial_read_size)]
        );
        assert_eq!(buffer.read_next()?, Some(bytes[initial_read_size]));
        Ok(())
    }

    #[test]
    fn test_read_next_slow_reader() -> Result<(), Error> {
        let bytes = vec![0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20];
        let slow_reader = SlowReader::new(bytes);
        let mut buffer = ByteBuffer::wrap(slow_reader);
        assert_eq!(buffer.read_next()?, Some(0xEF));
        assert_eq!(buffer.read_next()?, Some(0xBB));
        assert_eq!(buffer.read_next()?, Some(0xBF));
        assert_eq!(buffer.read_next()?, Some(0x3C));
        assert_eq!(buffer.read_next()?, Some(0x3F));
        assert_eq!(buffer.read_next()?, Some(0x78));
        assert_eq!(buffer.read_next()?, Some(0x6D));
        assert_eq!(buffer.read_next()?, Some(0x6C));
        assert_eq!(buffer.read_next()?, Some(0x20));
        assert_eq!(buffer.read_next()?, None);
        Ok(())
    }

    #[test]
    fn test_read_next_empty_input_slow_reader() -> Result<(), Error> {
        let bytes = vec![];
        let slow_reader = SlowReader::new(bytes);
        let mut buffer = ByteBuffer::wrap(slow_reader);
        assert_eq!(buffer.read_next()?, None);
        Ok(())
    }

    #[test]
    fn test_read_next_slow_reader_input_exceeds_buffer_size() -> Result<(), Error> {
        let start_of_xml_bytes: [u8; 22] = [
            0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
            0x6F, 0x6E, 0x3D, 0x22, 0x31, 0x2E, 0x30, 0x22,
        ];
        let mut bytes: Vec<u8> = Vec::with_capacity(BUFFER_SIZE + start_of_xml_bytes.len());
        bytes.resize(BUFFER_SIZE, 0x20);
        for b in start_of_xml_bytes {
            bytes.push(b);
        }
        let slow_reader = SlowReader::new(bytes);
        let mut buffer = ByteBuffer::wrap(slow_reader);
        for _ in 0..BUFFER_SIZE {
            assert_eq!(buffer.read_next()?, Some(0x20));
        }
        assert_eq!(buffer.read_next()?, Some(0xEF));
        assert_eq!(buffer.read_next()?, Some(0xBB));
        assert_eq!(buffer.read_next()?, Some(0xBF));
        assert_eq!(buffer.read_next()?, Some(0x3C));
        assert_eq!(buffer.read_next()?, Some(0x3F));
        assert_eq!(buffer.read_next()?, Some(0x78));
        assert_eq!(buffer.read_next()?, Some(0x6D));
        assert_eq!(buffer.read_next()?, Some(0x6C));
        assert_eq!(buffer.read_next()?, Some(0x20));
        assert_eq!(buffer.read_next()?, Some(0x76));
        assert_eq!(buffer.read_next()?, Some(0x65));
        assert_eq!(buffer.read_next()?, Some(0x72));
        assert_eq!(buffer.read_next()?, Some(0x73));
        assert_eq!(buffer.read_next()?, Some(0x69));
        assert_eq!(buffer.read_next()?, Some(0x6F));
        assert_eq!(buffer.read_next()?, Some(0x6E));
        assert_eq!(buffer.read_next()?, Some(0x3D));
        assert_eq!(buffer.read_next()?, Some(0x22));
        assert_eq!(buffer.read_next()?, Some(0x31));
        assert_eq!(buffer.read_next()?, Some(0x2E));
        assert_eq!(buffer.read_next()?, Some(0x30));
        assert_eq!(buffer.read_next()?, Some(0x22));
        assert_eq!(buffer.read_next()?, None);
        Ok(())
    }

    #[test]
    fn test_peek_slow_reader_input_exceeds_buffer_size() -> Result<(), Error> {
        let start_of_xml_bytes: [u8; 22] = [
            0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
            0x6F, 0x6E, 0x3D, 0x22, 0x31, 0x2E, 0x30, 0x22,
        ];
        let mut bytes: Vec<u8> = Vec::with_capacity(BUFFER_SIZE + start_of_xml_bytes.len());
        bytes.resize(BUFFER_SIZE, 0x20);
        for b in start_of_xml_bytes {
            bytes.push(b);
        }
        let slow_reader = SlowReader::new(bytes);
        let mut buffer = ByteBuffer::wrap(slow_reader);
        for _ in 0..(BUFFER_SIZE - 4) {
            assert_eq!(buffer.read_next()?, Some(0x20));
        }
        let peek = buffer.peek()?;
        assert_eq!(peek.len(), MIN_PEEK_REQUIREMENT);
        assert_eq!(peek[0], 0x20);
        assert_eq!(peek[1], 0x20);
        assert_eq!(peek[2], 0x20);
        assert_eq!(peek[3], 0x20);
        assert_eq!(peek[4], 0xEF);
        assert_eq!(peek[5], 0xBB);
        assert_eq!(peek[6], 0xBF);
        assert_eq!(peek[7], 0x3C);
        Ok(())
    }

    // Define a reader which will throw an Interrupted error before every successful (retry) read.
    struct DistractedReader {
        content: Vec<u8>,
        next_index: usize,
        next_read_will_be_interrupted: bool,
    }

    impl DistractedReader {
        fn new(content: Vec<u8>) -> Self {
            DistractedReader {
                content,
                next_index: 0,
                next_read_will_be_interrupted: true,
            }
        }
    }

    impl Read for DistractedReader {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            if self.next_read_will_be_interrupted {
                self.next_read_will_be_interrupted = false;
                return Err(Error::new(
                    std::io::ErrorKind::Interrupted,
                    "Deliberate interrupt for test purposes!",
                ));
            }
            self.next_read_will_be_interrupted = true;
            if self.next_index == self.content.len() {
                Ok(0)
            } else {
                let read_limit = buf.len().min(self.content.len() - self.next_index);
                buf[..read_limit].copy_from_slice(&self.content[self.next_index..][..read_limit]);
                // The above line is equivalent to the zip-iterator loop below.
                // for (dst, src) in std::iter::zip(buf, &self.content[self.next_index..]) {
                //     *dst = *src;
                // }
                // The above is also equivalent to the for-loop below.
                // for i in 0..read_limit {
                //     let byte = self.content[self.next_index + i];
                //     buf[i] = byte;
                // }
                self.next_index += read_limit;
                Ok(read_limit)
            }
        }
    }

    #[test]
    fn test_peek_distracted_read() -> Result<(), Error> {
        // Input contains fewer bytes than the guaranteed minimum peek length.
        let bytes = vec![0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D];
        let distracted_reader = DistractedReader::new(bytes.clone());
        let mut buffer = ByteBuffer::wrap(distracted_reader);
        // There's nothing more to give, so the peek length will simply be
        // limited to the total input length.
        let peek = buffer.peek()?;
        assert_eq!(peek.len(), 7);
        assert_eq!(peek, &bytes);
        Ok(())
    }

    #[test]
    fn test_peek_after_read_distracted_read() -> Result<(), Error> {
        let bytes = vec![0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D];
        let distracted_reader = DistractedReader::new(bytes);
        let mut buffer = ByteBuffer::wrap(distracted_reader);
        // Skip past byte-order mark.
        buffer.read_next()?;
        buffer.read_next()?;
        buffer.read_next()?;
        // Peek will now only see the bytes after the byte-order mark.
        let peek = buffer.peek()?;
        assert_eq!(peek.len(), 4);
        assert_eq!(peek, &vec![0x3C, 0x3F, 0x78, 0x6D]);
        Ok(())
    }

    #[test]
    fn test_peek_minimum_distracted_read() -> Result<(), Error> {
        // Input contains more than the guaranteed minimum peek length.
        let bytes = vec![0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20];
        let distracted_reader = DistractedReader::new(bytes.clone());
        let mut buffer = ByteBuffer::wrap(distracted_reader);
        let peek = buffer.peek()?;
        assert!(peek.len() >= MIN_PEEK_REQUIREMENT);
        assert_eq!(
            &peek[0..MIN_PEEK_REQUIREMENT],
            &bytes[0..MIN_PEEK_REQUIREMENT]
        );
        Ok(())
    }

    #[test]
    fn test_peek_after_shunt_distracted_read() -> Result<(), Error> {
        // Input contains more than the guaranteed minimum peek length.
        let bytes = vec![
            0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
            0x6F, 0x6E, 0x3D, 0x22, 0x31, 0x2E, 0x30, 0x22,
        ];
        assert!(bytes.len() > MIN_PEEK_REQUIREMENT);
        let distracted_reader = DistractedReader::new(bytes.clone());
        let mut buffer = ByteBuffer::wrap(distracted_reader);
        let initial_read_size = 8;
        for _ in 0..initial_read_size {
            buffer.read_next()?;
        }
        let previous_next_index = buffer.next_byte_index;
        let previous_stop_index = buffer.stop_byte_index;
        buffer.shunt_to_left();
        assert_eq!(buffer.next_byte_index, 0);
        assert_eq!(
            buffer.stop_byte_index,
            previous_stop_index - previous_next_index
        );
        let peek = buffer.peek()?;
        // Peek may return more than the minimum, so we can only test the minimum.
        assert!(peek.len() >= MIN_PEEK_REQUIREMENT);
        assert_eq!(
            &peek[0..MIN_PEEK_REQUIREMENT],
            &bytes[initial_read_size..(MIN_PEEK_REQUIREMENT + initial_read_size)]
        );
        assert_eq!(buffer.read_next()?, Some(bytes[initial_read_size]));
        Ok(())
    }

    #[test]
    fn test_read_next_distracted_reader() -> Result<(), Error> {
        let bytes = vec![0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20];
        let distracted_reader = DistractedReader::new(bytes);
        let mut buffer = ByteBuffer::wrap(distracted_reader);
        assert_eq!(buffer.read_next()?, Some(0xEF));
        assert_eq!(buffer.read_next()?, Some(0xBB));
        assert_eq!(buffer.read_next()?, Some(0xBF));
        assert_eq!(buffer.read_next()?, Some(0x3C));
        assert_eq!(buffer.read_next()?, Some(0x3F));
        assert_eq!(buffer.read_next()?, Some(0x78));
        assert_eq!(buffer.read_next()?, Some(0x6D));
        assert_eq!(buffer.read_next()?, Some(0x6C));
        assert_eq!(buffer.read_next()?, Some(0x20));
        assert_eq!(buffer.read_next()?, None);
        Ok(())
    }

    #[test]
    fn test_read_next_empty_input_distracted_reader() -> Result<(), Error> {
        let bytes = vec![];
        let distracted_reader = DistractedReader::new(bytes);
        let mut buffer = ByteBuffer::wrap(distracted_reader);
        assert_eq!(buffer.read_next()?, None);
        Ok(())
    }

    #[test]
    fn test_read_next_distracted_reader_input_exceeds_buffer_size() -> Result<(), Error> {
        let start_of_xml_bytes: [u8; 22] = [
            0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
            0x6F, 0x6E, 0x3D, 0x22, 0x31, 0x2E, 0x30, 0x22,
        ];
        let mut bytes: Vec<u8> = Vec::with_capacity(BUFFER_SIZE + start_of_xml_bytes.len());
        bytes.resize(BUFFER_SIZE, 0x20);
        for b in start_of_xml_bytes {
            bytes.push(b);
        }
        let distracted_reader = DistractedReader::new(bytes);
        let mut buffer = ByteBuffer::wrap(distracted_reader);
        for _ in 0..BUFFER_SIZE {
            assert_eq!(buffer.read_next()?, Some(0x20));
        }
        assert_eq!(buffer.read_next()?, Some(0xEF));
        assert_eq!(buffer.read_next()?, Some(0xBB));
        assert_eq!(buffer.read_next()?, Some(0xBF));
        assert_eq!(buffer.read_next()?, Some(0x3C));
        assert_eq!(buffer.read_next()?, Some(0x3F));
        assert_eq!(buffer.read_next()?, Some(0x78));
        assert_eq!(buffer.read_next()?, Some(0x6D));
        assert_eq!(buffer.read_next()?, Some(0x6C));
        assert_eq!(buffer.read_next()?, Some(0x20));
        assert_eq!(buffer.read_next()?, Some(0x76));
        assert_eq!(buffer.read_next()?, Some(0x65));
        assert_eq!(buffer.read_next()?, Some(0x72));
        assert_eq!(buffer.read_next()?, Some(0x73));
        assert_eq!(buffer.read_next()?, Some(0x69));
        assert_eq!(buffer.read_next()?, Some(0x6F));
        assert_eq!(buffer.read_next()?, Some(0x6E));
        assert_eq!(buffer.read_next()?, Some(0x3D));
        assert_eq!(buffer.read_next()?, Some(0x22));
        assert_eq!(buffer.read_next()?, Some(0x31));
        assert_eq!(buffer.read_next()?, Some(0x2E));
        assert_eq!(buffer.read_next()?, Some(0x30));
        assert_eq!(buffer.read_next()?, Some(0x22));
        assert_eq!(buffer.read_next()?, None);
        Ok(())
    }

    #[test]
    fn test_peek_distracted_reader_input_exceeds_buffer_size() -> Result<(), Error> {
        let start_of_xml_bytes: [u8; 22] = [
            0xEF, 0xBB, 0xBF, 0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
            0x6F, 0x6E, 0x3D, 0x22, 0x31, 0x2E, 0x30, 0x22,
        ];
        let mut bytes: Vec<u8> = Vec::with_capacity(BUFFER_SIZE + start_of_xml_bytes.len());
        bytes.resize(BUFFER_SIZE, 0x20);
        for b in start_of_xml_bytes {
            bytes.push(b);
        }
        let distracted_reader = DistractedReader::new(bytes);
        let mut buffer = ByteBuffer::wrap(distracted_reader);
        for _ in 0..(BUFFER_SIZE - 4) {
            assert_eq!(buffer.read_next()?, Some(0x20));
        }
        // These index assertions rely on slice reading being greedy.
        assert_eq!(buffer.next_byte_index, BUFFER_SIZE - 4);
        assert_eq!(buffer.stop_byte_index, BUFFER_SIZE);
        let peek = buffer.peek()?;
        assert!(peek.len() >= MIN_PEEK_REQUIREMENT);
        assert_eq!(peek[0], 0x20);
        assert_eq!(peek[1], 0x20);
        assert_eq!(peek[2], 0x20);
        assert_eq!(peek[3], 0x20);
        assert_eq!(peek[4], 0xEF);
        assert_eq!(peek[5], 0xBB);
        assert_eq!(peek[6], 0xBF);
        assert_eq!(peek[7], 0x3C);
        Ok(())
    }
}