use std::fmt::Write as _;
use crate::error::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ColumnId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RowId(pub u32);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Column {
pub id: ColumnId,
pub header: String,
}
impl Column {
#[must_use]
pub fn new(id: u32, header: impl Into<String>) -> Self {
Self {
id: ColumnId(id),
header: header.into(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Row {
pub id: RowId,
pub cells: Vec<CellValue>,
}
impl Row {
#[must_use]
pub fn new(id: u32, cells: Vec<CellValue>) -> Self {
Self {
id: RowId(id),
cells,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum CellValue {
Empty,
Text(String),
Int(i64),
Float {
value: f64,
decimals: u8,
},
Redacted,
}
impl CellValue {
#[must_use]
pub fn text(s: impl Into<String>) -> Self {
Self::Text(s.into())
}
#[must_use]
pub fn int(v: i64) -> Self {
Self::Int(v)
}
#[must_use]
pub fn float(value: f64, decimals: u8) -> Self {
Self::Float { value, decimals }
}
pub fn write_paint(&self, out: &mut String, redacted_placeholder: &str) {
match self {
Self::Empty => {}
Self::Text(s) => out.push_str(s),
Self::Int(v) => {
let _ = write!(out, "{v}");
}
Self::Float { value, decimals } => {
let d = usize::from((*decimals).min(8));
let _ = write!(out, "{value:.d$}");
}
Self::Redacted => out.push_str(redacted_placeholder),
}
}
#[must_use]
pub fn paint_str(&self, redacted_placeholder: &str) -> String {
let mut s = String::new();
self.write_paint(&mut s, redacted_placeholder);
s
}
#[must_use]
pub fn copy_str(&self) -> Option<String> {
match self {
Self::Empty | Self::Redacted => None,
other => Some(other.paint_str("")),
}
}
#[must_use]
pub const fn is_datum(&self) -> bool {
!matches!(self, Self::Empty | Self::Redacted)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Grid {
pub columns: Vec<Column>,
pub rows: Vec<Row>,
}
impl Grid {
pub fn try_new(columns: Vec<Column>, rows: Vec<Row>) -> Result<Self, Error> {
if columns.is_empty() {
return Err(Error::InvalidGrid("at least one column is required"));
}
let n = columns.len();
for row in &rows {
if row.cells.len() != n {
return Err(Error::InvalidGrid("row width does not match columns"));
}
}
Ok(Self { columns, rows })
}
#[must_use]
pub fn debug_values(&self) -> Vec<String> {
let mut out = Vec::new();
for row in &self.rows {
for cell in &row.cells {
if let Some(s) = cell.copy_str() {
out.push(s);
}
}
}
out
}
}