Skip to main content

sealed_surface/
model.rs

1//! Tabular model. No host framework types.
2
3use std::fmt::Write as _;
4
5use crate::error::Error;
6
7/// Stable column identity (opaque to the host).
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub struct ColumnId(pub u32);
10
11/// Stable row identity (opaque to the host; not a grain id).
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub struct RowId(pub u32);
14
15/// Column schema. Header text is treated as schema, not a datum.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Column {
18    /// Opaque id.
19    pub id: ColumnId,
20    /// Header label painted as glyphs. Not copied in sealed mode.
21    pub header: String,
22}
23
24impl Column {
25    /// Construct a column.
26    #[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/// One data row.
36#[derive(Debug, Clone, PartialEq)]
37pub struct Row {
38    /// Opaque id.
39    pub id: RowId,
40    /// Cells aligned to [`Grid::columns`].
41    pub cells: Vec<CellValue>,
42}
43
44impl Row {
45    /// Construct a row. Length is checked in [`Grid::try_new`].
46    #[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/// A single cell. [`CellValue::Redacted`] must not carry a hidden scalar.
56#[derive(Debug, Clone, PartialEq)]
57pub enum CellValue {
58    /// Empty.
59    Empty,
60    /// UTF-8 text.
61    Text(String),
62    /// Integer.
63    Int(i64),
64    /// Fixed-decimal float for display.
65    Float {
66        /// Numeric value.
67        value: f64,
68        /// Digits after the decimal point (capped at 8 when painted).
69        decimals: u8,
70    },
71    /// Licensed-out. Original value must not be stored alongside this variant.
72    Redacted,
73}
74
75impl CellValue {
76    /// Text cell.
77    #[must_use]
78    pub fn text(s: impl Into<String>) -> Self {
79        Self::Text(s.into())
80    }
81
82    /// Integer cell.
83    #[must_use]
84    pub fn int(v: i64) -> Self {
85        Self::Int(v)
86    }
87
88    /// Float cell.
89    #[must_use]
90    pub fn float(value: f64, decimals: u8) -> Self {
91        Self::Float { value, decimals }
92    }
93
94    /// Append the paint glyphs to `out`. Caller owns the buffer (hot path).
95    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    /// Glyphs to paint. Hosts must not put this string in the DOM when sealed.
111    #[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    /// Copy/TSV payload. `None` for empty and redacted.
119    #[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    /// True when this cell still holds a licensed datum.
128    #[must_use]
129    pub const fn is_datum(&self) -> bool {
130        !matches!(self, Self::Empty | Self::Redacted)
131    }
132}
133
134/// Owned table.
135#[derive(Debug, Clone, PartialEq)]
136pub struct Grid {
137    /// Schema.
138    pub columns: Vec<Column>,
139    /// Data rows.
140    pub rows: Vec<Row>,
141}
142
143impl Grid {
144    /// Build a grid, rejecting ragged rows.
145    ///
146    /// # Errors
147    ///
148    /// Returns [`Error::InvalidGrid`] when there are no columns or a row length
149    /// does not match the column count.
150    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    /// Every licensed scalar as display text (for tests and lens proofs).
164    #[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}