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
use crate::prelude::*;

/// Create a string [`Reader`] from a string.
pub fn reader(s: &str) -> Reader<'_> {
    Reader(s)
}

/// Create an empty string [`Writer`].
pub fn writer() -> Writer {
    Writer(String::new())
}

/// A reader for reading from a string (`&str`).
///
/// Implements the `Read` trait, so this is a way to integrate strings into ezio's trait system.
/// Primarily designed for testing and other experimentation where proper IO is mocked with string
/// data.
#[derive(Clone, Debug)]
pub struct Reader<'a>(&'a str);

/// A writer for writing into a string (`String`).
///
/// Implements the `Write` trait, so this is a way to integrate strings into ezio's trait system.
/// Primarily designed for testing and other experimentation where proper IO is mocked with string
/// data.
///
/// To access the written string data, convert into a `String` using `into()`, or get a reference
/// using `as_ref()`.
#[derive(Clone, Debug)]
pub struct Writer(String);

impl Into<String> for Writer {
    fn into(self) -> String {
        self.0
    }
}

impl AsRef<str> for Writer {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Write for Writer {
    fn write(&mut self, s: &str) {
        self.0.push_str(s);
    }
}

impl std::io::Write for Writer {
    fn write(&mut self, b: &[u8]) -> Result<usize, std::io::Error> {
        let s = std::str::from_utf8(b).expect("Tried to write non-utf8 bytes to a string");
        self.0.push_str(s);
        Ok(b.len())
    }

    fn flush(&mut self) -> Result<(), std::io::Error> {
        Ok(())
    }
}

impl<'a> From<&'a str> for Reader<'a> {
    fn from(s: &'a str) -> Reader<'a> {
        Reader(s)
    }
}

impl<'a> Read for Reader<'a> {
    fn read_all(&mut self) -> String {
        self.0.to_owned()
    }

    fn read_line(&mut self) -> String {
        let (line, rest) = match self.0.find('\n') {
            Some(n) => {
                let (line, rest) = self.0.split_at(n);
                (line, &rest[1..])
            }
            None => (self.0, ""),
        };

        self.0 = rest;
        line.to_owned()
    }
}

impl<'a> std::io::Read for Reader<'a> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let len = std::cmp::min(self.0.len(), buf.len());
        let bytes = &self.0.as_bytes()[..len];
        buf.copy_from_slice(bytes);
        Ok(len)
    }
}

/// An iterator for reading lines from a string [`Reader`].
pub struct StrIterReader<'a>(std::str::Lines<'a>);

impl<'a> IntoIterator for Reader<'a> {
    type Item = String;
    type IntoIter = StrIterReader<'a>;

    fn into_iter(self) -> Self::IntoIter {
        StrIterReader(self.0.lines())
    }
}

impl<'a> Iterator for StrIterReader<'a> {
    // We could return &'a str, but we use String for consistency with the rest of the crate.
    type Item = String;

    fn next(&mut self) -> Option<String> {
        self.0.next().map(|s| s.to_owned())
    }
}

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

    #[test]
    fn str_write() {
        let mut writer = writer();
        writer.write("Hello, ");
        writer.write("world!");
        assert_eq!(writer.as_ref(), "Hello, world!");
    }

    #[test]
    fn str_write_any() {
        let mut writer = writer();
        writer.write_any("Hello ");
        writer.write_any(42);
        writer.write_any(String::new());
        assert_eq!(writer.as_ref(), "Hello 42");
    }

    #[test]
    fn str_read() {
        let mut reader = reader("line 1\n line 2");
        assert_eq!(reader.read_all(), "line 1\n line 2");
        assert_eq!(reader.read_line(), "line 1");
        assert_eq!(reader.read_line(), " line 2");

        let mut reader: Reader = "".into();
        assert_eq!(reader.read_line(), "");
    }

    #[test]
    fn str_read_any() {
        let mut reader = reader("line 1\n42\n3.14");
        assert_eq!(&reader.read_line_any::<String>(), "line 1");
        assert_eq!(reader.read_line_any::<u8>(), 42);
        assert_eq!(reader.read_line_any::<f64>(), 3.14);
    }

    #[test]
    fn str_iter() {
        let reader = reader("line 0\nline 1");
        for (i, line) in reader.into_iter().enumerate() {
            assert_eq!(line, format!("line {}", i));
        }
    }
}