topheman / snake-pipe-rust

πŸ¦€ A snake game based on stdin/stdout (+tcp and unix sockets) in rust
MIT License
12 stars 1 forks source link

Remove `.unwrap` from Stream::new #10

Closed topheman closed 8 months ago

topheman commented 8 months ago

See implementation of Stream::new: https://github.com/topheman/snake-pipe-rust/blob/master/src/stream.rs

It's not a big problem since there should always be a first line that contains the InitOptions in the stream.

However, the code example fails cargo test πŸ₯²

impl Stream {
    /// Creates a stream from a buffer (could be from [`std::io::stdin()`]`.line()`)
    pub fn new<T: BufRead + 'static>(
        mut lines: Lines<T>,
    ) -> Result<Stream, Box<dyn std::error::Error>> {
        let first_line = lines.next().unwrap()?; // πŸ‘ˆ
        let options: InitOptions = serde_json::from_str(&first_line)?;
        // flat_map keeps Some and extracts their values while removing Err - we ignore parse errors on lines / we dont panic on it
        let parsed_lines = lines.flat_map(|result_line| match result_line {
            Ok(line) => match serde_json::from_str::<Game>(&line) {
                Ok(parsed_line) => Some(parsed_line),
                Err(_) => None,
            },
            Err(_) => None,
        });
        Ok(Self {
            options,
            lines: Box::new(parsed_lines),
        })
    }
}