sealed-surface 0.2.0

Non-extractable data surface: tables and timeseries as glyphs, never DOM text
Documentation
//! Tabular model. No host framework types.

use std::fmt::Write as _;

use crate::error::Error;

/// Stable column identity (opaque to the host).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ColumnId(pub u32);

/// Stable row identity (opaque to the host; not a grain id).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RowId(pub u32);

/// Column schema. Header text is treated as schema, not a datum.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Column {
    /// Opaque id.
    pub id: ColumnId,
    /// Header label painted as glyphs. Not copied in sealed mode.
    pub header: String,
}

impl Column {
    /// Construct a column.
    #[must_use]
    pub fn new(id: u32, header: impl Into<String>) -> Self {
        Self {
            id: ColumnId(id),
            header: header.into(),
        }
    }
}

/// One data row.
#[derive(Debug, Clone, PartialEq)]
pub struct Row {
    /// Opaque id.
    pub id: RowId,
    /// Cells aligned to [`Grid::columns`].
    pub cells: Vec<CellValue>,
}

impl Row {
    /// Construct a row. Length is checked in [`Grid::try_new`].
    #[must_use]
    pub fn new(id: u32, cells: Vec<CellValue>) -> Self {
        Self {
            id: RowId(id),
            cells,
        }
    }
}

/// A single cell. [`CellValue::Redacted`] must not carry a hidden scalar.
#[derive(Debug, Clone, PartialEq)]
pub enum CellValue {
    /// Empty.
    Empty,
    /// UTF-8 text.
    Text(String),
    /// Integer.
    Int(i64),
    /// Fixed-decimal float for display.
    Float {
        /// Numeric value.
        value: f64,
        /// Digits after the decimal point (capped at 8 when painted).
        decimals: u8,
    },
    /// Licensed-out. Original value must not be stored alongside this variant.
    Redacted,
}

impl CellValue {
    /// Text cell.
    #[must_use]
    pub fn text(s: impl Into<String>) -> Self {
        Self::Text(s.into())
    }

    /// Integer cell.
    #[must_use]
    pub fn int(v: i64) -> Self {
        Self::Int(v)
    }

    /// Float cell.
    #[must_use]
    pub fn float(value: f64, decimals: u8) -> Self {
        Self::Float { value, decimals }
    }

    /// Append the paint glyphs to `out`. Caller owns the buffer (hot path).
    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),
        }
    }

    /// Glyphs to paint. Hosts must not put this string in the DOM when sealed.
    #[must_use]
    pub fn paint_str(&self, redacted_placeholder: &str) -> String {
        let mut s = String::new();
        self.write_paint(&mut s, redacted_placeholder);
        s
    }

    /// Copy/TSV payload. `None` for empty and redacted.
    #[must_use]
    pub fn copy_str(&self) -> Option<String> {
        match self {
            Self::Empty | Self::Redacted => None,
            other => Some(other.paint_str("")),
        }
    }

    /// True when this cell still holds a licensed datum.
    #[must_use]
    pub const fn is_datum(&self) -> bool {
        !matches!(self, Self::Empty | Self::Redacted)
    }
}

/// Owned table.
#[derive(Debug, Clone, PartialEq)]
pub struct Grid {
    /// Schema.
    pub columns: Vec<Column>,
    /// Data rows.
    pub rows: Vec<Row>,
}

impl Grid {
    /// Build a grid, rejecting ragged rows.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidGrid`] when there are no columns or a row length
    /// does not match the column count.
    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 })
    }

    /// Every licensed scalar as display text (for tests and lens proofs).
    #[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
    }
}