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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
//! ## vga-rs
//! Low level VGA(0xB8000) library in freestanding Rust.
//!
//! ## Example
//! ```rust
//! #![no_std]
//! extern crate vga_rs;
//! use vga_rs::*;
//! extern crate cursor_rs;
//!
//! fn reset_screen() {
//! 	let buffer_slice=VgaBuffer::new().as_mut_slice(); // No error because lifetime of slice is free from VgaBuffer.
//! 	for vchar_ref in buffer_slice.iter_mut()
//! 	{
//!			let vchar = vchar_ref.get_volatile();
//! 		vchar_ref.set_volatile(vchar & 0xff00);
//! 	}
//!     cursor_rs::set_cursor(0,0);
//! }
//! ```

#![no_std]

extern crate vgainfo_rs;

/// Contains 8 bit color.
#[repr(transparent)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Color(u8);

impl Color {
    pub const BLACK: Color = Color(0u8);
    pub const BLUE: Color = Color(1);
    pub const GREEN: Color = Color(2);
    pub const CYAN: Color = Color(3);
    pub const RED: Color = Color(4);
    pub const MAGENTA: Color = Color(5);
    pub const BROWN: Color = Color(6);
    pub const LIGHTGRAY: Color = Color(7);
    pub const DARKGRAY: Color = Color(8);
    pub const LIGHTBLUE: Color = Color(9);
    pub const LIGHTGREEN: Color = Color(10);
    pub const LIGHTCYAN: Color = Color(11);
    pub const LIGHTRED: Color = Color(12);
    pub const PINK: Color = Color(13);
    pub const YELLOW: Color = Color(14);
    pub const WHITE: Color = Color(15);

    pub const EXTRA: Color = Color(1u8 << 3);
}

impl Color {
    /// Construct Color from (blue | green | red | extra bit).
    pub const fn new(b: bool, g: bool, r: bool, extra: bool) -> Self {
        Self(
            if b { 1u8 << 0 } else { 0u8 }
                | if g { 1u8 << 1 } else { 0u8 }
                | if r { 1u8 << 2 } else { 0u8 }
                | if extra { 1u8 << 3 } else { 0u8 },
        )
    }

    /// Construct Color from u8.
    #[inline]
    pub const fn from_u8(bit: u8) -> Self {
        Self(bit)
    }

    /// Construct Color from u8. Check bit 4-7.
    pub const fn from_u8_checked(bit: u8) -> Option<Self> {
        match bit & 0xf0 {
            0u8 => Some(Self(bit)),
            _ => None,
        }
    }

    /// Extract Color to u8.
    #[inline]
    pub const fn as_u8(self) -> u8 {
        let Self(x) = self;
        x
    }
}

use core::ops::BitOr;
impl BitOr for Color {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        let (Self(a), Self(b)) = (self, rhs);
        Self(a | b)
    }
}

/// Contains foreground and background colors.
#[repr(C, packed)]
#[derive(Debug, Copy, Clone)]
pub struct Attribute {
    pub fgcolor: Color,
    pub bgcolor: Color,
}

impl Attribute {
    /// Construct an Attribute.
    #[inline]
    pub const fn new(fgcolor: Color, bgcolor: Color) -> Self {
        Self {
            fgcolor: fgcolor,
            bgcolor: bgcolor,
        }
    }

    /// Construct an Attribute from u8.
    #[inline]
    pub const fn from_u8(bit: u8) -> Self {
        Self {
            fgcolor: Color::from_u8(bit & 0x0f),
            bgcolor: Color::from_u8((bit & 0xf0) >> 4),
        }
    }

    /// Extract Attribute to u8.
    #[inline]
    pub const fn as_u8(self) -> u8 {
        self.fgcolor.as_u8() | (self.bgcolor.as_u8() << 4)
    }
}

/// An element of video buffer, contains codepoint and attribute.
#[repr(C, packed)]
#[derive(Debug, Copy, Clone)]
pub struct VgaChar {
    pub codepoint: u8,
    pub attribute: u8,
}

impl VgaChar {
    /// Construct a VgaChar.
    #[inline]
    pub const fn new(cp: u8, attr: Attribute) -> Self {
        Self {
            codepoint: cp,
            attribute: attr.as_u8(),
        }
    }

