factory.rs (2053B)
1 use crate::{ 2 TokenFactory, 3 number::{NumberFormat, ScientificNumber, StandardNumber}, 4 operator::{Operator, ScientificOperator, StandardOperator}, 5 token::Function, 6 }; 7 8 #[derive(Clone)] 9 pub struct StandardFactory; 10 11 impl TokenFactory for StandardFactory { 12 type Number = StandardNumber; 13 type Operator = StandardOperator; 14 15 fn create_number(&self, s: &str) -> Result<Self::Number, String> { 16 s.parse::<f64>() 17 .map(StandardNumber) 18 .map_err(|_| format!("Invalid number: {}", s)) 19 } 20 21 fn create_operator(&self, s: &str) -> Result<Self::Operator, String> { 22 match s { 23 "+" => Ok(StandardOperator(Operator::Add)), 24 "-" => Ok(StandardOperator(Operator::Subtract)), 25 "*" => Ok(StandardOperator(Operator::Multiply)), 26 "/" => Ok(StandardOperator(Operator::Divide)), 27 _ => Err(format!("Invalid operator: {}", s)), 28 } 29 } 30 } 31 32 pub struct ScientificFactory; 33 34 impl TokenFactory for ScientificFactory { 35 type Number = ScientificNumber; 36 type Operator = ScientificOperator; 37 38 fn create_number(&self, s: &str) -> Result<Self::Number, String> { 39 // Handle both scientific and standard notation 40 if s.contains('e') || s.contains('E') { 41 s.parse::<f64>().map(|value| ScientificNumber { 42 value, 43 format: NumberFormat::Scientific, 44 }) 45 } else { 46 s.parse::<f64>().map(|value| ScientificNumber { 47 value, 48 format: NumberFormat::Decimal, 49 }) 50 } 51 .map_err(|_| format!("Invalid number: {}", s)) 52 } 53 54 fn create_operator(&self, s: &str) -> Result<Self::Operator, String> { 55 // Scientific mode support more operators 56 match s { 57 "sin" => Ok(ScientificOperator::Function(Function::Sin)), 58 "cos" => Ok(ScientificOperator::Function(Function::Cos)), 59 // ...other scientifc operators 60 _ => Err(format!("Invalid operator: {}", s)), 61 } 62 } 63 }