Skip to main content

ispell/
async_reader.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with
3// this file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use std::process::ChildStdout;
6use std::io::{BufReader, BufRead};
7use std::sync::mpsc::Sender;
8
9use error::Result;
10
11
12/// An asynchronous reader, that reads from a spawned command stdout
13/// and sends it to a channel
14pub struct AsyncReader {
15    stdout: BufReader<ChildStdout>,
16    sender: Sender<Result<String>>,
17}
18
19impl AsyncReader {
20    /// Create a new AsyncReader
21    pub fn new(stdout: ChildStdout, sender: Sender<Result<String>>) -> AsyncReader {
22        AsyncReader {
23            stdout: BufReader::new(stdout),
24            sender: sender,
25        }
26    }
27
28    /// Reads the output from ispell and sends it over the channel
29    pub fn read_loop(&mut self) {
30        loop {
31            let result = self.read();
32            match self.sender.send(result) {
33                Ok(_) => (),
34                Err(_) => break, // main process was aborted
35            }
36        }
37    }
38
39    /// Reads a string
40    fn read(&mut self) -> Result<String> {
41        let mut output = String::new();
42        loop {
43            self.stdout.read_line(&mut output)?;
44            if output.ends_with("\n\n") || output == "\n" || output.starts_with("@") {
45                break;
46            }
47        }
48        Ok(output)
49    }
50}
51