aboutsummaryrefslogtreecommitdiff
path: root/src/error/mod.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/error/mod.rs')
-rw-r--r--src/error/mod.rs42
1 files changed, 42 insertions, 0 deletions
diff --git a/src/error/mod.rs b/src/error/mod.rs
index ec2b555..307ca31 100644
--- a/src/error/mod.rs
+++ b/src/error/mod.rs
@@ -2,11 +2,16 @@
2 * Refer to LICENCE for more information. 2 * Refer to LICENCE for more information.
3 * */ 3 * */
4 4
5use std::iter::ExactSizeIterator;
6
7use crate::lex;
8
5#[derive(Debug)] 9#[derive(Debug)]
6pub enum CalcError { 10pub 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 => format!(
34 "Constants\n{}\nFunctions\n{}\nOperators\n{}\n",
35 blocks(lex::CONSTANTS.keys().cloned()),
36 blocks(lex::FUNCTIONS.keys().cloned()),
37 {
38 let l: Vec<_> = lex::OPERATORS.keys().map(|c| c.to_string()).collect();
39 l.join(" ")
40 }
41 ),
42 }
43}
44
45/// Convert iterator into strings of chunks of 8 right padded with space.
46fn blocks(mut iter: impl Iterator<Item = &'static str> + ExactSizeIterator) -> String {
47 // calculate max width but ideally this should be calculated once
48 let mut max_width = 79; // capped at 79
49 if let Ok(s) = std::env::var("COLUMNS") {
50 if let Ok(n) = s.parse() {
51 if n < max_width {
52 max_width = n;
53 }
54 }
55 }
56
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}