diff options
Diffstat (limited to 'src/error.rs')
-rw-r--r-- | src/error.rs | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..e05d4e3 --- /dev/null +++ b/src/error.rs | |||
@@ -0,0 +1,71 @@ | |||
1 | /* Copyright (C) 2019 Akshay Oppiliappan <[email protected]> | ||
2 | * Refer to LICENCE for more information. | ||
3 | * */ | ||
4 | |||
5 | use std::iter::ExactSizeIterator; | ||
6 | |||
7 | use crate::lex; | ||
8 | |||
9 | #[derive(Debug)] | ||
10 | pub enum CalcError { | ||
11 | Math(Math), | ||
12 | Syntax(String), | ||
13 | Parser(String), | ||
14 | Help, | ||
15 | } | ||
16 | |||
17 | #[derive(Debug)] | ||
18 | pub enum Math { | ||
19 | DivideByZero, | ||
20 | OutOfBounds, | ||
21 | UnknownBase, | ||
22 | } | ||
23 | |||
24 | pub fn handler(e: CalcError) -> String { | ||
25 | match e { | ||
26 | CalcError::Math(math_err) => match math_err { | ||
27 | Math::DivideByZero => "Math Error: Divide by zero error!".to_string(), | ||
28 | Math::OutOfBounds => "Domain Error: Out of bounds!".to_string(), | ||
29 | Math::UnknownBase => "Base too large! Accepted ranges: 0 - 36".to_string(), | ||
30 | }, | ||
31 | CalcError::Syntax(details) => format!("Syntax Error: {}", details), | ||
32 | CalcError::Parser(details) => format!("Parser Error: {}", details), | ||
33 | CalcError::Help => { | ||
34 | // calculate max width but ideally this should be calculated once | ||
35 | let mut max_width = 79; // capped at 79 | ||
36 | if let Some((w, _)) = term_size::dimensions() { | ||
37 | if w < max_width { | ||
38 | max_width = w; | ||
39 | } | ||
40 | } | ||
41 | let operators: Vec<_> = lex::OPERATORS.keys().map(|c| c.to_string()).collect(); | ||
42 | format!( | ||
43 | "Constants\n{}\nFunctions\n{}\nOperators\n{}\n", | ||
44 | blocks(max_width, lex::CONSTANTS.keys().cloned()), | ||
45 | blocks(max_width, lex::FUNCTIONS.keys().cloned()), | ||
46 | operators.join(" ") | ||
47 | ) | ||
48 | } | ||
49 | } | ||
50 | } | ||
51 | |||
52 | /// Convert iterator into strings of chunks of 8 right padded with space. | ||
53 | fn blocks( | ||
54 | max_width: usize, | ||
55 | mut iter: impl Iterator<Item = &'static str> + ExactSizeIterator, | ||
56 | ) -> String { | ||
57 | // multiply by eight since we are formatting it into chunks of 8 | ||
58 | let items_per_line = max_width / 8; | ||
59 | let full_bytes = (iter.len() - iter.len() % items_per_line) * 8; | ||
60 | let part_bytes = iter.len() % items_per_line * 8; // leftovers | ||
61 | let n_newlines = iter.len() / items_per_line + if part_bytes > 0 { 1 } else { 0 }; | ||
62 | let mut s = String::with_capacity(full_bytes + part_bytes + n_newlines); | ||
63 | for _ in 0..n_newlines { | ||
64 | for item in iter.by_ref().take(items_per_line) { | ||
65 | s.extend(format!("{:>8}", item).chars()); | ||
66 | } | ||
67 | s.push('\n'); | ||
68 | } | ||
69 | debug_assert_eq!(s.capacity(), s.len()); // check capacity calculation | ||
70 | s | ||
71 | } | ||