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
extern crate alloc;
use std::io::{Read, Write};
use alloc::vec::Vec;
use alloc::string::String;

pub struct IO {
    pub in_buffer: Vec<u8>,
    pub out_buffer: Vec<u8>,
}
impl IO {
    pub fn write(&mut self, data: &[u8]) {
        self.out_buffer.extend_from_slice(data);
    }
    pub fn read(&mut self, size: usize) -> Vec<u8> {
        let mut data = Vec::new();
        for _ in 0..size {
            data.push(self.in_buffer.remove(0));
        }
        data
    }
    pub fn read_until(&mut self, delim: u8) -> Vec<u8> {
        let mut data = Vec::new();
        loop {
            let byte = self.in_buffer.remove(0);
            if byte == delim {
                break;
            }
            data.push(byte);
        }
        data
    }
    pub fn read_line(&mut self) -> String {
        let mut data = String::new();
        loop {
            let byte = self.in_buffer.remove(0);
            if byte == b'\n' {
                break;
            }
            data.push(byte as char);
        }
        data
    }
    pub fn flush(&mut self) {
        //write to stdout then clear
        std::io::stdout().write_all(&self.out_buffer).unwrap();
        self.out_buffer.clear();
    }
}

impl Default for IO {
    fn default() -> Self {
        Self {
            in_buffer: Vec::new(),
            out_buffer: Vec::new(),
        }
    }
}