Skip to main content

crisol_core/data/
column.rs

1//! Typed columns, validity, and cell values.
2
3use std::collections::BTreeMap;
4use std::sync::Arc;
5
6/// The type of one column.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
10#[non_exhaustive]
11/// # Example
12///
13/// ```
14/// use crisol_core::data::ColumnType;
15/// ```
16pub enum ColumnType {
17    /// IEEE-754 double.
18    Float,
19    /// Signed 64-bit integer.
20    Int,
21    /// Boolean.
22    Bool,
23    /// UTF-8 text.
24    Text,
25    /// Days since the Unix epoch.
26    Date,
27    /// Nanoseconds since the Unix epoch.
28    Time,
29    /// A small set of text categories.
30    Category,
31}
32
33impl ColumnType {
34    /// A short name for a header or a schema.
35    pub const fn label(self) -> &'static str {
36        match self {
37            Self::Float => "float",
38            Self::Int => "int",
39            Self::Bool => "bool",
40            Self::Text => "text",
41            Self::Date => "date",
42            Self::Time => "time",
43            Self::Category => "category",
44        }
45    }
46}
47
48/// The storage of one column. Strings are shared with `Arc<[String]>`, so a clone is
49/// cheap and a derived column can keep the same backing storage.
50#[derive(Clone, Debug, PartialEq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
52#[non_exhaustive]
53/// # Example
54///
55/// ```
56/// use crisol_core::data::ColumnValues;
57/// ```
58pub enum ColumnValues {
59    /// Floats.
60    Float(Arc<[f64]>),
61    /// Integers.
62    Int(Arc<[i64]>),
63    /// Booleans.
64    Bool(Arc<[bool]>),
65    /// Text.
66    Text(Arc<[String]>),
67    /// Dates as days since the epoch.
68    Date(Arc<[i64]>),
69    /// Times as nanoseconds since the epoch.
70    Time(Arc<[i64]>),
71    /// Categories as text.
72    Category(Arc<[String]>),
73}
74
75impl ColumnValues {
76    /// The number of values.
77    pub fn len(&self) -> usize {
78        match self {
79            Self::Float(values) => values.len(),
80            Self::Int(values) => values.len(),
81            Self::Bool(values) => values.len(),
82            Self::Text(values) => values.len(),
83            Self::Date(values) => values.len(),
84            Self::Time(values) => values.len(),
85            Self::Category(values) => values.len(),
86        }
87    }
88
89    /// Whether the column has no values.
90    pub fn is_empty(&self) -> bool {
91        self.len() == 0
92    }
93
94    /// The type of the storage.
95    pub fn kind(&self) -> ColumnType {
96        match self {
97            Self::Float(_) => ColumnType::Float,
98            Self::Int(_) => ColumnType::Int,
99            Self::Bool(_) => ColumnType::Bool,
100            Self::Text(_) => ColumnType::Text,
101            Self::Date(_) => ColumnType::Date,
102            Self::Time(_) => ColumnType::Time,
103            Self::Category(_) => ColumnType::Category,
104        }
105    }
106}
107
108/// One column with its name, type, validity, and metadata.
109#[derive(Clone, Debug, PartialEq)]
110#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
111#[non_exhaustive]
112/// # Example
113///
114/// ```
115/// use crisol_core::data::Column;
116/// ```
117pub struct Column {
118    /// Column name.
119    pub name: String,
120    /// Storage and type.
121    pub values: ColumnValues,
122    /// A false entry marks a null cell. `None` means every cell is valid.
123    pub validity: Option<Vec<bool>>,
124    /// Unit text, such as `V` or `s`.
125    pub unit: Option<String>,
126    /// Free-form metadata (source, precision, labels).
127    pub metadata: BTreeMap<String, String>,
128}
129
130impl Column {
131    /// A column from storage.
132    pub fn new(name: impl Into<String>, values: ColumnValues) -> Self {
133        Self {
134            name: name.into(),
135            values,
136            validity: None,
137            unit: None,
138            metadata: BTreeMap::new(),
139        }
140    }
141
142    /// A float column.
143    pub fn floats(name: impl Into<String>, values: impl Into<Arc<[f64]>>) -> Self {
144        Self::new(name, ColumnValues::Float(values.into()))
145    }
146
147    /// An integer column.
148    pub fn ints(name: impl Into<String>, values: impl Into<Arc<[i64]>>) -> Self {
149        Self::new(name, ColumnValues::Int(values.into()))
150    }
151
152    /// A boolean column.
153    pub fn bools(name: impl Into<String>, values: impl Into<Arc<[bool]>>) -> Self {
154        Self::new(name, ColumnValues::Bool(values.into()))
155    }
156
157    /// A text column.
158    pub fn text(name: impl Into<String>, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
159        let values: Arc<[String]> = values.into_iter().map(Into::into).collect();
160        Self::new(name, ColumnValues::Text(values))
161    }
162
163    /// A date column (days since the Unix epoch).
164    pub fn dates(name: impl Into<String>, values: impl Into<Arc<[i64]>>) -> Self {
165        Self::new(name, ColumnValues::Date(values.into()))
166    }
167
168    /// A time column (nanoseconds since the Unix epoch).
169    pub fn times(name: impl Into<String>, values: impl Into<Arc<[i64]>>) -> Self {
170        Self::new(name, ColumnValues::Time(values.into()))
171    }
172
173    /// A category column.
174    pub fn categories(name: impl Into<String>, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
175        let values: Arc<[String]> = values.into_iter().map(Into::into).collect();
176        Self::new(name, ColumnValues::Category(values))
177    }
178
179    /// Set the unit.
180    pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
181        self.unit = Some(unit.into());
182        self
183    }
184
185    /// Add metadata.
186    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
187        self.metadata.insert(key.into(), value.into());
188        self
189    }
190
191    /// Set the validity mask. A shorter mask marks trailing cells invalid.
192    pub fn with_validity(mut self, validity: impl IntoIterator<Item = bool>) -> Self {
193        self.validity = Some(validity.into_iter().collect());
194        self
195    }
196
197    /// The type.
198    pub fn kind(&self) -> ColumnType {
199        self.values.kind()
200    }
201
202    /// Number of values.
203    pub fn len(&self) -> usize {
204        self.values.len()
205    }
206
207    /// Whether the column is empty.
208    pub fn is_empty(&self) -> bool {
209        self.len() == 0
210    }
211
212    /// Whether `row` has a value.
213    pub fn is_valid(&self, row: usize) -> bool {
214        self.validity
215            .as_ref()
216            .is_none_or(|validity| validity.get(row).copied().unwrap_or(false))
217    }
218
219    /// A borrowed cell value.
220    pub fn cell(&self, row: usize) -> CellValue<'_> {
221        if !self.is_valid(row) {
222            return CellValue::Null;
223        }
224        match &self.values {
225            ColumnValues::Float(values) => values
226                .get(row)
227                .map_or(CellValue::Null, |value| CellValue::Float(*value)),
228            ColumnValues::Int(values) => values.get(row).map_or(CellValue::Null, |value| CellValue::Int(*value)),
229            ColumnValues::Bool(values) => values.get(row).map_or(CellValue::Null, |value| CellValue::Bool(*value)),
230            ColumnValues::Text(values) => values
231                .get(row)
232                .map_or(CellValue::Null, |value| CellValue::Text(value.as_str())),
233            ColumnValues::Date(values) => values.get(row).map_or(CellValue::Null, |value| CellValue::Date(*value)),
234            ColumnValues::Time(values) => values.get(row).map_or(CellValue::Null, |value| CellValue::Time(*value)),
235            ColumnValues::Category(values) => values
236                .get(row)
237                .map_or(CellValue::Null, |value| CellValue::Category(value.as_str())),
238        }
239    }
240
241    /// A copy of rows in `range`.
242    pub fn slice(&self, range: std::ops::Range<usize>) -> Self {
243        let start = range.start.min(self.len());
244        let end = range.end.min(self.len()).max(start);
245        let values = match &self.values {
246            ColumnValues::Float(values) => ColumnValues::Float(Arc::from(values.get(start..end).unwrap_or_default())),
247            ColumnValues::Int(values) => ColumnValues::Int(Arc::from(values.get(start..end).unwrap_or_default())),
248            ColumnValues::Bool(values) => ColumnValues::Bool(Arc::from(values.get(start..end).unwrap_or_default())),
249            ColumnValues::Text(values) => ColumnValues::Text(Arc::from(values.get(start..end).unwrap_or_default())),
250            ColumnValues::Date(values) => ColumnValues::Date(Arc::from(values.get(start..end).unwrap_or_default())),
251            ColumnValues::Time(values) => ColumnValues::Time(Arc::from(values.get(start..end).unwrap_or_default())),
252            ColumnValues::Category(values) => {
253                ColumnValues::Category(Arc::from(values.get(start..end).unwrap_or_default()))
254            }
255        };
256        Self {
257            name: self.name.clone(),
258            values,
259            validity: self.validity.as_ref().map(|validity| {
260                (start..end)
261                    .map(|row| validity.get(row).copied().unwrap_or(false))
262                    .collect()
263            }),
264            unit: self.unit.clone(),
265            metadata: self.metadata.clone(),
266        }
267    }
268}
269
270/// A borrowed cell value.
271#[derive(Clone, Copy, Debug, PartialEq)]
272#[non_exhaustive]
273/// # Example
274///
275/// ```
276/// use crisol_core::data::CellValue;
277/// ```
278pub enum CellValue<'a> {
279    /// No value.
280    Null,
281    /// Float.
282    Float(f64),
283    /// Integer.
284    Int(i64),
285    /// Boolean.
286    Bool(bool),
287    /// Text.
288    Text(&'a str),
289    /// Date.
290    Date(i64),
291    /// Time.
292    Time(i64),
293    /// Category.
294    Category(&'a str),
295}
296
297impl CellValue<'_> {
298    /// Whether the cell is null.
299    pub fn is_null(self) -> bool {
300        matches!(self, Self::Null)
301    }
302
303    /// A text representation for a grid or a copy.
304    pub fn to_text(self) -> String {
305        match self {
306            Self::Null => String::new(),
307            Self::Float(value) => value.to_string(),
308            Self::Int(value) => value.to_string(),
309            Self::Bool(value) => value.to_string(),
310            Self::Text(value) | Self::Category(value) => value.to_owned(),
311            Self::Date(value) => format!("date:{value}"),
312            Self::Time(value) => format!("time:{value}"),
313        }
314    }
315
316    /// An owned value.
317    pub fn to_owned_value(self) -> DataValue {
318        match self {
319            Self::Null => DataValue::Null,
320            Self::Float(value) => DataValue::Float(value),
321            Self::Int(value) => DataValue::Int(value),
322            Self::Bool(value) => DataValue::Bool(value),
323            Self::Text(value) | Self::Category(value) => DataValue::Text(value.to_owned()),
324            Self::Date(value) => DataValue::Date(value),
325            Self::Time(value) => DataValue::Time(value),
326        }
327    }
328}
329
330/// An owned value, used by the query evaluator and streaming buffers.
331#[derive(Clone, Debug, PartialEq)]
332#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
333#[non_exhaustive]
334/// # Example
335///
336/// ```
337/// use crisol_core::data::DataValue;
338/// ```
339pub enum DataValue {
340    /// No value.
341    Null,
342    /// Float.
343    Float(f64),
344    /// Integer.
345    Int(i64),
346    /// Boolean.
347    Bool(bool),
348    /// Text.
349    Text(String),
350    /// Date.
351    Date(i64),
352    /// Time.
353    Time(i64),
354}
355
356impl DataValue {
357    /// The value as plain text, for a column that mixes types.
358    #[cfg(any(feature = "workbook", feature = "sqlite"))]
359    pub(crate) fn display_text(&self) -> String {
360        match self {
361            Self::Null => String::new(),
362            Self::Float(value) => value.to_string(),
363            Self::Int(value) | Self::Date(value) | Self::Time(value) => value.to_string(),
364            Self::Bool(value) => value.to_string(),
365            Self::Text(value) => value.clone(),
366        }
367    }
368
369    /// A numeric value as an f64, when it is numeric.
370    pub fn as_f64(&self) -> Option<f64> {
371        match self {
372            Self::Float(value) => Some(*value),
373            Self::Int(value) => Some(*value as f64),
374            Self::Date(value) | Self::Time(value) => Some(*value as f64),
375            _ => None,
376        }
377    }
378
379    /// A text value, for text comparisons.
380    pub fn as_text(&self) -> Option<&str> {
381        match self {
382            Self::Text(value) => Some(value),
383            _ => None,
384        }
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    #[test]
393    fn columns_carry_types_units_and_validity() {
394        let column = Column::floats("voltage", vec![1.0, f64::NAN, 3.0])
395            .with_unit("V")
396            .with_validity([true, false, true]);
397        assert_eq!(column.kind(), ColumnType::Float);
398        assert_eq!(column.unit.as_deref(), Some("V"));
399        assert!(column.is_valid(0));
400        assert!(!column.is_valid(1));
401        assert_eq!(column.cell(2), CellValue::Float(3.0));
402        assert_eq!(column.cell(1), CellValue::Null);
403    }
404
405    #[test]
406    fn slices_keep_metadata_and_validity() {
407        let column = Column::ints("n", vec![0, 1, 2, 3]).with_validity([true, true, false, true]);
408        let slice = column.slice(1..3);
409        assert_eq!(slice.len(), 2);
410        assert_eq!(slice.cell(0), CellValue::Int(1));
411        assert_eq!(slice.cell(1), CellValue::Null);
412    }
413
414    #[test]
415    fn owned_values_round_trip() {
416        let column = Column::text("name", ["a", "b"]);
417        assert_eq!(column.cell(0).to_owned_value(), DataValue::Text("a".to_owned()));
418        assert_eq!(DataValue::Int(2).as_f64(), Some(2.0));
419    }
420}