xcell_types/string/
mod.rs

1use std::{any::type_name, collections::BTreeSet, fmt::Formatter};
2
3use serde::{
4    de::{MapAccess, Visitor},
5    Deserialize, Deserializer, Serialize,
6};
7
8use xcell_errors::{
9    for_3rd::{read_map_next_extra, read_map_next_value, DataType},
10    XResult,
11};
12
13use crate::{utils::syntax_error, XCellTyped, XCellValue};
14
15mod der;
16
17#[derive(Debug, Clone, Serialize)]
18pub struct StringDescription {
19    patterns: BTreeSet<String>,
20    pub default: String,
21}
22
23impl From<StringDescription> for XCellTyped {
24    fn from(value: StringDescription) -> Self {
25        Self::String(Box::new(value))
26    }
27}
28
29impl StringDescription {
30    pub fn matches_type(&self, s: &str) -> bool {
31        for pattern in &self.patterns {
32            if s.eq_ignore_ascii_case(pattern) {
33                return true;
34            }
35        }
36        false
37    }
38    pub fn add_pattern(&mut self, s: impl Into<String>) {
39        self.patterns.insert(s.into());
40    }
41    pub fn mut_pattern(&mut self) -> &mut BTreeSet<String> {
42        &mut self.patterns
43    }
44    pub fn parse_cell(&self, cell: &DataType) -> XResult<XCellValue> {
45        self.parse_value(cell).map(XCellValue::String)
46    }
47    pub fn parse_value(&self, cell: &DataType) -> XResult<String> {
48        match cell {
49            DataType::Int(v) => Ok(v.to_string()),
50            DataType::Float(v) => Ok(v.to_string()),
51            DataType::String(v) => Ok(v.to_string()),
52            DataType::Bool(v) => Ok(v.to_string()),
53            DataType::DateTime(v) => Ok(v.to_string()),
54            DataType::Empty => Ok(self.default.clone()),
55            DataType::Error(e) => syntax_error(format!("未知错误 {e}")),
56        }
57    }
58}