aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: d8509d543aa2cff5db14fcc456b3b69da12c8a4a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
mod input;
pub mod ui;

#[derive(Default)]
pub struct Calculator {
    stack: Vec<f64>,
    input_buffer: String,
}

impl Calculator {
    fn perform_operation(&mut self, op: Operator) {
        let rhs = match self.stack.pop() {
            Some(f) => f,
            None => {
                return;
            }
        };
        let lhs = match self.stack.pop() {
            Some(f) => f,
            None => {
                return;
            }
        };
        self.stack.push(match op {
            Operator::Add => lhs + rhs,
            Operator::Sub => lhs - rhs,
            Operator::Mul => lhs * rhs,
            Operator::Div => lhs / rhs,
            Operator::Exp => lhs.powf(rhs),
        });
    }
}

enum Operator {
    Add,
    Sub,
    Mul,
    Div,
    Exp,
}

impl Operator {
    fn parse(c: char) -> Result<Self, ParseOperatorError> {
        match c {
            '+' => Ok(Self::Add),
            '-' => Ok(Self::Sub),
            '*' => Ok(Self::Mul),
            '/' => Ok(Self::Div),
            '^' => Ok(Self::Exp),
            _ => Err(ParseOperatorError(c)),
        }
    }
}

struct ParseOperatorError(char);

enum Function {
    DSin, // Sine (degrees)
    DCos, // Cosine (degrees)
    DTan, // Tangent (degrees)
    RSin, // Sine (radians)
    RCos, // Cosing (radians)
    RTan, // Tangent (radians)
    Deg,  // Convert from radians to degrees.
    Rad,  // Convert from degrees to radians.
}

impl Function {
    fn parse(s: &str) -> Result<Self, ParseFunctionError> {
        match s {
            "dsin" => Ok(Self::DSin),
            "dcos" => Ok(Self::DCos),
            "dtan" => Ok(Self::DTan),
            "rsin" => Ok(Self::RSin),
            "rcos" => Ok(Self::RCos),
            "rtan" => Ok(Self::RTan),
            "deg" => Ok(Self::Deg),
            "rad" => Ok(Self::Rad),
            _ => Err(ParseFunctionError(s.to_string())),
        }
    }

    fn call_on(&self, f: f64) -> f64 {
        match self {
            Self::DSin => f.to_radians().sin(),
            Self::DCos => f.to_radians().cos(),
            Self::DTan => f.to_radians().tan(),
            Self::RSin => f.sin(),
            Self::RCos => f.cos(),
            Self::RTan => f.tan(),
            Self::Deg => f.to_degrees(),
            Self::Rad => f.to_radians(),
        }
    }
}

struct ParseFunctionError(String);

pub enum Signal {
    None,
    Exit,
}