summaryrefslogblamecommitdiff
path: root/src/devices/stream.rs
blob: 532df580e1fdccef4483cc569b5cf246508c6385 (plain) (tree)
1
2
3
4
5
6
7
8
9

                                    




                             
 
                                  







                                 
 
                                                      

         


                                     

                                           


                                                  
                                






                                               

                            
                           
     
use std::io::{Read, Write};
use std::io::{BufReader, BufWriter};
use std::io::{Stdin, Stdout};

pub struct StreamDevice {
    pub wake_flag: bool,

    pub input_control: bool,
    pub output_control: bool,

    pub stdin: BufReader<Stdin>,
    pub stdout: BufWriter<Stdout>,
}

impl StreamDevice {
    pub fn new() -> Self {
        Self {
            wake_flag: false,

            input_control: true,
            output_control: true,

            stdin: BufReader::new(std::io::stdin()),
            stdout: BufWriter::new(std::io::stdout()),
        }
    }

    pub fn flush_local(&mut self) {
        self.stdout.flush().unwrap();
    }

    pub fn read_queue_len(&self) -> usize {
        self.stdin.buffer().len()
    }

    pub fn read_stdin(&mut self) -> u8 {
        let mut buffer = [0; 1];
        match self.stdin.read_exact(&mut buffer) {
            Ok(_)  => buffer[0],
            Err(_) => 0,
        }
    }

    pub fn write_stdout(&mut self, val: u8) {
        self.stdout.write_all(&[val]).unwrap();
    }
}

impl Drop for StreamDevice {
    fn drop(&mut self) {
        self.flush_local();
    }
}