aboutsummaryrefslogtreecommitdiff
path: root/evc/src/frame.rs
blob: 16acb96a3cfe732c38de1c48092072f9df3d3d99 (plain)
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
55
56
57
58
59
60
61
62
63
64
use crate::{
    pixel::Pixel,
    ser::{Sink, Source},
    view::View,
};
use std::ops::{Index, IndexMut};

pub struct Frame {
    pub size: (usize, usize),
    buffer: Vec<Vec<Pixel>>,
}

impl Frame {
    pub fn new(size: (usize, usize)) -> Self {
        Self {
            size,
            buffer: (0..size.0)
                .map(|_| (0..size.1).map(|_| Pixel::default()).collect())
                .collect(),
        }
    }
    pub fn read(source: &mut impl Source, size: (usize, usize)) -> anyhow::Result<Self> {
        let mut frame = Frame::new(size);
        for y in 0..size.1 {
            for x in 0..size.0 {
                let pixel = source.get::<Pixel>()?;
                frame[(x, y)] = pixel;
            }
        }
        Ok(frame)
    }
    pub fn write(&self, sink: &mut impl Sink) -> anyhow::Result<()> {
        for y in 0..self.size.1 {
            for x in 0..self.size.0 {
                sink.put(self[(x, y)])?;
            }
        }
        Ok(())
    }
    pub fn view<'a>(&'a self, offset: (usize, usize), size: (usize, usize)) -> View<&'a Frame> {
        View::new(self, offset, size)
    }
    pub fn view_mut<'a>(
        &'a mut self,
        offset: (usize, usize),
        size: (usize, usize),
    ) -> View<&'a mut Frame> {
        View::new(self, offset, size)
    }
}

impl Index<(usize, usize)> for Frame {
    type Output = Pixel;
    #[inline]
    fn index(&self, (x, y): (usize, usize)) -> &Self::Output {
        &self.buffer[x][y]
    }
}
impl IndexMut<(usize, usize)> for Frame {
    #[inline]
    fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Self::Output {
        &mut self.buffer[x][y]
    }
}