1#![allow(clippy::missing_safety_doc)]
2
3use embedded_graphics::{prelude::PixelColor, primitives::Rectangle};
4
5pub fn fill_with_color<COL: PixelColor>(rect: &Rectangle, color: COL) {
6 unsafe extern "Rust" {
7 fn _ll_fill_with_color(x: u32, y: u32, w: u32, h: u32, color: u32);
8 }
9
10 let color_as_u32 = color_to_u32(&color);
11
12 let top_left = rect.top_left;
13 let size = rect.size;
14 unsafe {
15 _ll_fill_with_color(
16 top_left.x as u32,
17 top_left.y as u32,
18 size.width,
19 size.height,
20 color_as_u32,
21 )
22 };
23}
24pub fn fill_with_buffer(rect: &Rectangle, colors: *const u8) {
25 unsafe extern "Rust" {
26 fn _ll_fill_with_buffer(x: u32, y: u32, w: u32, h: u32, colors: *const u8);
27 }
28
29 let top_left = rect.top_left;
30 let size = rect.size;
31 unsafe {
32 _ll_fill_with_buffer(
33 top_left.x as u32,
34 top_left.y as u32,
35 size.width,
36 size.height,
37 colors,
38 )
39 };
40}
41
42fn color_to_u32<COL: PixelColor>(color: &COL) -> u32 {
43 let color_ptr = color as *const COL as *const u8;
44 let color_size = core::mem::size_of::<COL>();
45
46 match color_size {
47 1 => unsafe { *color_ptr as u32 },
48 2 => unsafe { *color_ptr.cast::<u16>() as u32 },
49 3 => {
50 let bytes = unsafe { core::ptr::read_unaligned(color_ptr.cast::<[u8; 3]>()) };
51 u32::from_be_bytes([0, bytes[0], bytes[1], bytes[2]])
52 }
53 4 => unsafe { *color_ptr.cast::<u32>() },
54 _ => 0xFFFFFFFF,
55 }
56}
57
58pub unsafe trait ImplFillRect {
59 unsafe fn fill_with_color(x: u32, y: u32, w: u32, h: u32, color: u32);
60 unsafe fn fill_with_buffer(x: u32, y: u32, w: u32, h: u32, colors: *const u8);
61}
62
63#[macro_export]
64macro_rules! set_impl_fill_rect {
65 ($t: ty) => {
66 #[unsafe(no_mangle)]
67 unsafe fn _ll_fill_with_color(x: u32, y: u32, w: u32, h: u32, color: u32) {
68 unsafe { <$t as $crate::fill_rect::ImplFillRect>::fill_with_color(x, y, w, h, color) }
69 }
70 #[unsafe(no_mangle)]
71 unsafe fn _ll_fill_with_buffer(x: u32, y: u32, w: u32, h: u32, colors: *const u8) {
72 unsafe { <$t as $crate::fill_rect::ImplFillRect>::fill_with_buffer(x, y, w, h, colors) }
73 }
74 };
75}