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
//! This module contains the `ByteIterator` struct, which is used to iterate
//! over the bytes of a file. This allows us to read a file byte by byte,
//! instead of reading the entire file into memory at once.

use std::{
    fs::File,
    io::{self, BufReader, Read},
};

/// Verifies that the first character of the file is a '['.
///
/// # Arguments
///
/// * `first_char` - The first character of the file.
///
/// # Panics
///
/// * If the first character of the file is not a '['.
///
/// # Examples
///
/// ```
/// use jsonl_converter::reader::verify_first_char;
///
/// let first_char = '[';
/// verify_first_char(&first_char);
/// ```
pub fn verify_first_char(first_char: &char) {
    if first_char != &'[' {
        panic!(
            "The first character of the file must be a '[', not a '{}'.",
            first_char
        );
    }
}

/// This struct is used to iterate over the bytes of a file.
///
///
/// # Fields
///
/// * `reader` - A `BufReader` that reads the file.
pub struct ByteIterator {
    reader: BufReader<File>,
}

impl ByteIterator {
    /// Creates a new `ByteIterator` from a file.
    /// 
    /// # Arguments
    /// 
    /// * `filename` - The name of the file.
    /// 
    /// # Errors
    /// 
    /// * If the file cannot be opened.
    pub fn new(filename: &str) -> io::Result<Self> {
        let file = File::open(filename)?;
        let reader = BufReader::new(file);
        Ok(Self { reader })
    }

    /// Returns the next character of the file.
    pub fn next_char(&mut self) -> Option<char> {
        self.next().unwrap().unwrap().chars().next()
    }
}

impl Iterator for ByteIterator {
    type Item = io::Result<String>;

    /// Returns the next byte of the file.
    fn next(&mut self) -> Option<Self::Item> {
        let mut buffer = [0; 1];
        match self.reader.read_exact(&mut buffer) {
            Ok(_) => Some(Ok(String::from_utf8_lossy(&buffer).into_owned())),
            Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => None,
            Err(error) => Some(Err(error)),
        }
    }
}

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

    #[test]
    fn test_bytes_iterator_new_instance_accepts_valid_filename() {
        let bytes_iter = ByteIterator::new("src/reader.rs");
        assert!(bytes_iter.is_ok());
    }

    #[test]
    #[should_panic]
    fn test_bytes_iterator_new_instance_panics_on_invalid_filename() {
        let bytes_iter = ByteIterator::new("bad_filename");
        assert!(bytes_iter.is_ok());
    }

    #[test]
    fn test_can_iterate_over_bytes() {
        let bytes_iter = ByteIterator::new("src/reader.rs").unwrap();
        let mut bytes = String::new();

        for byte in bytes_iter {
            bytes.push_str(&byte.unwrap());
        }

        assert_eq!(bytes, include_str!("reader.rs"));
    }

    #[test]
    fn test_verify_first_char_passes() {
        verify_first_char(&'[');
    }

    #[test]
    #[should_panic]
    fn test_verify_first_char_panics_on_invalid_first_char() {
        verify_first_char(&'a');
    }
}