diff options
Diffstat (limited to 'src/error.rs')
-rw-r--r-- | src/error.rs | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/error.rs b/src/error.rs index ec2b555..e05d4e3 100644 --- a/src/error.rs +++ b/src/error.rs | |||
@@ -2,11 +2,16 @@ | |||
2 | * Refer to LICENCE for more information. | 2 | * Refer to LICENCE for more information. |
3 | * */ | 3 | * */ |
4 | 4 | ||
5 | use std::iter::ExactSizeIterator; | ||
6 | |||
7 | use crate::lex; | ||
8 | |||
5 | #[derive(Debug)] | 9 | #[derive(Debug)] |
6 | pub enum CalcError { | 10 | pub enum CalcError { |
7 | Math(Math), | 11 | Math(Math), |
8 | Syntax(String), | 12 | Syntax(String), |
9 | Parser(String), | 13 | Parser(String), |
14 | Help, | ||
10 | } | 15 | } |
11 | 16 | ||
12 | #[derive(Debug)] | 17 | #[derive(Debug)] |
@@ -25,5 +30,42 @@ pub fn handler(e: CalcError) -> String { | |||
25 | }, | 30 | }, |
26 | CalcError::Syntax(details) => format!("Syntax Error: {}", details), | 31 | CalcError::Syntax(details) => format!("Syntax Error: {}", details), |
27 | CalcError::Parser(details) => format!("Parser 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'); | ||
28 | } | 68 | } |
69 | debug_assert_eq!(s.capacity(), s.len()); // check capacity calculation | ||
70 | s | ||
29 | } | 71 | } |