1use std::fmt::Write as _;
4
5use crate::error::Error;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub struct ColumnId(pub u32);
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub struct RowId(pub u32);
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Column {
18 pub id: ColumnId,
20 pub header: String,
22}
23
24impl Column {
25 #[must_use]
27 pub fn new(id: u32, header: impl Into<String>) -> Self {
28 Self {
29 id: ColumnId(id),
30 header: header.into(),
31 }
32 }
33}
34
35#[derive(Debug, Clone, PartialEq)]
37pub struct Row {
38 pub id: RowId,
40 pub cells: Vec<CellValue>,
42}
43
44impl Row {
45 #[must_use]
47 pub fn new(id: u32, cells: Vec<CellValue>) -> Self {
48 Self {
49 id: RowId(id),
50 cells,
51 }
52 }
53}
54
55#[derive(Debug, Clone, PartialEq)]
57pub enum CellValue {
58 Empty,
60 Text(String),
62 Int(i64),
64 Float {
66 value: f64,
68 decimals: u8,
70 },
71 Redacted,
73}
74
75impl CellValue {
76 #[must_use]
78 pub fn text(s: impl Into<String>) -> Self {
79 Self::Text(s.into())
80 }
81
82 #[must_use]
84 pub fn int(v: i64) -> Self {
85 Self::Int(v)
86 }
87
88 #[must_use]
90 pub fn float(value: f64, decimals: u8) -> Self {
91 Self::Float { value, decimals }
92 }
93
94 pub fn write_paint(&self, out: &mut String, redacted_placeholder: &str) {
96 match self {
97 Self::Empty => {}
98 Self::Text(s) => out.push_str(s),
99 Self::Int(v) => {
100 let _ = write!(out, "{v}");
101 }
102 Self::Float { value, decimals } => {
103 let d = usize::from((*decimals).min(8));
104 let _ = write!(out, "{value:.d$}");
105 }
106 Self::Redacted => out.push_str(redacted_placeholder),
107 }
108 }
109
110 #[must_use]
112 pub fn paint_str(&self, redacted_placeholder: &str) -> String {
113 let mut s = String::new();
114 self.write_paint(&mut s, redacted_placeholder);
115 s
116 }
117
118 #[must_use]
120 pub fn copy_str(&self) -> Option<String> {
121 match self {
122 Self::Empty | Self::Redacted => None,
123 other => Some(other.paint_str("")),
124 }
125 }
126
127 #[must_use]
129 pub const fn is_datum(&self) -> bool {
130 !matches!(self, Self::Empty | Self::Redacted)
131 }
132}
133
134#[derive(Debug, Clone, PartialEq)]
136pub struct Grid {
137 pub columns: Vec<Column>,
139 pub rows: Vec<Row>,
141}
142
143impl Grid {
144 pub fn try_new(columns: Vec<Column>, rows: Vec<Row>) -> Result<Self, Error> {
151 if columns.is_empty() {
152 return Err(Error::InvalidGrid("at least one column is required"));
153 }
154 let n = columns.len();
155 for row in &rows {
156 if row.cells.len() != n {
157 return Err(Error::InvalidGrid("row width does not match columns"));
158 }
159 }
160 Ok(Self { columns, rows })
161 }
162
163 #[must_use]
165 pub fn debug_values(&self) -> Vec<String> {
166 let mut out = Vec::new();
167 for row in &self.rows {
168 for cell in &row.cells {
169 if let Some(s) = cell.copy_str() {
170 out.push(s);
171 }
172 }
173 }
174 out
175 }
176}