]> patrickod personal git archive - keywing-rs.git/blob - keywing/src/buffer.rs
Not exactly initial commit
[keywing-rs.git] / keywing / src / buffer.rs
1 use embedded_graphics::{
2     drawable::Pixel,
3     geometry::{Point, Size},
4     pixelcolor::{
5         raw::{RawData, RawU16},
6         Rgb565,
7     },
8     primitives::Rectangle,
9     style::{PrimitiveStyle, Styled},
10     DrawTarget,
11 };
12
13 pub struct FrameBuffer<'a> {
14     buf: &'a mut [[u16; 320]; 240],
15 }
16
17 impl<'a> FrameBuffer<'a> {
18     pub fn new(raw: &'a mut [[u16; 320]; 240]) -> Self {
19         Self {
20             buf: raw
21         }
22     }
23
24     pub fn inner(&self) -> &[u16] {
25         unsafe {
26             core::slice::from_raw_parts(self.buf.as_ptr().cast::<u16>(), (self.width() * self.height()) as usize)
27         }
28     }
29
30     fn width(&self) -> u32 {
31         self.buf.len() as u32
32     }
33
34     fn height(&self) -> u32 {
35         self.buf[0].len() as u32
36     }
37 }
38
39 impl<'a> DrawTarget<Rgb565> for FrameBuffer<'a>
40 {
41     type Error = ();
42
43     fn size(&self) -> Size {
44         Size::new(self.width(), self.height())
45     }
46
47     fn draw_pixel(&mut self, pixel: Pixel<Rgb565>) -> Result<(), Self::Error> {
48         let Pixel(pos, color) = pixel;
49
50         if pos.x < 0 || pos.y < 0 || pos.x >= self.width() as i32 || pos.y >= self.height() as i32 {
51             return Ok(());
52         }
53
54         self.buf[pos.y as usize][pos.x as usize] = swap(RawU16::from(color).into_inner());
55         Ok(())
56     }
57 }
58
59 const fn swap(inp: u16) -> u16 {
60     (inp & 0x00FF) << 8 |
61     (inp & 0xFF00) >> 8
62 }