Skip to main content

simple_cli_calculator/
lib.rs

1//! # calculator
2//!
3//! `calculator` is a very simple calculator library
4//! that implements the four basic op's and the power operator.
5//! Do not use unless you want certain doom.
6
7#[derive(Debug, PartialEq)]
8/// Four basic operations as an enum!
9pub enum Operations {
10    Add,
11    Subtract,
12    Multiply,
13    Divide,
14    Power,
15}
16
17/// Calculation struct used for everything.
18pub struct Calculation {
19    pub num1: f64,
20    pub num2: f64,
21    pub operation: Operations,
22}
23
24impl Calculation {
25    /// Converts a string to a calculation struct, assumes standard notation
26    ///
27    /// # Example
28    /// ```
29    /// let mut calc = calculator::Calculation::from_string("3 + 6").unwrap();
30    /// ```
31    /// Now you can use any of the functions from calculator!
32    /// # Panics
33    /// Never
34    /// # Errors
35    /// Returns error when input isn't long enough or a conversion error occurs
36    /// # Safety
37    /// This fn is safe AF.
38    pub fn from_string(input: &str) -> Result<Self, &str> {
39        let mut inputstring = input.split_whitespace();
40
41        let num1: f64 = match inputstring.next() {
42            Some(num) => match num.parse::<f64>() {
43                Ok(res) => res,
44                Err(_) => return Err("First number is invalid."),
45            },
46            _ => return Err("Input a Number."),
47        };
48
49        let operator: char = match inputstring.next() {
50            Some(char) => match char.char_indices().next() {
51                Some((_f, char)) => char,
52                None => {
53                    return Err(
54                        "If you're seeing this, i have no clue, let the author know what u typed.",
55                    );
56                }
57            },
58            _ => return Err("Input an operator."),
59        };
60
61        let num2: f64 = match inputstring.next() {
62            Some(num) => match num.parse::<f64>() {
63                Ok(res) => res,
64                Err(_) => return Err("Second number is invalid."),
65            },
66            _ => return Err("Input a second number."),
67        };
68
69        Self::new(num1, num2, operator)
70    }
71
72    pub fn from_rpn(input: &str) -> Result<Self, &str> {
73        let mut inputstring = input.split_whitespace();
74
75        let num1: f64 = match inputstring.next() {
76            Some(num) => match num.parse::<f64>() {
77                Ok(res) => res,
78                Err(_) => return Err("First number is invalid."),
79            },
80            _ => return Err("Input a Number."),
81        };
82
83        let num2: f64 = match inputstring.next() {
84            Some(num) => match num.parse::<f64>() {
85                Ok(res) => res,
86                Err(_) => return Err("Second number is invalid."),
87            },
88            _ => return Err("Input a second number."),
89        };
90
91        let operator: char = match inputstring.next() {
92            Some(char) => match char.char_indices().next() {
93                Some((_f, char)) => char,
94                None => {
95                    return Err(
96                        "If you're seeing this, i have no clue, let the author know what u typed.",
97                    );
98                }
99            },
100            _ => return Err("Input an operator."),
101        };
102
103        Self::new(num1, num2, operator)
104    }
105
106    pub fn new(num1: f64, num2: f64, op: char) -> Result<Self, &'static str> {
107        Ok(Calculation {
108            num1,
109            num2,
110            operation: match op {
111                '+' => Operations::Add,
112                '-' => Operations::Subtract,
113                '*' => Operations::Multiply,
114                '/' => Operations::Divide,
115                '^' => Operations::Power,
116                _ => return Err("Unknown operation, try + - * / ^"),
117            },
118        })
119    }
120
121    pub fn calculate_result(&self) -> f64 {
122        match self.operation {
123            Operations::Add => self.num1 + self.num2,
124            Operations::Divide => self.num1 / self.num2,
125            Operations::Multiply => self.num1 * self.num2,
126            Operations::Power => self.num1.powf(self.num2),
127            Operations::Subtract => self.num1 - self.num2,
128        }
129    }
130}