Skip to main content

display_driver/
area.rs

1/// A simple struct representing a rectangular area.
2#[derive(Debug, Clone, Copy)]
3pub struct Area {
4    /// Start X coordinate.
5    pub x: u16,
6    /// Start Y coordinate.
7    pub y: u16,
8    /// Width of the area being written.
9    pub w: u16,
10    /// Height of the area being written.
11    pub h: u16,
12}
13
14impl Area {
15    pub const fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
16        Self { x, y, w, h }
17    }
18
19    pub const fn from_origin(w: u16, h: u16) -> Self {
20        Self { x: 0, y: 0, w, h }
21    }
22
23    pub const fn from_origin_size(size: (u16, u16)) -> Self {
24        Self {
25            x: 0,
26            y: 0,
27            w: size.0,
28            h: size.1,
29        }
30    }
31
32    pub const fn position(&self) -> (u16, u16) {
33        (self.x, self.y)
34    }
35
36    pub const fn total_pixels(&self) -> usize {
37        self.w as usize * self.h as usize
38    }
39
40    pub const fn bottom_right(&self) -> (u16, u16) {
41        debug_assert!(self.w > 0 && self.h > 0);
42        (self.x + self.w - 1, self.y + self.h - 1)
43    }
44}
45
46// #[derive(Clone, Copy, Debug)]
47// pub enum AreaOrSize {
48//     Area(Area),
49//     // WidthAndHeight(u16, u16),
50//     Size(usize)
51// }
52
53// impl AreaOrSize {
54//     pub fn size(&self) -> usize {
55//         match *self {
56//             AreaOrSize::Area(area) => area.size(),
57//             // AreaOrSize::WidthAndHeight(w, h) => w as usize * h as usize,
58//             AreaOrSize::Size(size) => size,
59//         }
60//     }
61// }
62
63#[cfg(feature = "embedded-graphics")]
64mod eg_impls {
65    use super::*;
66    use embedded_graphics_core::prelude::*;
67    use embedded_graphics_core::primitives::Rectangle;
68
69    impl From<Rectangle> for Area {
70        fn from(value: Rectangle) -> Self {
71            Area {
72                x: value.top_left.x as _,
73                y: value.top_left.y as _,
74                w: value.size.width as _,
75                h: value.size.height as _,
76            }
77        }
78    }
79
80    impl From<Area> for Rectangle {
81        fn from(value: Area) -> Self {
82            Rectangle {
83                top_left: Point::new(value.x as _, value.y as _),
84                size: Size::new(value.w as _, value.h as _),
85            }
86        }
87    }
88}