|
| 1 | +#[allow(dead_code)] |
| 2 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 3 | +#[repr(u8)] //each enum variant would be stored as a u8. |
| 4 | +pub enum Color { |
| 5 | + Black = 0, |
| 6 | + Blue = 1, |
| 7 | + Green = 2, |
| 8 | + Cyan = 3, |
| 9 | + Red = 4, |
| 10 | + Magenta = 5, |
| 11 | + Brown = 6, |
| 12 | + LightGray = 7, |
| 13 | + DarkGray = 8, |
| 14 | + LightBlue = 9, |
| 15 | + LightGreen = 10, |
| 16 | + LightCyan = 11, |
| 17 | + LightRed = 12, |
| 18 | + Pink = 13, |
| 19 | + Yellow = 14, |
| 20 | + White = 15, |
| 21 | +} |
| 22 | + |
| 23 | +#[derive(Copy, Clone, Debug, PartialEq, Eq)] |
| 24 | +#[repr(transparent)] |
| 25 | +struct ColorCode(u8); |
| 26 | + |
| 27 | +impl ColorCode { |
| 28 | + fn new(foreground: Color, background: Color) -> ColorCode { |
| 29 | + ColorCode((background as u8) << 4 | (foreground as u8)) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 34 | +#[repr(C)] |
| 35 | +struct ScreenChar { |
| 36 | + ascii_character: u8, |
| 37 | + color_code: ColorCode, |
| 38 | +} |
| 39 | + |
| 40 | +const BUFFER_HEIGHT: usize = 25; |
| 41 | +const BUFFER_WIDTH: usize = 80; |
| 42 | + |
| 43 | +#[repr(transparent)] |
| 44 | +struct Buffer { |
| 45 | + chars: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT], |
| 46 | +} |
| 47 | + |
| 48 | +pub struct Writer { |
| 49 | + column_position: usize, |
| 50 | + color_code: ColorCode, |
| 51 | + buffer: &'static mut Buffer, |
| 52 | +} |
| 53 | + |
| 54 | +impl Writer { |
| 55 | + pub fn write_byte(&mut self, byte: u8) { |
| 56 | + match byte { |
| 57 | + b'\n' => self.new_line(), |
| 58 | + byte => { |
| 59 | + if self.column_position >= BUFFER_WIDTH { |
| 60 | + self.new_line() |
| 61 | + } |
| 62 | + let row = BUFFER_HEIGHT - 1; |
| 63 | + let col = self.column_position; |
| 64 | + let color_code = self.color_code; |
| 65 | + |
| 66 | + self.buffer.chars[row][col] = ScreenChar { |
| 67 | + ascii_character: byte, |
| 68 | + color_code, |
| 69 | + }; |
| 70 | + self.column_position += 1; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + fn new_line(&mut self) {} |
| 75 | +} |
| 76 | + |
| 77 | +impl Writer { |
| 78 | + pub fn write_string(&mut self, s: &str) { |
| 79 | + for byte in s.bytes() { |
| 80 | + match byte { |
| 81 | + // printable ASCII byte or newline |
| 82 | + 0x20..=0x7e | b'\n' => self.write_byte(byte), |
| 83 | + // not part of printable ASCII range |
| 84 | + _ => self.write_byte(0xfe) |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +pub fn print_something() { |
| 91 | + let mut writer = Writer { |
| 92 | + column_position: 0, |
| 93 | + color_code: ColorCode::new(Color::Yellow, Color::Black), |
| 94 | + buffer: unsafe { &mut *(0xb8000 as *mut Buffer) }, |
| 95 | + }; |
| 96 | + writer.write_byte(b'H'); |
| 97 | + writer.write_string("ello "); |
| 98 | + writer.write_string("Wörld!"); |
| 99 | +} |
0 commit comments