aboutsummaryrefslogtreecommitdiff
path: root/src/arch/x86/common/io/writer.rs
blob: 73616932794cf5331f9fdc774244114691038b4f (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use core::fmt;
use core::fmt::Write;
use lazy_static::lazy_static;
use spin::Mutex;

#[doc(hidden)]
pub fn _print(args: fmt::Arguments) {
    WRITER.lock().write_fmt(args).unwrap();
}

lazy_static! {
    pub static ref WRITER: Mutex<Writer> = Mutex::new(Writer::new());
}

#[derive(Default)]
pub struct Writer {
    max_y: isize,
    max_x: isize,
    x: isize,
    y: isize,
    addr: u32,
}

impl Writer {
    pub fn new() -> Self {
        Self {
            x: 0,
            y: 0,
            max_y: 25,
            max_x: 80,
            addr: 0xb8000,
        }
    }

    pub fn write(&mut self, c: char, b: u8) {
        let off: isize = self.y * self.max_x + self.x;
        let vga_buffer = self.addr as *mut u8;

        if c != '\n' {
            unsafe {
                *vga_buffer.offset(2 * off) = c as u8;
                *vga_buffer.offset(2 * off + 1) = b;
            }
            self.x += 1;
        } else {
            self.x = 0;
            self.y += 1;
        }

        if self.x >= self.max_x {
            self.x = 0;
            self.y += 1;
        }

        if self.y >= self.max_y {
            self.y = 0;
        }
    }

    pub fn print(&mut self, s: &str, b: u8) {
        for i in s.chars() {
            self.write(i, b);
        }
    }
}

impl fmt::Write for Writer {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.print(s, 0xb);
        Ok(())
    }
}