Skip to main content

graphics/
draw_buffer.rs

1use alloc::{vec, vec::Vec};
2use core::slice;
3
4use crate::{ColorRGB888, Point, RenderingColor};
5
6/// Alignment of the start of a draw buffer, in bytes. LVGL refuses buffers
7/// that are not aligned to `LV_DRAW_BUF_ALIGN` (`include/lv_conf.h`), which
8/// must not exceed this.
9pub const DRAW_BUFFER_ALIGNMENT: usize = 4;
10
11/// A unit of draw buffer storage: its alignment gives the buffer
12/// [`DRAW_BUFFER_ALIGNMENT`] whatever the rendering colour, whose own
13/// alignment may be smaller (2 bytes for RGB565).
14#[derive(Clone, Copy)]
15#[repr(C, align(4))]
16struct Storage([u8; DRAW_BUFFER_ALIGNMENT]);
17
18const _: () = {
19    assert!(align_of::<Storage>() == DRAW_BUFFER_ALIGNMENT);
20    assert!(align_of::<RenderingColor>() <= DRAW_BUFFER_ALIGNMENT);
21};
22
23/// An LVGL draw buffer: `len` pixels in the rendering colour format, aligned
24/// to [`DRAW_BUFFER_ALIGNMENT`].
25pub struct Buffer {
26    storage: Vec<Storage>,
27    pixels: usize,
28}
29
30impl AsRef<[RenderingColor]> for Buffer {
31    fn as_ref(&self) -> &[RenderingColor] {
32        // SAFETY: the storage is aligned for `RenderingColor` (checked above),
33        // holds at least `pixels` of them (`new`) and is initialised.
34        unsafe { slice::from_raw_parts(self.storage.as_ptr().cast(), self.pixels) }
35    }
36}
37
38impl Buffer {
39    pub fn new_from_resolution(resolution: &Point) -> Self {
40        let buffer_size = get_minimal_buffer_size(resolution);
41
42        Self::new(buffer_size)
43    }
44
45    /// A buffer of `buffer_size` black pixels.
46    pub fn new(buffer_size: usize) -> Self {
47        let bytes = buffer_size
48            .checked_mul(size_of::<RenderingColor>())
49            .expect("draw buffer size overflows");
50        let mut buffer = Self {
51            storage: vec![
52                Storage([0; DRAW_BUFFER_ALIGNMENT]);
53                bytes.div_ceil(DRAW_BUFFER_ALIGNMENT)
54            ],
55            pixels: buffer_size,
56        };
57        // SAFETY: as in `as_ref`, with the exclusive borrow of the storage.
58        let pixels: &mut [RenderingColor] =
59            unsafe { slice::from_raw_parts_mut(buffer.storage.as_mut_ptr().cast(), buffer.pixels) };
60        pixels.fill(ColorRGB888::new(0, 0, 0).into());
61        buffer
62    }
63
64    /// Number of pixels.
65    pub fn len(&self) -> usize {
66        self.pixels
67    }
68
69    pub fn is_empty(&self) -> bool {
70        self.pixels == 0
71    }
72
73    /// Size of the pixels in bytes, as LVGL renders into them.
74    pub fn size_in_bytes(&self) -> usize {
75        size_of_val(self.as_ref())
76    }
77
78    /// The start of the buffer, for LVGL to render into. It is aligned to
79    /// [`DRAW_BUFFER_ALIGNMENT`], and the allocation does not move when the
80    /// `Buffer` does.
81    pub fn as_mutable_pointer(&mut self) -> *mut RenderingColor {
82        self.storage.as_mut_ptr().cast()
83    }
84}
85
86pub const fn get_recommended_buffer_size(resolution: &Point) -> usize {
87    resolution.get_x() as usize * resolution.get_y() as usize
88}
89
90pub const fn get_minimal_buffer_size(resolution: &Point) -> usize {
91    if resolution.get_x() < resolution.get_y() {
92        resolution.get_y() as usize * resolution.get_y() as usize / 10
93    } else {
94        resolution.get_x() as usize * resolution.get_x() as usize / 10
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn views_cover_exactly_the_allocated_pixels() {
104        let buffer = Buffer::new(19_200);
105        assert_eq!(buffer.len(), 19_200);
106        // The buffer holds rendering pixels: a view typed with another colour
107        // size (such as 3-byte `ColorRGB888`) would read past or short of the
108        // allocation.
109        assert_eq!(
110            size_of_val(buffer.as_ref()),
111            19_200 * size_of::<RenderingColor>()
112        );
113        assert_eq!(buffer.size_in_bytes(), size_of_val(buffer.as_ref()));
114    }
115
116    #[test]
117    fn buffers_are_aligned_for_lvgl() {
118        // Odd sizes too: the allocation is rounded up to whole storage units.
119        for pixels in [1, 3, 240, 19_201] {
120            let mut buffer = Buffer::new(pixels);
121            assert!(
122                (buffer.as_mutable_pointer() as usize).is_multiple_of(DRAW_BUFFER_ALIGNMENT),
123                "{pixels} pixels"
124            );
125            assert_eq!(buffer.as_ref().len(), pixels);
126        }
127    }
128
129    #[test]
130    fn alignment_covers_lvgl_configuration() {
131        let configuration = include_str!("../include/lv_conf.h");
132        let alignment: usize = configuration
133            .lines()
134            .find_map(|line| line.trim().strip_prefix("#define LV_DRAW_BUF_ALIGN "))
135            .expect("LV_DRAW_BUF_ALIGN is defined")
136            .trim()
137            .parse()
138            .expect("LV_DRAW_BUF_ALIGN is a number");
139        assert!(alignment <= DRAW_BUFFER_ALIGNMENT);
140        assert!(DRAW_BUFFER_ALIGNMENT.is_multiple_of(alignment));
141    }
142}