xcell_types/enumerate/
mod.rs

1use crate::{utils::syntax_error, IntegerKind, XCellTyped, XCellValue};
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4use xcell_errors::{
5    for_3rd::{BigInt, DataType},
6    XResult,
7};
8
9#[derive(Clone, Debug, Default, Serialize, Deserialize)]
10pub struct EnumerateDescription {
11    pub integer: IntegerKind,
12    pub typing: String,
13    pub default: String,
14    pub mapping: BTreeMap<String, BigInt>,
15}
16
17impl From<EnumerateDescription> for XCellTyped {
18    fn from(value: EnumerateDescription) -> Self {
19        Self::Enumerate(Box::new(value))
20    }
21}
22
23impl EnumerateDescription {
24    pub fn new<S>(typing: S) -> Self
25    where
26        S: Into<String>,
27    {
28        Self { integer: Default::default(), typing: typing.into(), default: "".to_string(), mapping: Default::default() }
29    }
30    pub fn parse_cell(&self, cell: &DataType) -> XResult<XCellValue> {
31        self.parse_value(cell).map(XCellValue::Enumerate)
32    }
33    fn parse_value(&self, cell: &DataType) -> XResult<String> {
34        match cell {
35            DataType::Int(v) => Ok(v.to_string()),
36            DataType::Float(v) => Ok(v.to_string()),
37            DataType::String(v) => Ok(v.to_string()),
38            DataType::Bool(v) => Ok(v.to_string()),
39            DataType::DateTime(v) => Ok(v.to_string()),
40            DataType::Empty => Ok(self.default.clone()),
41            DataType::Error(e) => syntax_error(format!("未知错误 {e}")),
42        }
43    }
44}
45
46impl XCellTyped {
47    pub fn as_enumerate(&self) -> Option<&EnumerateDescription> {
48        match self {
49            XCellTyped::Enumerate(e) => Some(e),
50            _ => None,
51        }
52    }
53    pub fn mut_enumerate(&mut self) -> Option<&mut EnumerateDescription> {
54        match self {
55            XCellTyped::Enumerate(e) => Some(e),
56            _ => None,
57        }
58    }
59    pub fn is_enumerate(&self) -> bool {
60        self.as_enumerate().is_some()
61    }
62}