aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2023-02-01 13:33:35 -0330
committerSam Anthony <sam@samanthony.xyz>2023-02-01 13:33:35 -0330
commit7587f9798bfd4c2d4cf17e673643727caa329548 (patch)
tree951281ad01d108433dc93e9845efc9f19b598507
parentebf889219bbba702df0e7756c78268eb5437c30a (diff)
downloadpfc-7587f9798bfd4c2d4cf17e673643727caa329548.zip
input handling
-rw-r--r--src/lib.rs21
-rw-r--r--src/main.rs48
2 files changed, 60 insertions, 9 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 527ddb8..e08796d 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,13 +1,22 @@
pub mod ui;
-enum Token {
- Operand(f64),
- Operator(Operator),
-}
-
-enum Operator {
+pub enum Operator {
Add,
Sub,
Mul,
Div,
}
+
+impl Operator {
+ pub fn parse(c: char) -> Result<Self, ParseOperatorError> {
+ match c {
+ '+' => Ok(Self::Add),
+ '-' => Ok(Self::Sub),
+ '*' => Ok(Self::Mul),
+ '/' => Ok(Self::Div),
+ _ => Err(ParseOperatorError(c)),
+ }
+ }
+}
+
+pub struct ParseOperatorError(char);
diff --git a/src/main.rs b/src/main.rs
index d6bf2d9..83017cb 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -7,7 +7,7 @@ use tui::{
Frame, Terminal,
};
-use pfc::ui;
+use pfc::{ui, Operator};
enum Signal {
None,
@@ -15,7 +15,10 @@ enum Signal {
}
#[derive(Default)]
-struct App {}
+struct App {
+ stack: Vec<f64>,
+ input_buffer: String,
+}
impl App {
fn handle_input(&mut self, key: KeyEvent) -> Signal {
@@ -30,6 +33,24 @@ impl App {
KeyCode::Char('q') => {
return Signal::Exit;
}
+ KeyCode::Char(c) => {
+ if c.is_ascii_digit() {
+ self.input_buffer.push(c);
+ } else if c == '.' && !self.input_buffer.contains('.') {
+ self.input_buffer.push(c);
+ } else if let Ok(op) = Operator::parse(c) {
+ self.stack.push(self.input_buffer.parse::<f64>().unwrap());
+ self.input_buffer = String::new();
+ self.perform_operation(op);
+ }
+ }
+ KeyCode::Enter => {
+ self.stack.push(self.input_buffer.parse::<f64>().unwrap());
+ self.input_buffer = String::new();
+ }
+ KeyCode::Backspace => {
+ self.input_buffer.pop();
+ }
_ => {}
},
_ => {}
@@ -42,7 +63,28 @@ impl App {
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(100)].as_ref())
.split(f.size());
- f.render_widget(Paragraph::new("test"), chunks[0]);
+ f.render_widget(Paragraph::new(self.input_buffer.as_str()), chunks[0]);
+ }
+
+ 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;
+ }
+ };
+ match op {
+ Operator::Add => self.stack.push(lhs + rhs),
+ Operator::Sub => self.stack.push(lhs - rhs),
+ Operator::Mul => self.stack.push(lhs * rhs),
+ Operator::Div => self.stack.push(lhs / rhs),
+ }
}
}