viewport/
buffer.rs

1use {
2    crate::{
3        Bounds,
4        Cell,
5        Position,
6        Size,
7        Result
8    },
9};
10
11/// An intermediary between a caller writing data and the *real* terminal buffer.
12pub struct Buffer {
13    /// Boxed slice of `Cell`s to discourage trivial length mutation.
14    content: Box<[Cell]>,
15
16    /// The bounds of which this `Buffer` is constrained by.
17    pub bounds: Bounds,
18}
19
20impl std::fmt::Debug for Buffer {
21    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
22        for row in 0..self.bounds.dim.height() {
23            for col in 0..self.bounds.dim.width() {
24                let pos = Position(col, row);
25                write!(f, "{}    ", self.cell_at(pos).unwrap()).unwrap();
26            }
27            write!(f, "\n\n").unwrap();
28        }
29
30        Ok(())
31    }
32}
33
34impl Buffer {
35    /// Creates a `Buffer` filled with specified `Cell`s. 
36    pub fn filled_with(fill: Cell, bounds: Bounds) -> Self {
37        let content = vec![
38            fill; 
39            (bounds.dim.width() * bounds.dim.height()) as usize
40        ].into_boxed_slice();
41
42        Self { content, bounds }
43    }
44
45    /// Creates a blank `Buffer` within specified `Bounds`.
46    pub fn blank(bounds: Bounds) -> Self {
47        Self::filled_with(Cell::default(), bounds)
48    }
49
50    /// Returns the `Cell` at the specified `Position` if valid, and `Error` otherwise.
51    pub fn cell_at(&self, pos: Position) -> Result<&Cell> {
52        Ok(&self.content[self.bounds.index_of(pos)?])
53    }
54
55    /*pub fn line_at(&self, row: u16 -> Result<&[Cell]> {
56    }*/
57
58}