Skip to main content

classicube_sys\bitmap/
owned_bitmap.rs

1use core::borrow::Borrow;
2
3use crate::{
4    Math_NextPowOf2,
5    bindings::{Bitmap, BitmapCol},
6    std_types::{Vec, c_int, vec},
7};
8
9pub struct OwnedBitmap {
10    bitmap: Bitmap,
11
12    #[allow(dead_code)]
13    pixels: Vec<BitmapCol>,
14}
15
16impl OwnedBitmap {
17    /// # Panics
18    ///
19    /// Panics if `width` or `height` is negative.
20    #[must_use]
21    pub fn new(width: c_int, height: c_int, color: BitmapCol) -> Self {
22        let w = usize::try_from(width).expect("bitmap width must be non-negative");
23        let h = usize::try_from(height).expect("bitmap height must be non-negative");
24        let mut pixels = vec![color; w * h];
25        let scan0 = pixels.as_mut_ptr();
26
27        Self {
28            pixels,
29            bitmap: Bitmap {
30                scan0,
31                width,
32                height,
33            },
34        }
35    }
36
37    #[must_use]
38    pub fn new_cleared(width: c_int, height: c_int) -> Self {
39        Self::new(width, height, 0x0000_0000)
40    }
41
42    #[must_use]
43    pub fn new_pow_of_2(width: c_int, height: c_int, color: BitmapCol) -> OwnedBitmap {
44        let width = Math_NextPowOf2(width);
45        let height = Math_NextPowOf2(height);
46
47        Self::new(width, height, color)
48    }
49
50    #[must_use]
51    pub fn new_pow_of_2_cleared(width: c_int, height: c_int) -> OwnedBitmap {
52        Self::new_pow_of_2(width, height, 0x0000_0000)
53    }
54
55    #[must_use]
56    pub fn as_bitmap(&self) -> &Bitmap {
57        &self.bitmap
58    }
59
60    pub fn as_bitmap_mut(&mut self) -> &mut Bitmap {
61        &mut self.bitmap
62    }
63
64    /// # Safety
65    ///
66    /// The `OwnedBitmap` needs to live longer than the `Bitmap` return here.
67    #[must_use]
68    pub unsafe fn get_bitmap(&self) -> Bitmap {
69        Bitmap { ..self.bitmap }
70    }
71}
72
73impl Borrow<Bitmap> for OwnedBitmap {
74    fn borrow(&self) -> &Bitmap {
75        self.as_bitmap()
76    }
77}