rust/rhg/src/ui.rs
changeset 45050 513b3ef277a3
child 45382 eb55274d3650
equal deleted inserted replaced
45049:dd3050227a84 45050:513b3ef277a3
       
     1 use std::io;
       
     2 use std::io::Write;
       
     3 
       
     4 pub struct Ui {}
       
     5 
       
     6 /// The kind of user interface error
       
     7 pub enum UiError {
       
     8     /// The standard output stream cannot be written to
       
     9     StdoutError(io::Error),
       
    10     /// The standard error stream cannot be written to
       
    11     StderrError(io::Error),
       
    12 }
       
    13 
       
    14 /// The commandline user interface
       
    15 impl Ui {
       
    16     pub fn new() -> Self {
       
    17         Ui {}
       
    18     }
       
    19 
       
    20     /// Write bytes to stdout
       
    21     pub fn write_stdout(&self, bytes: &[u8]) -> Result<(), UiError> {
       
    22         let mut stdout = io::stdout();
       
    23 
       
    24         self.write_stream(&mut stdout, bytes)
       
    25             .or_else(|e| self.into_stdout_error(e))?;
       
    26 
       
    27         stdout.flush().or_else(|e| self.into_stdout_error(e))
       
    28     }
       
    29 
       
    30     fn into_stdout_error(&self, error: io::Error) -> Result<(), UiError> {
       
    31         self.write_stderr(
       
    32             &[b"abort: ", error.to_string().as_bytes(), b"\n"].concat(),
       
    33         )?;
       
    34         Err(UiError::StdoutError(error))
       
    35     }
       
    36 
       
    37     /// Write bytes to stderr
       
    38     pub fn write_stderr(&self, bytes: &[u8]) -> Result<(), UiError> {
       
    39         let mut stderr = io::stderr();
       
    40 
       
    41         self.write_stream(&mut stderr, bytes)
       
    42             .or_else(|e| Err(UiError::StderrError(e)))?;
       
    43 
       
    44         stderr.flush().or_else(|e| Err(UiError::StderrError(e)))
       
    45     }
       
    46 
       
    47     fn write_stream(
       
    48         &self,
       
    49         stream: &mut impl Write,
       
    50         bytes: &[u8],
       
    51     ) -> Result<(), io::Error> {
       
    52         stream.write_all(bytes)
       
    53     }
       
    54 }