xcell_types/boolean/
mod.rs1use std::{any::type_name, collections::BTreeSet, fmt::Formatter};
2
3use serde::{
4 de::{MapAccess, Visitor},
5 Deserialize, Deserializer, Serialize,
6};
7
8use serde_types::OneOrMany;
9use xcell_errors::{
10 for_3rd::{read_map_next_extra, read_map_next_value, DataType},
11 XResult,
12};
13
14use crate::utils::{syntax_error, type_mismatch};
15
16use super::*;
17
18mod der;
19
20#[derive(Debug, Clone, Serialize)]
21pub struct BooleanDescription {
22 pub accept: BTreeSet<String>,
23 pub reject: BTreeSet<String>,
24 pub default: bool,
25}
26
27impl From<BooleanDescription> for XCellTyped {
28 fn from(value: BooleanDescription) -> Self {
29 Self::Boolean(Box::new(value))
30 }
31}
32
33impl BooleanDescription {
34 pub fn new(default: bool) -> BooleanDescription {
35 Self { default, ..Self::default() }
36 }
37
38 pub fn parse_cell(&self, cell: &DataType) -> XResult<XCellValue> {
39 self.parse_value(cell).map(XCellValue::Boolean)
40 }
41 fn parse_value(&self, cell: &DataType) -> XResult<bool> {
42 match cell {
43 DataType::String(s) => {
44 if self.accept.contains(s.to_ascii_lowercase().trim()) {
45 Ok(true)
46 }
47 else if self.reject.contains(s.to_ascii_lowercase().trim()) {
48 Ok(false)
49 }
50 else {
51 syntax_error(format!("{} 无法解析为 bool 类型", s))
52 }
53 }
54 DataType::Bool(v) => Ok(*v),
55 DataType::Empty => Ok(self.default),
56 DataType::Error(e) => syntax_error(format!("未知错误 {e}")),
57 _ => type_mismatch("Boolean", cell),
58 }
59 }
60}