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
//! [`Buffer`] trait represents an image.

use crate::pixel::Pixel;

/// A trait for represents an image.
pub trait Buffer<P: Pixel> {
    /// Get `(width, height)`.
    fn dimensions(&self) -> (u32, u32);

    /// Get pixel by `x` and `y`.
    fn get_pixel(&self, x: u32, y: u32) -> &P;

    /// Get mut pixel by `x` and `y`.
    fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut P;

    /// Put a pixel.
    fn put_pixel(&mut self, x: u32, y: u32, pixel: P);
}

/// 2D image buffer for manipulation.
#[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],
        }
    }
}