File: grid_builder.rs

package info (click to toggle)
rust-papergrid 0.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 640 kB
  • sloc: makefile: 4
file content (137 lines) | stat: -rw-r--r-- 3,468 bytes parent folder | download
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#![cfg(feature = "std")]
#![allow(unused_macros, unused_imports)]

use std::collections::HashMap;

use papergrid::{
    colors::NoColors,
    config::{pos, spanned::SpannedConfig, Borders, Position},
    dimension::{spanned::SpannedGridDimension, Dimension, Estimate},
    grid::iterable::Grid,
    records::{IterRecords, Records},
};

pub fn grid(rows: usize, cols: usize) -> GridBuilder {
    GridBuilder::new(rows, cols)
}

#[derive(Debug, Default, Clone)]
pub struct GridBuilder {
    size: (usize, usize),
    cfg: SpannedConfig,
    data: HashMap<Position, String>,
}

impl GridBuilder {
    pub fn new(rows: usize, cols: usize) -> Self {
        let mut cfg = SpannedConfig::default();
        cfg.set_borders(DEFAULT_BORDERS);

        Self {
            size: (rows, cols),
            cfg,
            ..Default::default()
        }
    }

    pub fn config(mut self, mut f: impl FnMut(&mut SpannedConfig)) -> Self {
        f(&mut self.cfg);
        self
    }

    pub fn data(
        mut self,
        data: impl IntoIterator<Item = impl IntoIterator<Item = impl Into<String>>>,
    ) -> Self {
        for (i, rows) in data.into_iter().enumerate() {
            for (j, text) in rows.into_iter().enumerate() {
                let text = text.into();
                self.data.insert(pos(i, j), text);
            }
        }

        self
    }

    pub fn change_cell(mut self, pos: Position, text: impl Into<String>) -> Self {
        self.data.insert(pos, text.into());
        self
    }

    pub fn build(self) -> String {
        let mut data = records(self.size.0, self.size.1);
        for (p, text) in self.data {
            data[p.row()][p.col()] = text;
        }

        let grid = build_grid(data, self.cfg, self.size);
        grid.to_string()
    }
}

fn build_grid(
    data: Vec<Vec<String>>,
    cfg: SpannedConfig,
    shape: (usize, usize),
) -> Grid<IterRecords<Vec<Vec<String>>>, SpannedGridDimension, SpannedConfig, NoColors> {
    let records = IterRecords::new(data, shape.1, Some(shape.0));

    let mut dims = SpannedGridDimension::default();
    dims.estimate(&records, &cfg);

    Grid::new(records, dims, cfg, NoColors)
}

fn records(rows: usize, cols: usize) -> Vec<Vec<String>> {
    let mut records = vec![vec![String::new(); cols]; rows];
    (0..rows).for_each(|row| {
        (0..cols).for_each(|col| {
            let text = format!("{row}-{col}");
            records[row][col] = text;
        });
    });

    records
}

pub const DEFAULT_BORDERS: Borders<char> = Borders {
    top: Some('-'),
    top_left: Some('+'),
    top_right: Some('+'),
    top_intersection: Some('+'),

    bottom: Some('-'),
    bottom_left: Some('+'),
    bottom_right: Some('+'),
    bottom_intersection: Some('+'),

    horizontal: Some('-'),
    left_intersection: Some('+'),
    right_intersection: Some('+'),

    left: Some('|'),
    right: Some('|'),
    vertical: Some('|'),

    intersection: Some('+'),
};

/// A [`Estimate`]or of a width for a [`Grid`].
///
/// [`Grid`]: crate::grid::iterable::Grid
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ConstantDimension(pub Vec<usize>, pub Vec<usize>);

impl Dimension for ConstantDimension {
    fn get_width(&self, column: usize) -> usize {
        self.0[column]
    }

    fn get_height(&self, row: usize) -> usize {
        self.1[row]
    }
}

impl<R> Estimate<R, SpannedConfig> for ConstantDimension {
    fn estimate(&mut self, _: R, _: &SpannedConfig) {}
}