    /// Get a VgaChar and suppress optimization. In case ```self``` is on video buffer.
    /// ```rust
    /// let nonnull:NonNull::<VgaChar> = unsafe { NonNull::new_unchecked(VGA_PTR) };
    /// let vchar = nonnull.as_ref().get_volatile();
    /// ```
    pub fn get_volatile(&self) -> Self {
        let ptr = self as *const Self;
        let Self {
            codepoint,
            attribute,
        } = unsafe { ptr.read_volatile() };

        Self::new(codepoint, Attribute::from_u8(attribute))
    }

    /// Set a VgaChar and suppress optimization. In case ```self``` is on video buffer.
    /// ```rust
    /// let mut nonnull:NonNull::<VgaChar> = unsafe { NonNull::new_unchecked(VGA_PTR) };
    /// let vchar = nonnull.as_ref().get_volatile();
    /// nonnull.as_mut().get_volatile(vchar & 0xff00);
    /// ```
    pub fn set_volatile(&mut self, other: Self) {
        let ptr = self as *mut Self;
        {
            unsafe {
                ptr.write_volatile(other);
            }
        };
    }
}

use core::ptr::NonNull;

/// Containa a pointer to slice of Vga buffer.
#[derive(Debug, Copy, Clone)]
pub struct VgaBuffer {
    pointer: NonNull<[VgaChar]>,
}

impl VgaBuffer {
    pub const VGA_ADDR: usize = vgainfo_rs::VGA_ADDR;

    pub const WIDTH: usize = vgainfo_rs::WIDTH;
    pub const HIGH: usize = vgainfo_rs::HIGH;
    pub const LENGTH: usize = vgainfo_rs::LENGTH;

    pub const VGA_PTR: *mut VgaChar = Self::VGA_ADDR as *mut _;

    /// This static methode converts 2D index to 1D index.
    #[inline]
    pub const fn to_index(y: usize, x: usize) -> usize {
        y * Self::WIDTH + x
    }

    /// This static methode converts 1D index to 2D index.
    #[inline]
    pub const fn to_yx(index: usize) -> (usize, usize) {
        let y = index / Self::WIDTH;
        let x = index % Self::WIDTH;
        (y, x)
    }

    /// Construct a VgaBuffer.
    #[inline]
    pub fn new() -> Self {
        let nonnull = unsafe { NonNull::new_unchecked(Self::VGA_PTR) };
        Self {
            pointer: NonNull::slice_from_raw_parts(nonnull, Self::LENGTH),
        }
    }

    /// Set VgaChar to (y,x) coordinates. Uncheck range.
    pub unsafe fn set_vgachar(&mut self, vchar: VgaChar, y: usize, x: usize) {
        let index = Self::to_index(y, x);
        self.pointer
            .as_mut()
            .get_unchecked_mut(index)
            .set_volatile(vchar);
    }

    /// Get VgaChar at (y,x) coordinates. Uncheck range.
    pub unsafe fn get_vgachar(&self, y: usize, x: usize) -> VgaChar {
        let index = Self::to_index(y, x);
        self.pointer.as_ref().get_unchecked(index).get_volatile()
    }

    /// Video buffer to a slice.
    #[inline]
    pub fn as_slice<'a>(&self) -> &'a [VgaChar] {
        unsafe { self.pointer.as_ref() }
    }

    /// Video buffer to a mutable slice.
    /// ```rust
    /// let buffer_slice=VgaBuffer::new().as_mut_slice(); // No error because lifetime of slice is free from VgaBuffer.
    /// for vchar_ref in buffer.iter_mut()
    /// {
    ///		let vchar = vchar_ref.get_volatile();
    /// 	vchar_ref.set_volatile(vchar & 0xff00);
    /// }
    /// ```
    #[inline]
    pub fn as_mut_slice<'a>(&mut self) -> &'a mut [VgaChar] {
        unsafe { self.pointer.as_mut() }
    }
}

/// Getter and Setter interface.
pub trait VgaBufferHal {
    type Item;

    /// Setter interface.
    fn set(&mut self, item: Self::Item, y: usize, x: usize);

    /// Getter interface.
    fn get(&self, y: usize, x: usize) -> Self::Item;
}

impl VgaBufferHal for VgaBuffer {
    type Item = VgaChar;

    #[inline]
    fn set(&mut self, item: Self::Item, y: usize, x: usize) {
        unsafe { self.set_vgachar(item, y, x) };
    }

    #[inline]
    fn get(&self, y: usize, x: usize) -> Self::Item {
        unsafe { self.get_vgachar(y, x) }
    }
}