1use std::collections::BTreeMap;
4use std::sync::Arc;
5
6#[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]
11pub enum ColumnType {
17 Float,
19 Int,
21 Bool,
23 Text,
25 Date,
27 Time,
29 Category,
31}
32
33impl ColumnType {
34 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#[derive(Clone, Debug, PartialEq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
52#[non_exhaustive]
53pub enum ColumnValues {
59 Float(Arc<[f64]>),
61 Int(Arc<[i64]>),
63 Bool(Arc<[bool]>),
65 Text(Arc<[String]>),
67 Date(Arc<[i64]>),
69 Time(Arc<[i64]>),
71 Category(Arc<[String]>),
73}
74
75impl ColumnValues {
76 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 pub fn is_empty(&self) -> bool {
91 self.len() == 0
92 }
93
94 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#[derive(Clone, Debug, PartialEq)]
110#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
111#[non_exhaustive]
112pub struct Column {
118 pub name: String,
120 pub values: ColumnValues,
122 pub validity: Option<Vec<bool>>,
124 pub unit: Option<String>,
126 pub metadata: BTreeMap<String, String>,
128}
129
130impl Column {
131 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 pub fn floats(name: impl Into<String>, values: impl Into<Arc<[f64]>>) -> Self {
144 Self::new(name, ColumnValues::Float(values.into()))
145 }
146
147 pub fn ints(name: impl Into<String>, values: impl Into<Arc<[i64]>>) -> Self {
149 Self::new(name, ColumnValues::Int(values.into()))
150 }
151
152 pub fn bools(name: impl Into<String>, values: impl Into<Arc<[bool]>>) -> Self {
154 Self::new(name, ColumnValues::Bool(values.into()))
155 }
156
157 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 pub fn dates(name: impl Into<String>, values: impl Into<Arc<[i64]>>) -> Self {
165 Self::new(name, ColumnValues::Date(values.into()))
166 }
167
168 pub fn times(name: impl Into<String>, values: impl Into<Arc<[i64]>>) -> Self {
170 Self::new(name, ColumnValues::Time(values.into()))
171 }
172
173 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 pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
181 self.unit = Some(unit.into());
182 self
183 }
184
185 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 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 pub fn kind(&self) -> ColumnType {
199 self.values.kind()
200 }
201
202 pub fn len(&self) -> usize {
204 self.values.len()
205 }
206
207 pub fn is_empty(&self) -> bool {
209 self.len() == 0
210 }
211
212 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 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 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#[derive(Clone, Copy, Debug, PartialEq)]
272#[non_exhaustive]
273pub enum CellValue<'a> {
279 Null,
281 Float(f64),
283 Int(i64),
285 Bool(bool),
287 Text(&'a str),
289 Date(i64),
291 Time(i64),
293 Category(&'a str),
295}
296
297impl CellValue<'_> {
298 pub fn is_null(self) -> bool {
300 matches!(self, Self::Null)
301 }
302
303 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 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#[derive(Clone, Debug, PartialEq)]
332#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
333#[non_exhaustive]
334pub enum DataValue {
340 Null,
342 Float(f64),
344 Int(i64),
346 Bool(bool),
348 Text(String),
350 Date(i64),
352 Time(i64),
354}
355
356impl DataValue {
357 #[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 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 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}