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
|
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::{Calculator, Function, Operator, Signal};
impl Calculator {
pub fn handle_input(&mut self, key: KeyEvent) -> Signal {
match key.modifiers {
KeyModifiers::CONTROL => match key.code {
KeyCode::Char('c') => {
return Signal::Exit;
}
_ => {}
},
KeyModifiers::SHIFT => match key.code {
KeyCode::Char('D') => self.clear(),
_ => {}
},
KeyModifiers::NONE => match key.code {
KeyCode::Char('q') => {
return Signal::Exit;
}
KeyCode::Char('j' | 'k') => self.swap(),
KeyCode::Char('d') => {
self.input_buffer = String::new();
}
KeyCode::Char(c) => self.push_to_buffer(c),
KeyCode::Backspace => {
self.input_buffer.pop();
}
KeyCode::Enter if self.input_buffer.len() > 0 => {
if let Ok(func) = Function::parse(&self.input_buffer) {
if let Some(f) = self.stack.pop() {
self.stack.push(func.call_on(f));
}
} else {
self.stack.push(self.input_buffer.parse::<f64>().unwrap());
}
self.input_buffer = String::new();
}
_ => {}
},
_ => {}
}
return Signal::None;
}
// Push a character into the input buffer. If the character is an operator,
// the particular operation is performed.
fn push_to_buffer(&mut self, c: char) {
if c == '.' && !self.input_buffer.contains('.') {
if self.input_buffer.len() == 0 {
self.input_buffer.push('0');
}
self.input_buffer.push(c);
} else if let Ok(op) = Operator::parse(c) {
if self.input_buffer.len() > 0 {
self.stack.push(self.input_buffer.parse::<f64>().unwrap());
}
self.input_buffer = String::new();
self.perform_operation(op);
} else {
self.input_buffer.push(c);
}
}
// Swap the bottom of the stack and the input buffer. If the input buffer
// is empty, this simply pops from the stack into the input buffer.
fn swap(&mut self) {
if let Some(f) = self.stack.pop() {
if self.input_buffer.len() > 0 {
self.stack.push(self.input_buffer.parse::<f64>().unwrap());
}
self.input_buffer = format!("{}", f);
}
}
// Clear stack and input buffer.
fn clear(&mut self) {
self.input_buffer = String::new();
self.stack = Vec::new();
}
}
|