1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use crate::pixel::Pixel;
pub trait Buffer<P: Pixel> {
fn dimensions(&self) -> (u32, u32);
fn get_pixel(&self, x: u32, y: u32) -> &P;
fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut P;
fn put_pixel(&mut self, x: u32, y: u32, pixel: P);
}
#[derive(Clone)]
pub struct GenericBuffer<P: Pixel> {
pub(crate) width: u32,
pub(crate) height: u32,
pub(crate) buffer: Vec<P>,
}
impl<P: Pixel> Buffer<P> for GenericBuffer<P> {
fn dimensions(&self) -> (u32, u32) {
(self.width, self.height)
}
fn get_pixel(&self, x: u32, y: u32) -> &P {
&self.buffer[(y * self.width + x) as usize]
}
fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut P {
&mut self.buffer[(y * self.width + x) as usize]
}
fn put_pixel(&mut self, x: u32, y: u32, pixel: P) {
self.buffer[(y * self.width + x) as usize] = pixel;
}
}
impl<P: Pixel> GenericBuffer<P> {
pub fn from_pixel(width: u32, height: u32, pixel: P) -> Self {
GenericBuffer {
width,
height,
buffer: vec![pixel; (width * height) as usize],
}
}
}