diff --git a/src/calc.rs b/src/calc.rs index 07487c1..a09f7a4 100644 --- a/src/calc.rs +++ b/src/calc.rs @@ -260,9 +260,19 @@ impl<'a> Calculator<'a> { ',' => self.display_mode = CalculatorDisplayMode::Default(Some(',')), ' ' => self.display_mode = CalculatorDisplayMode::Default(Some(' ')), 's' => self.display_mode = CalculatorDisplayMode::Scientific(3), - 'S' => self.display_mode = CalculatorDisplayMode::Scientific(self.pop_usize()?), + 'S' => { + let precision = self.checked_get(0)? as usize; + if precision >= 20 { + return Err(CalculatorError::PrecisionTooHigh); + } + self.display_mode = CalculatorDisplayMode::Scientific(self.pop_usize()?) + } 'e' => self.display_mode = CalculatorDisplayMode::Engineering(3), 'E' => { + let precision = self.checked_get(0)? as usize; + if precision >= 20 { + return Err(CalculatorError::PrecisionTooHigh); + } self.display_mode = CalculatorDisplayMode::Engineering(self.pop_usize()?) } _ => return Err(CalculatorError::NoSuchSetting(c)), diff --git a/src/calc/errors.rs b/src/calc/errors.rs index 192204c..2006e7d 100644 --- a/src/calc/errors.rs +++ b/src/calc/errors.rs @@ -14,6 +14,7 @@ pub enum CalculatorError { NoSuchSetting(char), RecursiveMacro(char), ParseError, + PrecisionTooHigh, } impl fmt::Display for CalculatorError { @@ -32,6 +33,7 @@ impl fmt::Display for CalculatorError { CalculatorError::NoSuchSetting(c) => write!(f, "No such setting '{}'", c), CalculatorError::RecursiveMacro(c) => write!(f, "Recursive macro '{}'", c), CalculatorError::ParseError => write!(f, "Parse error"), + CalculatorError::PrecisionTooHigh => write!(f, "Precision too high"), } } } diff --git a/src/main.rs b/src/main.rs index cb8143c..69f1553 100644 --- a/src/main.rs +++ b/src/main.rs @@ -390,11 +390,12 @@ fn draw_clippy_rect(c: ClippyRectangle, f: &mut Frame String { let mut ret = format!("{:.precision$E}", f, precision = precision); let exp = ret.split_off(ret.find('E').unwrap_or(0)); - let (pow_sign, exp) = if exp.starts_with("E-") { - ('-', &exp[2..]) + let (pow_sign, exp) = if let Some(stripped) = exp.strip_prefix("E-") { + ('-', stripped) } else { ('+', &exp[1..]) }; + let sign = if !ret.starts_with('-') { " " } else { "" }; format!( "{:>2}: {}{}E{}{:0>pad$}", @@ -435,7 +436,7 @@ fn fmt_scientific(i: usize, f: f64, precision: usize) -> String { fn fmt_separated(i: usize, f: f64, sep: char) -> String { let mut ret = f.to_string(); let start = if ret.starts_with('-') { 1 } else { 0 }; - let end = ret.find('.').unwrap_or(ret.len()); + let end = ret.find('.').unwrap_or_else(|| ret.len()); for i in 0..((end - start - 1).div_euclid(3)) { ret.insert(end - (i + 1) * 3, sep); }